From 9762901cba48761ec2078b8a18c8cec82d9144b6 Mon Sep 17 00:00:00 2001 From: Daniel Ziegenberg Date: Sun, 10 Mar 2024 04:04:37 +0100 Subject: [PATCH 1/4] MDL-79678 libraries: Update OTPHP to 11.3.0 Notable changes: - The OTPHP library requires now at least PHP 8.1. - The OTPHP library now relies on the MBString extension. This extension is now a required dependency. - The OTPHP library now utilizes a PSR-20: clock. Signed-off-by: Daniel Ziegenberg --- .../totp/extlib/OTPHP/InternalClock.php | 19 ++ .../tool/mfa/factor/totp/extlib/OTPHP/OTP.php | 178 +++++------ .../factor/totp/extlib/OTPHP/OTPInterface.php | 127 ++++---- .../totp/extlib/OTPHP/ParameterTrait.php | 201 +++++-------- .../mfa/factor/totp/extlib/OTPHP/TOTP.php | 278 +++++++++--------- .../totp/extlib/OTPHP/TOTPInterface.php | 46 ++- .../factor/totp/extlib/OTPHP/composer.json | 41 ++- .../totp/extlib/OTPHP/readme_moodle.txt | 18 +- admin/tool/mfa/factor/totp/thirdpartylibs.xml | 2 +- 9 files changed, 467 insertions(+), 443 deletions(-) create mode 100644 admin/tool/mfa/factor/totp/extlib/OTPHP/InternalClock.php diff --git a/admin/tool/mfa/factor/totp/extlib/OTPHP/InternalClock.php b/admin/tool/mfa/factor/totp/extlib/OTPHP/InternalClock.php new file mode 100644 index 00000000000..8be469318e6 --- /dev/null +++ b/admin/tool/mfa/factor/totp/extlib/OTPHP/InternalClock.php @@ -0,0 +1,19 @@ +setSecret($secret); - $this->setDigest($digest); - $this->setDigits($digits); - } + private const DEFAULT_SECRET_SIZE = 64; /** - * {@inheritdoc} + * @param non-empty-string $secret */ - public function getQrCodeUri(string $uri = 'https://chart.googleapis.com/chart?chs=200x200&chld=M|0&cht=qr&chl={PROVISIONING_URI}', string $placeholder = '{PROVISIONING_URI}'): string + protected function __construct(string $secret) + { + $this->setSecret($secret); + } + + public function getQrCodeUri(string $uri, string $placeholder): string { $provisioning_uri = urlencode($this->getProvisioningUri()); @@ -45,38 +36,52 @@ abstract class OTP implements OTPInterface } /** - * @param int $input + * @param 0|positive-int $input + */ + public function at(int $input): string + { + return $this->generateOTP($input); + } + + /** + * @return non-empty-string + */ + final protected static function generateSecret(): string + { + return Base32::encodeUpper(random_bytes(self::DEFAULT_SECRET_SIZE)); + } + + /** + * The OTP at the specified input. * - * @return string The OTP at the specified input + * @param 0|positive-int $input + * + * @return non-empty-string */ protected function generateOTP(int $input): string { - $hash = hash_hmac($this->getDigest(), $this->intToByteString($input), $this->getDecodedSecret()); - $hmac = []; - foreach (str_split($hash, 2) as $hex) { - $hmac[] = hexdec($hex); - } - $offset = $hmac[count($hmac) - 1] & 0xF; - $code = ($hmac[$offset + 0] & 0x7F) << 24 | ($hmac[$offset + 1] & 0xFF) << 16 | ($hmac[$offset + 2] & 0xFF) << 8 | ($hmac[$offset + 3] & 0xFF); - $otp = $code % pow(10, $this->getDigits()); + $hash = hash_hmac($this->getDigest(), $this->intToByteString($input), $this->getDecodedSecret(), true); + $unpacked = unpack('C*', $hash); + $unpacked !== false || throw new InvalidArgumentException('Invalid data.'); + $hmac = array_values($unpacked); + + $offset = ($hmac[count($hmac) - 1] & 0xF); + $code = ($hmac[$offset] & 0x7F) << 24 | ($hmac[$offset + 1] & 0xFF) << 16 | ($hmac[$offset + 2] & 0xFF) << 8 | ($hmac[$offset + 3] & 0xFF); + $otp = $code % (10 ** $this->getDigits()); return str_pad((string) $otp, $this->getDigits(), '0', STR_PAD_LEFT); } /** - * {@inheritdoc} + * @param array $options */ - public function at(int $timestamp): string + protected function filterOptions(array &$options): void { - return $this->generateOTP($timestamp); - } - - /** - * @param array $options - */ - protected function filterOptions(array &$options) - { - foreach (['algorithm' => 'sha1', 'period' => 30, 'digits' => 6] as $key => $default) { + foreach ([ + 'algorithm' => 'sha1', + 'period' => 30, + 'digits' => 6, + ] as $key => $default) { if (isset($options[$key]) && $default === $options[$key]) { unset($options[$key]); } @@ -86,61 +91,60 @@ abstract class OTP implements OTPInterface } /** - * @param string $type - * @param array $options + * @param non-empty-string $type + * @param array $options * - * @return string + * @return non-empty-string */ protected function generateURI(string $type, array $options): string { $label = $this->getLabel(); - Assertion::string($label, 'The label is not set.'); - Assertion::false($this->hasColon($label), 'Label must not contain a colon.'); - $options = array_merge($options, $this->getParameters()); + is_string($label) || throw new InvalidArgumentException('The label is not set.'); + $this->hasColon($label) === false || throw new InvalidArgumentException('Label must not contain a colon.'); + $options = [...$options, ...$this->getParameters()]; $this->filterOptions($options); $params = str_replace(['+', '%7E'], ['%20', '~'], http_build_query($options, '', '&')); - return sprintf('otpauth://%s/%s?%s', $type, rawurlencode((null !== $this->getIssuer() ? $this->getIssuer().':' : '').$label), $params); + return sprintf( + 'otpauth://%s/%s?%s', + $type, + rawurlencode(($this->getIssuer() !== null ? $this->getIssuer() . ':' : '') . $label), + $params + ); } /** - * @return string - */ - private function getDecodedSecret(): string - { - try { - $secret = Base32::decodeUpper($this->getSecret()); - } catch (\Exception $e) { - throw new \RuntimeException('Unable to decode the secret. Is it correctly base32 encoded?'); - } - - return $secret; - } - - /** - * @param int $int - * - * @return string - */ - private function intToByteString(int $int): string - { - $result = []; - while (0 !== $int) { - $result[] = chr($int & 0xFF); - $int >>= 8; - } - - return str_pad(implode(array_reverse($result)), 8, "\000", STR_PAD_LEFT); - } - - /** - * @param string $safe - * @param string $user - * - * @return bool + * @param non-empty-string $safe + * @param non-empty-string $user */ protected function compareOTP(string $safe, string $user): bool { return hash_equals($safe, $user); } + + /** + * @return non-empty-string + */ + private function getDecodedSecret(): string + { + try { + $decoded = Base32::decodeUpper($this->getSecret()); + } catch (Exception) { + throw new RuntimeException('Unable to decode the secret. Is it correctly base32 encoded?'); + } + assert($decoded !== ''); + + return $decoded; + } + + private function intToByteString(int $int): string + { + $result = []; + while ($int !== 0) { + $result[] = chr($int & 0xFF); + $int >>= 8; + } + + return str_pad(implode('', array_reverse($result)), 8, "\000", STR_PAD_LEFT); + } } diff --git a/admin/tool/mfa/factor/totp/extlib/OTPHP/OTPInterface.php b/admin/tool/mfa/factor/totp/extlib/OTPHP/OTPInterface.php index 7dfc16d8c08..39ce4acd025 100644 --- a/admin/tool/mfa/factor/totp/extlib/OTPHP/OTPInterface.php +++ b/admin/tool/mfa/factor/totp/extlib/OTPHP/OTPInterface.php @@ -1,123 +1,132 @@ */ public function getParameters(): array; /** - * @param string $parameter - * @param mixed $value - * - * @return $this + * @param non-empty-string $parameter */ - public function setParameter(string $parameter, $value); + public function setParameter(string $parameter, mixed $value): void; /** - * @return string Get the provisioning URI + * Get the provisioning URI. + * + * @return non-empty-string */ public function getProvisioningUri(): string; /** - * @param string $uri The Uri of the QRCode generator with all parameters. By default the Googgle Chart API is used. This Uri MUST contain a placeholder that will be replaced by the method. - * @param string $placeholder The placeholder to be replaced in the QR Code generator URI. Default value is {PROVISIONING_URI}. + * Get the provisioning URI. * - * @return string Get the provisioning URI + * @param non-empty-string $uri The Uri of the QRCode generator with all parameters. This Uri MUST contain a placeholder that will be replaced by the method. + * @param non-empty-string $placeholder the placeholder to be replaced in the QR Code generator URI */ - public function getQrCodeUri(string $uri = 'https://chart.googleapis.com/chart?chs=200x200&chld=M|0&cht=qr&chl={PROVISIONING_URI}', string $placeholder = '{PROVISIONING_URI}'): string; + public function getQrCodeUri(string $uri, string $placeholder): string; } diff --git a/admin/tool/mfa/factor/totp/extlib/OTPHP/ParameterTrait.php b/admin/tool/mfa/factor/totp/extlib/OTPHP/ParameterTrait.php index 49d65c98a70..dc92861c4bc 100644 --- a/admin/tool/mfa/factor/totp/extlib/OTPHP/ParameterTrait.php +++ b/admin/tool/mfa/factor/totp/extlib/OTPHP/ParameterTrait.php @@ -2,228 +2,181 @@ declare(strict_types=1); -/* - * The MIT License (MIT) - * - * Copyright (c) 2014-2018 Spomky-Labs - * - * This software may be modified and distributed under the terms - * of the MIT license. See the LICENSE file for details. - */ - namespace OTPHP; -use Assert\Assertion; -use ParagonIE\ConstantTime\Base32; +use InvalidArgumentException; +use function array_key_exists; +use function assert; +use function in_array; +use function is_int; +use function is_string; trait ParameterTrait { /** - * @var array + * @var array */ - private $parameters = []; + private array $parameters = []; /** - * @var string|null + * @var non-empty-string|null */ - private $issuer = null; + private null|string $issuer = null; /** - * @var string|null + * @var non-empty-string|null */ - private $label = null; + private null|string $label = null; + + private bool $issuer_included_as_parameter = true; /** - * @var bool - */ - private $issuer_included_as_parameter = true; - - /** - * @return array + * @return array */ public function getParameters(): array { $parameters = $this->parameters; - if (null !== $this->getIssuer() && $this->isIssuerIncludedAsParameter() === true) { + if ($this->getIssuer() !== null && $this->isIssuerIncludedAsParameter() === true) { $parameters['issuer'] = $this->getIssuer(); } return $parameters; } - /** - * @return string - */ public function getSecret(): string { - return $this->getParameter('secret'); + $value = $this->getParameter('secret'); + (is_string($value) && $value !== '') || throw new InvalidArgumentException('Invalid "secret" parameter.'); + + return $value; } - /** - * @param string|null $secret - */ - private function setSecret($secret) - { - $this->setParameter('secret', $secret); - } - - /** - * @return string|null - */ - public function getLabel() + public function getLabel(): null|string { return $this->label; } - /** - * @param string $label - */ - public function setLabel(string $label) + public function setLabel(string $label): void { $this->setParameter('label', $label); } - /** - * @return string|null - */ - public function getIssuer() + public function getIssuer(): null|string { return $this->issuer; } - /** - * @param string $issuer - */ - public function setIssuer(string $issuer) + public function setIssuer(string $issuer): void { $this->setParameter('issuer', $issuer); } - /** - * @return bool - */ public function isIssuerIncludedAsParameter(): bool { return $this->issuer_included_as_parameter; } - /** - * @param bool $issuer_included_as_parameter - */ - public function setIssuerIncludedAsParameter(bool $issuer_included_as_parameter) + public function setIssuerIncludedAsParameter(bool $issuer_included_as_parameter): void { $this->issuer_included_as_parameter = $issuer_included_as_parameter; } - /** - * @return int - */ public function getDigits(): int { - return $this->getParameter('digits'); + $value = $this->getParameter('digits'); + (is_int($value) && $value > 0) || throw new InvalidArgumentException('Invalid "digits" parameter.'); + + return $value; } - /** - * @param int $digits - */ - private function setDigits(int $digits) - { - $this->setParameter('digits', $digits); - } - - /** - * @return string - */ public function getDigest(): string { - return $this->getParameter('algorithm'); + $value = $this->getParameter('algorithm'); + (is_string($value) && $value !== '') || throw new InvalidArgumentException('Invalid "algorithm" parameter.'); + + return $value; } - /** - * @param string $digest - */ - private function setDigest(string $digest) - { - $this->setParameter('algorithm', $digest); - } - - /** - * @param string $parameter - * - * @return bool - */ public function hasParameter(string $parameter): bool { return array_key_exists($parameter, $this->parameters); } - /** - * @param string $parameter - * - * @return mixed - */ - public function getParameter(string $parameter) + public function getParameter(string $parameter): mixed { if ($this->hasParameter($parameter)) { return $this->getParameters()[$parameter]; } - throw new \InvalidArgumentException(sprintf('Parameter "%s" does not exist', $parameter)); + throw new InvalidArgumentException(sprintf('Parameter "%s" does not exist', $parameter)); } - /** - * @param string $parameter - * @param mixed $value - */ - public function setParameter(string $parameter, $value) + public function setParameter(string $parameter, mixed $value): void { $map = $this->getParameterMap(); - if (true === array_key_exists($parameter, $map)) { + if (array_key_exists($parameter, $map) === true) { $callback = $map[$parameter]; $value = $callback($value); } if (property_exists($this, $parameter)) { - $this->$parameter = $value; + $this->{$parameter} = $value; } else { $this->parameters[$parameter] = $value; } } + public function setSecret(string $secret): void + { + $this->setParameter('secret', $secret); + } + + public function setDigits(int $digits): void + { + $this->setParameter('digits', $digits); + } + + public function setDigest(string $digest): void + { + $this->setParameter('algorithm', $digest); + } + /** - * @return array + * @return array */ protected function getParameterMap(): array { return [ - 'label' => function ($value) { - Assertion::false($this->hasColon($value), 'Label must not contain a colon.'); + 'label' => function (string $value): string { + assert($value !== ''); + $this->hasColon($value) === false || throw new InvalidArgumentException( + 'Label must not contain a colon.' + ); return $value; }, - 'secret' => function ($value) { - if (null === $value) { - $value = Base32::encodeUpper(random_bytes(64)); - } - $value = trim(strtoupper($value), '='); + 'secret' => static fn (string $value): string => mb_strtoupper(trim($value, '=')), + 'algorithm' => static function (string $value): string { + $value = mb_strtolower($value); + in_array($value, hash_algos(), true) || throw new InvalidArgumentException(sprintf( + 'The "%s" digest is not supported.', + $value + )); return $value; }, - 'algorithm' => function ($value) { - $value = strtolower($value); - Assertion::inArray($value, hash_algos(), sprintf('The "%s" digest is not supported.', $value)); - - return $value; - }, - 'digits' => function ($value) { - Assertion::greaterThan($value, 0, 'Digits must be at least 1.'); + 'digits' => static function ($value): int { + $value > 0 || throw new InvalidArgumentException('Digits must be at least 1.'); return (int) $value; }, - 'issuer' => function ($value) { - Assertion::false($this->hasColon($value), 'Issuer must not contain a colon.'); + 'issuer' => function (string $value): string { + assert($value !== ''); + $this->hasColon($value) === false || throw new InvalidArgumentException( + 'Issuer must not contain a colon.' + ); return $value; }, @@ -231,15 +184,13 @@ trait ParameterTrait } /** - * @param string $value - * - * @return bool + * @param non-empty-string $value */ - private function hasColon($value) + private function hasColon(string $value): bool { $colons = [':', '%3A', '%3a']; foreach ($colons as $colon) { - if (false !== strpos($value, $colon)) { + if (str_contains($value, $colon)) { return true; } } diff --git a/admin/tool/mfa/factor/totp/extlib/OTPHP/TOTP.php b/admin/tool/mfa/factor/totp/extlib/OTPHP/TOTP.php index b350b104adf..035e04f950e 100644 --- a/admin/tool/mfa/factor/totp/extlib/OTPHP/TOTP.php +++ b/admin/tool/mfa/factor/totp/extlib/OTPHP/TOTP.php @@ -2,216 +2,214 @@ declare(strict_types=1); -/* - * The MIT License (MIT) - * - * Copyright (c) 2014-2018 Spomky-Labs - * - * This software may be modified and distributed under the terms - * of the MIT license. See the LICENSE file for details. - */ - namespace OTPHP; -use Assert\Assertion; +use InvalidArgumentException; +use Psr\Clock\ClockInterface; +use function assert; +use function is_int; +/** + * @see \OTPHP\Test\TOTPTest + */ final class TOTP extends OTP implements TOTPInterface { - /** - * TOTP constructor. - * - * @param string|null $secret - * @param int $period - * @param string $digest - * @param int $digits - * @param int $epoch - */ - protected function __construct($secret, int $period, string $digest, int $digits, int $epoch = 0) + private readonly ClockInterface $clock; + + public function __construct(string $secret, ?ClockInterface $clock = null) { - parent::__construct($secret, $digest, $digits); - $this->setPeriod($period); - $this->setEpoch($epoch); + parent::__construct($secret); + if ($clock === null) { + trigger_deprecation( + 'spomky-labs/otphp', + '11.3.0', + 'The parameter "$clock" will become mandatory in 12.0.0. Please set a valid PSR Clock implementation instead of "null".' + ); + $clock = new InternalClock(); + } + + $this->clock = $clock; } - /** - * TOTP constructor. - * - * @param string|null $secret - * @param int $period - * @param string $digest - * @param int $digits - * @param int $epoch - * - * @return self - */ - public static function create($secret = null, int $period = 30, string $digest = 'sha1', int $digits = 6, int $epoch = 0): self - { - return new self($secret, $period, $digest, $digits, $epoch); + public static function create( + null|string $secret = null, + int $period = self::DEFAULT_PERIOD, + string $digest = self::DEFAULT_DIGEST, + int $digits = self::DEFAULT_DIGITS, + int $epoch = self::DEFAULT_EPOCH, + ?ClockInterface $clock = null + ): self { + $totp = $secret !== null + ? self::createFromSecret($secret, $clock) + : self::generate($clock) + ; + $totp->setPeriod($period); + $totp->setDigest($digest); + $totp->setDigits($digits); + $totp->setEpoch($epoch); + + return $totp; } - /** - * @param int $period - */ - protected function setPeriod(int $period) + public static function createFromSecret(string $secret, ?ClockInterface $clock = null): self { - $this->setParameter('period', $period); + $totp = new self($secret, $clock); + $totp->setPeriod(self::DEFAULT_PERIOD); + $totp->setDigest(self::DEFAULT_DIGEST); + $totp->setDigits(self::DEFAULT_DIGITS); + $totp->setEpoch(self::DEFAULT_EPOCH); + + return $totp; + } + + public static function generate(?ClockInterface $clock = null): self + { + return self::createFromSecret(self::generateSecret(), $clock); } - /** - * {@inheritdoc} - */ public function getPeriod(): int { - return $this->getParameter('period'); + $value = $this->getParameter('period'); + (is_int($value) && $value > 0) || throw new InvalidArgumentException('Invalid "period" parameter.'); + + return $value; } - /** - * @param int $epoch - */ - private function setEpoch(int $epoch) - { - $this->setParameter('epoch', $epoch); - } - - /** - * {@inheritdoc} - */ public function getEpoch(): int { - return $this->getParameter('epoch'); + $value = $this->getParameter('epoch'); + (is_int($value) && $value >= 0) || throw new InvalidArgumentException('Invalid "epoch" parameter.'); + + return $value; } - /** - * {@inheritdoc} - */ - public function at(int $timestamp): string + public function expiresIn(): int { - return $this->generateOTP($this->timecode($timestamp)); + $period = $this->getPeriod(); + + return $period - ($this->clock->now()->getTimestamp() % $this->getPeriod()); } /** - * {@inheritdoc} + * The OTP at the specified input. + * + * @param 0|positive-int $input */ + public function at(int $input): string + { + return $this->generateOTP($this->timecode($input)); + } + public function now(): string { - return $this->at(time()); + $timestamp = $this->clock->now() + ->getTimestamp(); + assert($timestamp >= 0, 'The timestamp must return a positive integer.'); + + return $this->at($timestamp); } /** - * If no timestamp is provided, the OTP is verified at the actual timestamp - * {@inheritdoc} + * If no timestamp is provided, the OTP is verified at the actual timestamp. When used, the leeway parameter will + * allow time drift. The passed value is in seconds. + * + * @param 0|positive-int $timestamp + * @param null|0|positive-int $leeway */ - public function verify(string $otp, $timestamp = null, $window = null): bool + public function verify(string $otp, null|int $timestamp = null, null|int $leeway = null): bool { - $timestamp = $this->getTimestamp($timestamp); + $timestamp ??= $this->clock->now() + ->getTimestamp(); + $timestamp >= 0 || throw new InvalidArgumentException('Timestamp must be at least 0.'); - if (null === $window) { + if ($leeway === null) { return $this->compareOTP($this->at($timestamp), $otp); } - return $this->verifyOtpWithWindow($otp, $timestamp, $window); + $leeway = abs($leeway); + $leeway < $this->getPeriod() || throw new InvalidArgumentException( + 'The leeway must be lower than the TOTP period' + ); + $timestampMinusLeeway = $timestamp - $leeway; + $timestampMinusLeeway >= 0 || throw new InvalidArgumentException( + 'The timestamp must be greater than or equal to the leeway.' + ); + + return $this->compareOTP($this->at($timestampMinusLeeway), $otp) + || $this->compareOTP($this->at($timestamp), $otp) + || $this->compareOTP($this->at($timestamp + $leeway), $otp); } - /** - * @param string $otp - * @param int $timestamp - * @param int $window - * - * @return bool - */ - private function verifyOtpWithWindow(string $otp, int $timestamp, int $window): bool - { - $window = abs($window); - - for ($i = 0; $i <= $window; $i++) { - $next = (int) $i * $this->getPeriod() + $timestamp; - $previous = (int) -$i * $this->getPeriod() + $timestamp; - $valid = $this->compareOTP($this->at($next), $otp) || - $this->compareOTP($this->at($previous), $otp); - - if ($valid) { - return true; - } - } - - return false; - } - - /** - * @param int|null $timestamp - * - * @return int - */ - private function getTimestamp($timestamp): int - { - $timestamp = $timestamp ?? time(); - Assertion::greaterOrEqualThan($timestamp, 0, 'Timestamp must be at least 0.'); - - return (int) $timestamp; - } - - /** - * {@inheritdoc} - */ public function getProvisioningUri(): string { $params = []; - if (30 !== $this->getPeriod()) { + if ($this->getPeriod() !== 30) { $params['period'] = $this->getPeriod(); } - if (0 !== $this->getEpoch()) { + if ($this->getEpoch() !== 0) { $params['epoch'] = $this->getEpoch(); } return $this->generateURI('totp', $params); } - /** - * @param int $timestamp - * - * @return int - */ - private function timecode(int $timestamp): int + public function setPeriod(int $period): void { - return (int) floor(($timestamp - $this->getEpoch()) / $this->getPeriod()); + $this->setParameter('period', $period); + } + + public function setEpoch(int $epoch): void + { + $this->setParameter('epoch', $epoch); } /** - * {@inheritdoc} + * @return array */ protected function getParameterMap(): array { - $v = array_merge( - parent::getParameterMap(), - [ - 'period' => function ($value) { - Assertion::greaterThan((int) $value, 0, 'Period must be at least 1.'); + return [ + ...parent::getParameterMap(), + 'period' => static function ($value): int { + (int) $value > 0 || throw new InvalidArgumentException('Period must be at least 1.'); - return (int) $value; - }, - 'epoch' => function ($value) { - Assertion::greaterOrEqualThan((int) $value, 0, 'Epoch must be greater than or equal to 0.'); + return (int) $value; + }, + 'epoch' => static function ($value): int { + (int) $value >= 0 || throw new InvalidArgumentException( + 'Epoch must be greater than or equal to 0.' + ); - return (int) $value; - }, - ] - ); - - return $v; + return (int) $value; + }, + ]; } /** - * {@inheritdoc} + * @param array $options */ - protected function filterOptions(array &$options) + protected function filterOptions(array &$options): void { parent::filterOptions($options); - if (isset($options['epoch']) && 0 === $options['epoch']) { + if (isset($options['epoch']) && $options['epoch'] === 0) { unset($options['epoch']); } ksort($options); } + + /** + * @param 0|positive-int $timestamp + * + * @return 0|positive-int + */ + private function timecode(int $timestamp): int + { + $timecode = (int) floor(($timestamp - $this->getEpoch()) / $this->getPeriod()); + assert($timecode >= 0); + + return $timecode; + } } diff --git a/admin/tool/mfa/factor/totp/extlib/OTPHP/TOTPInterface.php b/admin/tool/mfa/factor/totp/extlib/OTPHP/TOTPInterface.php index 571f924d023..a79fedcceb1 100644 --- a/admin/tool/mfa/factor/totp/extlib/OTPHP/TOTPInterface.php +++ b/admin/tool/mfa/factor/totp/extlib/OTPHP/TOTPInterface.php @@ -2,26 +2,50 @@ declare(strict_types=1); -/* - * The MIT License (MIT) - * - * Copyright (c) 2014-2018 Spomky-Labs - * - * This software may be modified and distributed under the terms - * of the MIT license. See the LICENSE file for details. - */ - namespace OTPHP; interface TOTPInterface extends OTPInterface { + public const DEFAULT_PERIOD = 30; + + public const DEFAULT_EPOCH = 0; + /** - * @return string Return the TOTP at the current time + * Create a new TOTP object. + * + * If the secret is null, a random 64 bytes secret will be generated. + * + * @param null|non-empty-string $secret + * @param positive-int $period + * @param non-empty-string $digest + * @param positive-int $digits + * + * @deprecated Deprecated since v11.1, use ::createFromSecret or ::generate instead + */ + public static function create( + null|string $secret = null, + int $period = self::DEFAULT_PERIOD, + string $digest = self::DEFAULT_DIGEST, + int $digits = self::DEFAULT_DIGITS + ): self; + + public function setPeriod(int $period): void; + + public function setEpoch(int $epoch): void; + + /** + * Return the TOTP at the current time. + * + * @return non-empty-string */ public function now(): string; /** - * @return int Get the period of time for OTP generation (a non-null positive integer, in second) + * Get the period of time for OTP generation (a non-null positive integer, in second). */ public function getPeriod(): int; + + public function expiresIn(): int; + + public function getEpoch(): int; } diff --git a/admin/tool/mfa/factor/totp/extlib/OTPHP/composer.json b/admin/tool/mfa/factor/totp/extlib/OTPHP/composer.json index 1abd98395fa..bff1e48f3f4 100644 --- a/admin/tool/mfa/factor/totp/extlib/OTPHP/composer.json +++ b/admin/tool/mfa/factor/totp/extlib/OTPHP/composer.json @@ -16,15 +16,25 @@ } ], "require": { - "php": "^7.1", - "paragonie/constant_time_encoding": "^2.0", - "beberlei/assert": "^2.4" + "php": ">=8.1", + "ext-mbstring": "*", + "paragonie/constant_time_encoding": "^2.0 || ^3.0", + "psr/clock": "^1.0", + "symfony/deprecation-contracts": "^3.2" }, "require-dev": { - "phpunit/phpunit": "^6.0", - "satooshi/php-coveralls": "^1.0" - }, - "suggest": { + "ekino/phpstan-banned-code": "^1.0", + "infection/infection": "^0.26|^0.27|^0.28|^0.29", + "php-parallel-lint/php-parallel-lint": "^1.3", + "phpstan/phpstan": "^1.0", + "phpstan/phpstan-deprecation-rules": "^1.0", + "phpstan/phpstan-phpunit": "^1.0", + "phpstan/phpstan-strict-rules": "^1.0", + "phpunit/phpunit": "^9.5.26|^10.0|^11.0", + "qossmic/deptrac-shim": "^1.0", + "rector/rector": "^1.0", + "symfony/phpunit-bridge": "^6.1|^7.0", + "symplify/easy-coding-standard": "^12.0" }, "autoload": { "psr-4": { "OTPHP\\": "src/" } @@ -32,9 +42,18 @@ "autoload-dev": { "psr-4": { "OTPHP\\Test\\": "tests/" } }, - "extra": { - "branch-alias": { - "dev-master": "9.0.x-dev" - } + "config": { + "allow-plugins": { + "phpstan/extension-installer": true, + "infection/extension-installer": true, + "composer/package-versions-deprecated": true, + "symfony/flex": true, + "symfony/runtime": true + }, + "optimize-autoloader": true, + "preferred-install": { + "*": "dist" + }, + "sort-packages": true } } diff --git a/admin/tool/mfa/factor/totp/extlib/OTPHP/readme_moodle.txt b/admin/tool/mfa/factor/totp/extlib/OTPHP/readme_moodle.txt index ba87585e750..44188b2a104 100644 --- a/admin/tool/mfa/factor/totp/extlib/OTPHP/readme_moodle.txt +++ b/admin/tool/mfa/factor/totp/extlib/OTPHP/readme_moodle.txt @@ -1,18 +1,18 @@ -OTPHP 9.1.1 +OTPHP -------------- -https://github.com/Spomky-Labs/otphp/releases/tag/v9.1.1 -Instructions to import WebAuthn into Moodle: +Instructions to import OTPHP into Moodle: 1. Download the latest release from https://github.com/Spomky-Labs/otphp/releases/tag/vx.x.x (choose "Source code") 2. Unzip the source code -3. Copy the following files from otphp-x.x/lib/OTPHP into admin/tool/mfa/factor/totp/extlib/OTPHP: - 1. OTP.php - 2. OTPInterface.php - 3. ParameterTrait.php - 4. TOTP.php - 5. TOTPInterface.php +3. Copy the following files from otphp-x.x/src into admin/tool/mfa/factor/totp/extlib/OTPHP: + 1. InternalClock.php + 2. OTP.php + 3. OTPInterface.php + 4. ParameterTrait.php + 5. TOTP.php + 6. TOTPInterface.php 4. Copy the following files from otphp-x.x into admin/tool/mfa/factor/totp/extlib/OTPHP: 1. LICENSE diff --git a/admin/tool/mfa/factor/totp/thirdpartylibs.xml b/admin/tool/mfa/factor/totp/thirdpartylibs.xml index 5365218a40c..3b7eea47169 100644 --- a/admin/tool/mfa/factor/totp/thirdpartylibs.xml +++ b/admin/tool/mfa/factor/totp/thirdpartylibs.xml @@ -10,7 +10,7 @@ extlib/OTPHP OTPHP - 9.1.1 + 11.3.0 MIT https://github.com/Spomky-Labs/otphp From 1a25317f429b08eb5d2d370bfa02b0dbcb4ed490 Mon Sep 17 00:00:00 2001 From: Daniel Ziegenberg Date: Sun, 10 Mar 2024 04:07:41 +0100 Subject: [PATCH 2/4] MDL-79678 libraries: Remove unused dependency Assert This commit removes the dependency Assert that once was required by OTPHP, but is no longer needed as of version 11.2.0. Signed-off-by: Daniel Ziegenberg --- admin/tool/mfa/factor/totp/classes/factor.php | 3 - .../factor/totp/extlib/Assert/Assertion.php | 2825 ----------------- .../Assert/AssertionFailedException.php | 35 - .../Assert/InvalidArgumentException.php | 76 - .../mfa/factor/totp/extlib/Assert/LICENSE | 11 - .../factor/totp/extlib/Assert/composer.json | 23 - .../totp/extlib/Assert/readme_moodle.txt | 17 - .../mfa/factor/totp/tests/factor_test.php | 3 - admin/tool/mfa/factor/totp/thirdpartylibs.xml | 7 - 9 files changed, 3000 deletions(-) delete mode 100644 admin/tool/mfa/factor/totp/extlib/Assert/Assertion.php delete mode 100644 admin/tool/mfa/factor/totp/extlib/Assert/AssertionFailedException.php delete mode 100644 admin/tool/mfa/factor/totp/extlib/Assert/InvalidArgumentException.php delete mode 100644 admin/tool/mfa/factor/totp/extlib/Assert/LICENSE delete mode 100644 admin/tool/mfa/factor/totp/extlib/Assert/composer.json delete mode 100644 admin/tool/mfa/factor/totp/extlib/Assert/readme_moodle.txt diff --git a/admin/tool/mfa/factor/totp/classes/factor.php b/admin/tool/mfa/factor/totp/classes/factor.php index a5d1b9555c3..88911b6987e 100644 --- a/admin/tool/mfa/factor/totp/classes/factor.php +++ b/admin/tool/mfa/factor/totp/classes/factor.php @@ -25,9 +25,6 @@ require_once(__DIR__.'/../extlib/OTPHP/ParameterTrait.php'); require_once(__DIR__.'/../extlib/OTPHP/OTP.php'); require_once(__DIR__.'/../extlib/OTPHP/TOTP.php'); -require_once(__DIR__.'/../extlib/Assert/Assertion.php'); -require_once(__DIR__.'/../extlib/Assert/AssertionFailedException.php'); -require_once(__DIR__.'/../extlib/Assert/InvalidArgumentException.php'); require_once(__DIR__.'/../extlib/ParagonIE/ConstantTime/EncoderInterface.php'); require_once(__DIR__.'/../extlib/ParagonIE/ConstantTime/Binary.php'); require_once(__DIR__.'/../extlib/ParagonIE/ConstantTime/Base32.php'); diff --git a/admin/tool/mfa/factor/totp/extlib/Assert/Assertion.php b/admin/tool/mfa/factor/totp/extlib/Assert/Assertion.php deleted file mode 100644 index 6f5b3c2dc54..00000000000 --- a/admin/tool/mfa/factor/totp/extlib/Assert/Assertion.php +++ /dev/null @@ -1,2825 +0,0 @@ - - * - * @method static bool allAlnum(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is alphanumeric for all values. - * @method static bool allBase64(string $value, string|callable $message = null, string $propertyPath = null) Assert that a constant is defined for all values. - * @method static bool allBetween(mixed $value, mixed $lowerLimit, mixed $upperLimit, string|callable $message = null, string $propertyPath = null) Assert that a value is greater or equal than a lower limit, and less than or equal to an upper limit for all values. - * @method static bool allBetweenExclusive(mixed $value, mixed $lowerLimit, mixed $upperLimit, string|callable $message = null, string $propertyPath = null) Assert that a value is greater than a lower limit, and less than an upper limit for all values. - * @method static bool allBetweenLength(mixed $value, int $minLength, int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string length is between min and max lengths for all values. - * @method static bool allBoolean(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is php boolean for all values. - * @method static bool allChoice(mixed $value, array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices for all values. - * @method static bool allChoicesNotEmpty(array $values, array $choices, string|callable $message = null, string $propertyPath = null) Determines if the values array has every choice as key and that this choice has content for all values. - * @method static bool allClassExists(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that the class exists for all values. - * @method static bool allContains(mixed $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string contains a sequence of chars for all values. - * @method static bool allCount(array|Countable|ResourceBundle|SimpleXMLElement $countable, int $count, string|callable $message = null, string $propertyPath = null) Assert that the count of countable is equal to count for all values. - * @method static bool allDate(string $value, string $format, string|callable $message = null, string $propertyPath = null) Assert that date is valid and corresponds to the given format for all values. - * @method static bool allDefined(mixed $constant, string|callable $message = null, string $propertyPath = null) Assert that a constant is defined for all values. - * @method static bool allDigit(mixed $value, string|callable $message = null, string $propertyPath = null) Validates if an integer or integerish is a digit for all values. - * @method static bool allDirectory(string $value, string|callable $message = null, string $propertyPath = null) Assert that a directory exists for all values. - * @method static bool allE164(string $value, string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid E164 Phone Number for all values. - * @method static bool allEmail(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is an email address (using input_filter/FILTER_VALIDATE_EMAIL) for all values. - * @method static bool allEndsWith(mixed $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string ends with a sequence of chars for all values. - * @method static bool allEq(mixed $value, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are equal (using ==) for all values. - * @method static bool allEqArraySubset(mixed $value, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that the array contains the subset for all values. - * @method static bool allExtensionLoaded(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that extension is loaded for all values. - * @method static bool allExtensionVersion(string $extension, string $operator, mixed $version, string|callable $message = null, string $propertyPath = null) Assert that extension is loaded and a specific version is installed for all values. - * @method static bool allFalse(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that the value is boolean False for all values. - * @method static bool allFile(string $value, string|callable $message = null, string $propertyPath = null) Assert that a file exists for all values. - * @method static bool allFloat(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is a php float for all values. - * @method static bool allGreaterOrEqualThan(mixed $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater or equal than given limit for all values. - * @method static bool allGreaterThan(mixed $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater than given limit for all values. - * @method static bool allImplementsInterface(mixed $class, string $interfaceName, string|callable $message = null, string $propertyPath = null) Assert that the class implements the interface for all values. - * @method static bool allInArray(mixed $value, array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices. This is an alias of Assertion::choice() for all values. - * @method static bool allInteger(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is a php integer for all values. - * @method static bool allIntegerish(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is a php integer'ish for all values. - * @method static bool allInterfaceExists(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that the interface exists for all values. - * @method static bool allIp(string $value, int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 or IPv6 address for all values. - * @method static bool allIpv4(string $value, int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 address for all values. - * @method static bool allIpv6(string $value, int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv6 address for all values. - * @method static bool allIsArray(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is an array for all values. - * @method static bool allIsArrayAccessible(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is an array or an array-accessible object for all values. - * @method static bool allIsCallable(mixed $value, string|callable $message = null, string $propertyPath = null) Determines that the provided value is callable for all values. - * @method static bool allIsCountable(array|Countable|ResourceBundle|SimpleXMLElement $value, string|callable $message = null, string $propertyPath = null) Assert that value is countable for all values. - * @method static bool allIsInstanceOf(mixed $value, string $className, string|callable $message = null, string $propertyPath = null) Assert that value is instance of given class-name for all values. - * @method static bool allIsJsonString(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid json string for all values. - * @method static bool allIsObject(mixed $value, string|callable $message = null, string $propertyPath = null) Determines that the provided value is an object for all values. - * @method static bool allIsResource(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is a resource for all values. - * @method static bool allIsTraversable(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is an array or a traversable object for all values. - * @method static bool allKeyExists(mixed $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array for all values. - * @method static bool allKeyIsset(mixed $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object using isset() for all values. - * @method static bool allKeyNotExists(mixed $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key does not exist in an array for all values. - * @method static bool allLength(mixed $value, int $length, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string has a given length for all values. - * @method static bool allLessOrEqualThan(mixed $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less or equal than given limit for all values. - * @method static bool allLessThan(mixed $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less than given limit for all values. - * @method static bool allMax(mixed $value, mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that a number is smaller as a given limit for all values. - * @method static bool allMaxCount(array|Countable|ResourceBundle|SimpleXMLElement $countable, int $count, string|callable $message = null, string $propertyPath = null) Assert that the countable have at most $count elements for all values. - * @method static bool allMaxLength(mixed $value, int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string value is not longer than $maxLength chars for all values. - * @method static bool allMethodExists(string $value, mixed $object, string|callable $message = null, string $propertyPath = null) Determines that the named method is defined in the provided object for all values. - * @method static bool allMin(mixed $value, mixed $minValue, string|callable $message = null, string $propertyPath = null) Assert that a value is at least as big as a given limit for all values. - * @method static bool allMinCount(array|Countable|ResourceBundle|SimpleXMLElement $countable, int $count, string|callable $message = null, string $propertyPath = null) Assert that the countable have at least $count elements for all values. - * @method static bool allMinLength(mixed $value, int $minLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that a string is at least $minLength chars long for all values. - * @method static bool allNoContent(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is empty for all values. - * @method static bool allNotBlank(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is not blank for all values. - * @method static bool allNotContains(mixed $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string does not contains a sequence of chars for all values. - * @method static bool allNotEmpty(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is not empty for all values. - * @method static bool allNotEmptyKey(mixed $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object and its value is not empty for all values. - * @method static bool allNotEq(mixed $value1, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not equal (using ==) for all values. - * @method static bool allNotInArray(mixed $value, array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is not in array of choices for all values. - * @method static bool allNotIsInstanceOf(mixed $value, string $className, string|callable $message = null, string $propertyPath = null) Assert that value is not instance of given class-name for all values. - * @method static bool allNotNull(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is not null for all values. - * @method static bool allNotRegex(mixed $value, string $pattern, string|callable $message = null, string $propertyPath = null) Assert that value does not match a regex for all values. - * @method static bool allNotSame(mixed $value1, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not the same (using ===) for all values. - * @method static bool allNull(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is null for all values. - * @method static bool allNumeric(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is numeric for all values. - * @method static bool allObjectOrClass(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that the value is an object, or a class that exists for all values. - * @method static bool allPhpVersion(string $operator, mixed $version, string|callable $message = null, string $propertyPath = null) Assert on PHP version for all values. - * @method static bool allPropertiesExist(mixed $value, array $properties, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the properties all exist for all values. - * @method static bool allPropertyExists(mixed $value, string $property, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the property exists for all values. - * @method static bool allRange(mixed $value, mixed $minValue, mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that value is in range of numbers for all values. - * @method static bool allReadable(string $value, string|callable $message = null, string $propertyPath = null) Assert that the value is something readable for all values. - * @method static bool allRegex(mixed $value, string $pattern, string|callable $message = null, string $propertyPath = null) Assert that value matches a regex for all values. - * @method static bool allSame(mixed $value, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are the same (using ===) for all values. - * @method static bool allSatisfy(mixed $value, callable $callback, string|callable $message = null, string $propertyPath = null) Assert that the provided value is valid according to a callback for all values. - * @method static bool allScalar(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is a PHP scalar for all values. - * @method static bool allStartsWith(mixed $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string starts with a sequence of chars for all values. - * @method static bool allString(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is a string for all values. - * @method static bool allSubclassOf(mixed $value, string $className, string|callable $message = null, string $propertyPath = null) Assert that value is subclass of given class-name for all values. - * @method static bool allTrue(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that the value is boolean True for all values. - * @method static bool allUrl(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is an URL for all values. - * @method static bool allUuid(string $value, string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid UUID for all values. - * @method static bool allVersion(string $version1, string $operator, string $version2, string|callable $message = null, string $propertyPath = null) Assert comparison of two versions for all values. - * @method static bool allWriteable(string $value, string|callable $message = null, string $propertyPath = null) Assert that the value is something writeable for all values. - * @method static bool nullOrAlnum(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is alphanumeric or that the value is null. - * @method static bool nullOrBase64(string|null $value, string|callable $message = null, string $propertyPath = null) Assert that a constant is defined or that the value is null. - * @method static bool nullOrBetween(mixed|null $value, mixed $lowerLimit, mixed $upperLimit, string|callable $message = null, string $propertyPath = null) Assert that a value is greater or equal than a lower limit, and less than or equal to an upper limit or that the value is null. - * @method static bool nullOrBetweenExclusive(mixed|null $value, mixed $lowerLimit, mixed $upperLimit, string|callable $message = null, string $propertyPath = null) Assert that a value is greater than a lower limit, and less than an upper limit or that the value is null. - * @method static bool nullOrBetweenLength(mixed|null $value, int $minLength, int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string length is between min and max lengths or that the value is null. - * @method static bool nullOrBoolean(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is php boolean or that the value is null. - * @method static bool nullOrChoice(mixed|null $value, array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices or that the value is null. - * @method static bool nullOrChoicesNotEmpty(array|null $values, array $choices, string|callable $message = null, string $propertyPath = null) Determines if the values array has every choice as key and that this choice has content or that the value is null. - * @method static bool nullOrClassExists(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that the class exists or that the value is null. - * @method static bool nullOrContains(mixed|null $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string contains a sequence of chars or that the value is null. - * @method static bool nullOrCount(array|Countable|ResourceBundle|SimpleXMLElement|null $countable, int $count, string|callable $message = null, string $propertyPath = null) Assert that the count of countable is equal to count or that the value is null. - * @method static bool nullOrDate(string|null $value, string $format, string|callable $message = null, string $propertyPath = null) Assert that date is valid and corresponds to the given format or that the value is null. - * @method static bool nullOrDefined(mixed|null $constant, string|callable $message = null, string $propertyPath = null) Assert that a constant is defined or that the value is null. - * @method static bool nullOrDigit(mixed|null $value, string|callable $message = null, string $propertyPath = null) Validates if an integer or integerish is a digit or that the value is null. - * @method static bool nullOrDirectory(string|null $value, string|callable $message = null, string $propertyPath = null) Assert that a directory exists or that the value is null. - * @method static bool nullOrE164(string|null $value, string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid E164 Phone Number or that the value is null. - * @method static bool nullOrEmail(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is an email address (using input_filter/FILTER_VALIDATE_EMAIL) or that the value is null. - * @method static bool nullOrEndsWith(mixed|null $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string ends with a sequence of chars or that the value is null. - * @method static bool nullOrEq(mixed|null $value, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are equal (using ==) or that the value is null. - * @method static bool nullOrEqArraySubset(mixed|null $value, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that the array contains the subset or that the value is null. - * @method static bool nullOrExtensionLoaded(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that extension is loaded or that the value is null. - * @method static bool nullOrExtensionVersion(string|null $extension, string $operator, mixed $version, string|callable $message = null, string $propertyPath = null) Assert that extension is loaded and a specific version is installed or that the value is null. - * @method static bool nullOrFalse(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that the value is boolean False or that the value is null. - * @method static bool nullOrFile(string|null $value, string|callable $message = null, string $propertyPath = null) Assert that a file exists or that the value is null. - * @method static bool nullOrFloat(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is a php float or that the value is null. - * @method static bool nullOrGreaterOrEqualThan(mixed|null $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater or equal than given limit or that the value is null. - * @method static bool nullOrGreaterThan(mixed|null $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater than given limit or that the value is null. - * @method static bool nullOrImplementsInterface(mixed|null $class, string $interfaceName, string|callable $message = null, string $propertyPath = null) Assert that the class implements the interface or that the value is null. - * @method static bool nullOrInArray(mixed|null $value, array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices. This is an alias of Assertion::choice() or that the value is null. - * @method static bool nullOrInteger(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is a php integer or that the value is null. - * @method static bool nullOrIntegerish(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is a php integer'ish or that the value is null. - * @method static bool nullOrInterfaceExists(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that the interface exists or that the value is null. - * @method static bool nullOrIp(string|null $value, int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 or IPv6 address or that the value is null. - * @method static bool nullOrIpv4(string|null $value, int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 address or that the value is null. - * @method static bool nullOrIpv6(string|null $value, int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv6 address or that the value is null. - * @method static bool nullOrIsArray(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is an array or that the value is null. - * @method static bool nullOrIsArrayAccessible(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is an array or an array-accessible object or that the value is null. - * @method static bool nullOrIsCallable(mixed|null $value, string|callable $message = null, string $propertyPath = null) Determines that the provided value is callable or that the value is null. - * @method static bool nullOrIsCountable(array|Countable|ResourceBundle|SimpleXMLElement|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is countable or that the value is null. - * @method static bool nullOrIsInstanceOf(mixed|null $value, string $className, string|callable $message = null, string $propertyPath = null) Assert that value is instance of given class-name or that the value is null. - * @method static bool nullOrIsJsonString(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid json string or that the value is null. - * @method static bool nullOrIsObject(mixed|null $value, string|callable $message = null, string $propertyPath = null) Determines that the provided value is an object or that the value is null. - * @method static bool nullOrIsResource(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is a resource or that the value is null. - * @method static bool nullOrIsTraversable(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is an array or a traversable object or that the value is null. - * @method static bool nullOrKeyExists(mixed|null $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array or that the value is null. - * @method static bool nullOrKeyIsset(mixed|null $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object using isset() or that the value is null. - * @method static bool nullOrKeyNotExists(mixed|null $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key does not exist in an array or that the value is null. - * @method static bool nullOrLength(mixed|null $value, int $length, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string has a given length or that the value is null. - * @method static bool nullOrLessOrEqualThan(mixed|null $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less or equal than given limit or that the value is null. - * @method static bool nullOrLessThan(mixed|null $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less than given limit or that the value is null. - * @method static bool nullOrMax(mixed|null $value, mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that a number is smaller as a given limit or that the value is null. - * @method static bool nullOrMaxCount(array|Countable|ResourceBundle|SimpleXMLElement|null $countable, int $count, string|callable $message = null, string $propertyPath = null) Assert that the countable have at most $count elements or that the value is null. - * @method static bool nullOrMaxLength(mixed|null $value, int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string value is not longer than $maxLength chars or that the value is null. - * @method static bool nullOrMethodExists(string|null $value, mixed $object, string|callable $message = null, string $propertyPath = null) Determines that the named method is defined in the provided object or that the value is null. - * @method static bool nullOrMin(mixed|null $value, mixed $minValue, string|callable $message = null, string $propertyPath = null) Assert that a value is at least as big as a given limit or that the value is null. - * @method static bool nullOrMinCount(array|Countable|ResourceBundle|SimpleXMLElement|null $countable, int $count, string|callable $message = null, string $propertyPath = null) Assert that the countable have at least $count elements or that the value is null. - * @method static bool nullOrMinLength(mixed|null $value, int $minLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that a string is at least $minLength chars long or that the value is null. - * @method static bool nullOrNoContent(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is empty or that the value is null. - * @method static bool nullOrNotBlank(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is not blank or that the value is null. - * @method static bool nullOrNotContains(mixed|null $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string does not contains a sequence of chars or that the value is null. - * @method static bool nullOrNotEmpty(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is not empty or that the value is null. - * @method static bool nullOrNotEmptyKey(mixed|null $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object and its value is not empty or that the value is null. - * @method static bool nullOrNotEq(mixed|null $value1, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not equal (using ==) or that the value is null. - * @method static bool nullOrNotInArray(mixed|null $value, array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is not in array of choices or that the value is null. - * @method static bool nullOrNotIsInstanceOf(mixed|null $value, string $className, string|callable $message = null, string $propertyPath = null) Assert that value is not instance of given class-name or that the value is null. - * @method static bool nullOrNotNull(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is not null or that the value is null. - * @method static bool nullOrNotRegex(mixed|null $value, string $pattern, string|callable $message = null, string $propertyPath = null) Assert that value does not match a regex or that the value is null. - * @method static bool nullOrNotSame(mixed|null $value1, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not the same (using ===) or that the value is null. - * @method static bool nullOrNull(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is null or that the value is null. - * @method static bool nullOrNumeric(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is numeric or that the value is null. - * @method static bool nullOrObjectOrClass(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that the value is an object, or a class that exists or that the value is null. - * @method static bool nullOrPhpVersion(string|null $operator, mixed $version, string|callable $message = null, string $propertyPath = null) Assert on PHP version or that the value is null. - * @method static bool nullOrPropertiesExist(mixed|null $value, array $properties, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the properties all exist or that the value is null. - * @method static bool nullOrPropertyExists(mixed|null $value, string $property, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the property exists or that the value is null. - * @method static bool nullOrRange(mixed|null $value, mixed $minValue, mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that value is in range of numbers or that the value is null. - * @method static bool nullOrReadable(string|null $value, string|callable $message = null, string $propertyPath = null) Assert that the value is something readable or that the value is null. - * @method static bool nullOrRegex(mixed|null $value, string $pattern, string|callable $message = null, string $propertyPath = null) Assert that value matches a regex or that the value is null. - * @method static bool nullOrSame(mixed|null $value, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are the same (using ===) or that the value is null. - * @method static bool nullOrSatisfy(mixed|null $value, callable $callback, string|callable $message = null, string $propertyPath = null) Assert that the provided value is valid according to a callback or that the value is null. - * @method static bool nullOrScalar(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is a PHP scalar or that the value is null. - * @method static bool nullOrStartsWith(mixed|null $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string starts with a sequence of chars or that the value is null. - * @method static bool nullOrString(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is a string or that the value is null. - * @method static bool nullOrSubclassOf(mixed|null $value, string $className, string|callable $message = null, string $propertyPath = null) Assert that value is subclass of given class-name or that the value is null. - * @method static bool nullOrTrue(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that the value is boolean True or that the value is null. - * @method static bool nullOrUrl(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is an URL or that the value is null. - * @method static bool nullOrUuid(string|null $value, string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid UUID or that the value is null. - * @method static bool nullOrVersion(string|null $version1, string $operator, string $version2, string|callable $message = null, string $propertyPath = null) Assert comparison of two versions or that the value is null. - * @method static bool nullOrWriteable(string|null $value, string|callable $message = null, string $propertyPath = null) Assert that the value is something writeable or that the value is null. - */ -class Assertion -{ - const INVALID_FLOAT = 9; - const INVALID_INTEGER = 10; - const INVALID_DIGIT = 11; - const INVALID_INTEGERISH = 12; - const INVALID_BOOLEAN = 13; - const VALUE_EMPTY = 14; - const VALUE_NULL = 15; - const VALUE_NOT_NULL = 25; - const INVALID_STRING = 16; - const INVALID_REGEX = 17; - const INVALID_MIN_LENGTH = 18; - const INVALID_MAX_LENGTH = 19; - const INVALID_STRING_START = 20; - const INVALID_STRING_CONTAINS = 21; - const INVALID_CHOICE = 22; - const INVALID_NUMERIC = 23; - const INVALID_ARRAY = 24; - const INVALID_KEY_EXISTS = 26; - const INVALID_NOT_BLANK = 27; - const INVALID_INSTANCE_OF = 28; - const INVALID_SUBCLASS_OF = 29; - const INVALID_RANGE = 30; - const INVALID_ALNUM = 31; - const INVALID_TRUE = 32; - const INVALID_EQ = 33; - const INVALID_SAME = 34; - const INVALID_MIN = 35; - const INVALID_MAX = 36; - const INVALID_LENGTH = 37; - const INVALID_FALSE = 38; - const INVALID_STRING_END = 39; - const INVALID_UUID = 40; - const INVALID_COUNT = 41; - const INVALID_NOT_EQ = 42; - const INVALID_NOT_SAME = 43; - const INVALID_TRAVERSABLE = 44; - const INVALID_ARRAY_ACCESSIBLE = 45; - const INVALID_KEY_ISSET = 46; - const INVALID_VALUE_IN_ARRAY = 47; - const INVALID_E164 = 48; - const INVALID_BASE64 = 49; - const INVALID_NOT_REGEX = 50; - const INVALID_DIRECTORY = 101; - const INVALID_FILE = 102; - const INVALID_READABLE = 103; - const INVALID_WRITEABLE = 104; - const INVALID_CLASS = 105; - const INVALID_INTERFACE = 106; - const INVALID_FILE_NOT_EXISTS = 107; - const INVALID_EMAIL = 201; - const INTERFACE_NOT_IMPLEMENTED = 202; - const INVALID_URL = 203; - const INVALID_NOT_INSTANCE_OF = 204; - const VALUE_NOT_EMPTY = 205; - const INVALID_JSON_STRING = 206; - const INVALID_OBJECT = 207; - const INVALID_METHOD = 208; - const INVALID_SCALAR = 209; - const INVALID_LESS = 210; - const INVALID_LESS_OR_EQUAL = 211; - const INVALID_GREATER = 212; - const INVALID_GREATER_OR_EQUAL = 213; - const INVALID_DATE = 214; - const INVALID_CALLABLE = 215; - const INVALID_KEY_NOT_EXISTS = 216; - const INVALID_SATISFY = 217; - const INVALID_IP = 218; - const INVALID_BETWEEN = 219; - const INVALID_BETWEEN_EXCLUSIVE = 220; - const INVALID_EXTENSION = 222; - const INVALID_CONSTANT = 221; - const INVALID_VERSION = 223; - const INVALID_PROPERTY = 224; - const INVALID_RESOURCE = 225; - const INVALID_COUNTABLE = 226; - const INVALID_MIN_COUNT = 227; - const INVALID_MAX_COUNT = 228; - const INVALID_STRING_NOT_CONTAINS = 229; - - /** - * Exception to throw when an assertion failed. - * - * @var string - */ - protected static $exceptionClass = InvalidArgumentException::class; - - /** - * Assert that two values are equal (using ==). - * - * @param mixed $value - * @param mixed $value2 - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function eq($value, $value2, $message = null, string $propertyPath = null): bool - { - if ($value != $value2) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" does not equal expected value "%s".'), - static::stringify($value), - static::stringify($value2) - ); - - throw static::createException($value, $message, static::INVALID_EQ, $propertyPath, ['expected' => $value2]); - } - - return true; - } - - /** - * Assert that the array contains the subset. - * - * @param mixed $value - * @param mixed $value2 - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function eqArraySubset($value, $value2, $message = null, string $propertyPath = null): bool - { - static::isArray($value, $message, $propertyPath); - static::isArray($value2, $message, $propertyPath); - - $patched = \array_replace_recursive($value, $value2); - static::eq($patched, $value, $message, $propertyPath); - - return true; - } - - /** - * Assert that two values are the same (using ===). - * - * @param mixed $value - * @param mixed $value2 - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function same($value, $value2, $message = null, string $propertyPath = null): bool - { - if ($value !== $value2) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not the same as expected value "%s".'), - static::stringify($value), - static::stringify($value2) - ); - - throw static::createException($value, $message, static::INVALID_SAME, $propertyPath, ['expected' => $value2]); - } - - return true; - } - - /** - * Assert that two values are not equal (using ==). - * - * @param mixed $value1 - * @param mixed $value2 - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function notEq($value1, $value2, $message = null, string $propertyPath = null): bool - { - if ($value1 == $value2) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" was not expected to be equal to value "%s".'), - static::stringify($value1), - static::stringify($value2) - ); - throw static::createException($value1, $message, static::INVALID_NOT_EQ, $propertyPath, ['expected' => $value2]); - } - - return true; - } - - /** - * Assert that two values are not the same (using ===). - * - * @param mixed $value1 - * @param mixed $value2 - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function notSame($value1, $value2, $message = null, string $propertyPath = null): bool - { - if ($value1 === $value2) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" was not expected to be the same as value "%s".'), - static::stringify($value1), - static::stringify($value2) - ); - throw static::createException($value1, $message, static::INVALID_NOT_SAME, $propertyPath, ['expected' => $value2]); - } - - return true; - } - - /** - * Assert that value is not in array of choices. - * - * @param mixed $value - * @param array $choices - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function notInArray($value, array $choices, $message = null, string $propertyPath = null): bool - { - if (true === \in_array($value, $choices)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" was not expected to be an element of the values: %s'), - static::stringify($value), - static::stringify($choices) - ); - throw static::createException($value, $message, static::INVALID_VALUE_IN_ARRAY, $propertyPath, ['choices' => $choices]); - } - - return true; - } - - /** - * Assert that value is a php integer. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function integer($value, $message = null, string $propertyPath = null): bool - { - if (!\is_int($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not an integer.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_INTEGER, $propertyPath); - } - - return true; - } - - /** - * Assert that value is a php float. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function float($value, $message = null, string $propertyPath = null): bool - { - if (!\is_float($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not a float.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_FLOAT, $propertyPath); - } - - return true; - } - - /** - * Validates if an integer or integerish is a digit. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function digit($value, $message = null, string $propertyPath = null): bool - { - if (!\ctype_digit((string)$value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not a digit.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_DIGIT, $propertyPath); - } - - return true; - } - - /** - * Assert that value is a php integer'ish. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function integerish($value, $message = null, string $propertyPath = null): bool - { - if ( - \is_resource($value) || - \is_object($value) || - \is_bool($value) || - \is_null($value) || - \is_array($value) || - (\is_string($value) && '' == $value) || - ( - \strval(\intval($value)) !== \strval($value) && - \strval(\intval($value)) !== \strval(\ltrim($value, '0')) && - '' !== \strval(\intval($value)) && - '' !== \strval(\ltrim($value, '0')) - ) - ) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not an integer or a number castable to integer.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_INTEGERISH, $propertyPath); - } - - return true; - } - - /** - * Assert that value is php boolean. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function boolean($value, $message = null, string $propertyPath = null): bool - { - if (!\is_bool($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not a boolean.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_BOOLEAN, $propertyPath); - } - - return true; - } - - /** - * Assert that value is a PHP scalar. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function scalar($value, $message = null, string $propertyPath = null): bool - { - if (!\is_scalar($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not a scalar.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_SCALAR, $propertyPath); - } - - return true; - } - - /** - * Assert that value is not empty. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function notEmpty($value, $message = null, string $propertyPath = null): bool - { - if (empty($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is empty, but non empty value was expected.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::VALUE_EMPTY, $propertyPath); - } - - return true; - } - - /** - * Assert that value is empty. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function noContent($value, $message = null, string $propertyPath = null): bool - { - if (!empty($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not empty, but empty value was expected.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::VALUE_NOT_EMPTY, $propertyPath); - } - - return true; - } - - /** - * Assert that value is null. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - */ - public static function null($value, $message = null, string $propertyPath = null): bool - { - if (null !== $value) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not null, but null value was expected.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::VALUE_NOT_NULL, $propertyPath); - } - - return true; - } - - /** - * Assert that value is not null. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function notNull($value, $message = null, string $propertyPath = null): bool - { - if (null === $value) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is null, but non null value was expected.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::VALUE_NULL, $propertyPath); - } - - return true; - } - - /** - * Assert that value is a string. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function string($value, $message = null, string $propertyPath = null) - { - if (!\is_string($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" expected to be string, type %s given.'), - static::stringify($value), - \gettype($value) - ); - - throw static::createException($value, $message, static::INVALID_STRING, $propertyPath); - } - - return true; - } - - /** - * Assert that value matches a regex. - * - * @param mixed $value - * @param string $pattern - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function regex($value, $pattern, $message = null, string $propertyPath = null): bool - { - static::string($value, $message, $propertyPath); - - if (!\preg_match($pattern, $value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" does not match expression.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_REGEX, $propertyPath, ['pattern' => $pattern]); - } - - return true; - } - - /** - * Assert that value does not match a regex. - * - * @param mixed $value - * @param string $pattern - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function notRegex($value, $pattern, $message = null, string $propertyPath = null): bool - { - static::string($value, $message, $propertyPath); - - if (\preg_match($pattern, $value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" matches expression.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_NOT_REGEX, $propertyPath, ['pattern' => $pattern]); - } - - return true; - } - - /** - * Assert that string has a given length. - * - * @param mixed $value - * @param int $length - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function length($value, $length, $message = null, string $propertyPath = null, $encoding = 'utf8'): bool - { - static::string($value, $message, $propertyPath); - - if (\mb_strlen($value, $encoding) !== $length) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" has to be %d exactly characters long, but length is %d.'), - static::stringify($value), - $length, - \mb_strlen($value, $encoding) - ); - - throw static::createException($value, $message, static::INVALID_LENGTH, $propertyPath, ['length' => $length, 'encoding' => $encoding]); - } - - return true; - } - - /** - * Assert that a string is at least $minLength chars long. - * - * @param mixed $value - * @param int $minLength - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function minLength($value, $minLength, $message = null, string $propertyPath = null, $encoding = 'utf8'): bool - { - static::string($value, $message, $propertyPath); - - if (\mb_strlen($value, $encoding) < $minLength) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is too short, it should have at least %d characters, but only has %d characters.'), - static::stringify($value), - $minLength, - \mb_strlen($value, $encoding) - ); - - throw static::createException($value, $message, static::INVALID_MIN_LENGTH, $propertyPath, ['min_length' => $minLength, 'encoding' => $encoding]); - } - - return true; - } - - /** - * Assert that string value is not longer than $maxLength chars. - * - * @param mixed $value - * @param int $maxLength - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function maxLength($value, $maxLength, $message = null, string $propertyPath = null, $encoding = 'utf8'): bool - { - static::string($value, $message, $propertyPath); - - if (\mb_strlen($value, $encoding) > $maxLength) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is too long, it should have no more than %d characters, but has %d characters.'), - static::stringify($value), - $maxLength, - \mb_strlen($value, $encoding) - ); - - throw static::createException($value, $message, static::INVALID_MAX_LENGTH, $propertyPath, ['max_length' => $maxLength, 'encoding' => $encoding]); - } - - return true; - } - - /** - * Assert that string length is between min and max lengths. - * - * @param mixed $value - * @param int $minLength - * @param int $maxLength - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function betweenLength($value, $minLength, $maxLength, $message = null, string $propertyPath = null, $encoding = 'utf8'): bool - { - static::string($value, $message, $propertyPath); - static::minLength($value, $minLength, $message, $propertyPath, $encoding); - static::maxLength($value, $maxLength, $message, $propertyPath, $encoding); - - return true; - } - - /** - * Assert that string starts with a sequence of chars. - * - * @param mixed $string - * @param string $needle - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function startsWith($string, $needle, $message = null, string $propertyPath = null, $encoding = 'utf8'): bool - { - static::string($string, $message, $propertyPath); - - if (0 !== \mb_strpos($string, $needle, null, $encoding)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" does not start with "%s".'), - static::stringify($string), - static::stringify($needle) - ); - - throw static::createException($string, $message, static::INVALID_STRING_START, $propertyPath, ['needle' => $needle, 'encoding' => $encoding]); - } - - return true; - } - - /** - * Assert that string ends with a sequence of chars. - * - * @param mixed $string - * @param string $needle - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function endsWith($string, $needle, $message = null, string $propertyPath = null, $encoding = 'utf8'): bool - { - static::string($string, $message, $propertyPath); - - $stringPosition = \mb_strlen($string, $encoding) - \mb_strlen($needle, $encoding); - - if (\mb_strripos($string, $needle, null, $encoding) !== $stringPosition) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" does not end with "%s".'), - static::stringify($string), - static::stringify($needle) - ); - - throw static::createException($string, $message, static::INVALID_STRING_END, $propertyPath, ['needle' => $needle, 'encoding' => $encoding]); - } - - return true; - } - - /** - * Assert that string contains a sequence of chars. - * - * @param mixed $string - * @param string $needle - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function contains($string, $needle, $message = null, string $propertyPath = null, $encoding = 'utf8'): bool - { - static::string($string, $message, $propertyPath); - - if (false === \mb_strpos($string, $needle, null, $encoding)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" does not contain "%s".'), - static::stringify($string), - static::stringify($needle) - ); - - throw static::createException($string, $message, static::INVALID_STRING_CONTAINS, $propertyPath, ['needle' => $needle, 'encoding' => $encoding]); - } - - return true; - } - - /** - * Assert that string does not contains a sequence of chars. - * - * @param mixed $string - * @param string $needle - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function notContains($string, $needle, $message = null, string $propertyPath = null, $encoding = 'utf8'): bool - { - static::string($string, $message, $propertyPath); - - if (false !== \mb_strpos($string, $needle, null, $encoding)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" contains "%s".'), - static::stringify($string), - static::stringify($needle) - ); - - throw static::createException($string, $message, static::INVALID_STRING_NOT_CONTAINS, $propertyPath, ['needle' => $needle, 'encoding' => $encoding]); - } - - return true; - } - - /** - * Assert that value is in array of choices. - * - * @param mixed $value - * @param array $choices - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function choice($value, array $choices, $message = null, string $propertyPath = null): bool - { - if (!\in_array($value, $choices, true)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not an element of the valid values: %s'), - static::stringify($value), - \implode(', ', \array_map([\get_called_class(), 'stringify'], $choices)) - ); - - throw static::createException($value, $message, static::INVALID_CHOICE, $propertyPath, ['choices' => $choices]); - } - - return true; - } - - /** - * Assert that value is in array of choices. - * - * This is an alias of {@see choice()}. - * - * @param mixed $value - * @param array $choices - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function inArray($value, array $choices, $message = null, string $propertyPath = null): bool - { - return static::choice($value, $choices, $message, $propertyPath); - } - - /** - * Assert that value is numeric. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function numeric($value, $message = null, string $propertyPath = null): bool - { - if (!\is_numeric($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not numeric.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_NUMERIC, $propertyPath); - } - - return true; - } - - /** - * Assert that value is a resource. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - */ - public static function isResource($value, $message = null, string $propertyPath = null): bool - { - if (!\is_resource($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not a resource.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_RESOURCE, $propertyPath); - } - - return true; - } - - /** - * Assert that value is an array. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function isArray($value, $message = null, string $propertyPath = null): bool - { - if (!\is_array($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not an array.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_ARRAY, $propertyPath); - } - - return true; - } - - /** - * Assert that value is an array or a traversable object. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function isTraversable($value, $message = null, string $propertyPath = null): bool - { - if (!\is_array($value) && !$value instanceof Traversable) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not an array and does not implement Traversable.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_TRAVERSABLE, $propertyPath); - } - - return true; - } - - /** - * Assert that value is an array or an array-accessible object. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function isArrayAccessible($value, $message = null, string $propertyPath = null): bool - { - if (!\is_array($value) && !$value instanceof ArrayAccess) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not an array and does not implement ArrayAccess.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_ARRAY_ACCESSIBLE, $propertyPath); - } - - return true; - } - - /** - * Assert that value is countable. - * - * @param array|Countable|ResourceBundle|SimpleXMLElement $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function isCountable($value, $message = null, string $propertyPath = null): bool - { - if (\function_exists('is_countable')) { - $assert = \is_countable($value); - } else { - $assert = \is_array($value) || $value instanceof Countable || $value instanceof ResourceBundle || $value instanceof SimpleXMLElement; - } - - if (!$assert) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not an array and does not implement Countable.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_COUNTABLE, $propertyPath); - } - - return true; - } - - /** - * Assert that key exists in an array. - * - * @param mixed $value - * @param string|int $key - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function keyExists($value, $key, $message = null, string $propertyPath = null): bool - { - static::isArray($value, $message, $propertyPath); - - if (!\array_key_exists($key, $value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Array does not contain an element with key "%s"'), - static::stringify($key) - ); - - throw static::createException($value, $message, static::INVALID_KEY_EXISTS, $propertyPath, ['key' => $key]); - } - - return true; - } - - /** - * Assert that key does not exist in an array. - * - * @param mixed $value - * @param string|int $key - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function keyNotExists($value, $key, $message = null, string $propertyPath = null): bool - { - static::isArray($value, $message, $propertyPath); - - if (\array_key_exists($key, $value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Array contains an element with key "%s"'), - static::stringify($key) - ); - - throw static::createException($value, $message, static::INVALID_KEY_NOT_EXISTS, $propertyPath, ['key' => $key]); - } - - return true; - } - - /** - * Assert that key exists in an array/array-accessible object using isset(). - * - * @param mixed $value - * @param string|int $key - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function keyIsset($value, $key, $message = null, string $propertyPath = null): bool - { - static::isArrayAccessible($value, $message, $propertyPath); - - if (!isset($value[$key])) { - $message = \sprintf( - static::generateMessage($message ?: 'The element with key "%s" was not found'), - static::stringify($key) - ); - - throw static::createException($value, $message, static::INVALID_KEY_ISSET, $propertyPath, ['key' => $key]); - } - - return true; - } - - /** - * Assert that key exists in an array/array-accessible object and its value is not empty. - * - * @param mixed $value - * @param string|int $key - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function notEmptyKey($value, $key, $message = null, string $propertyPath = null): bool - { - static::keyIsset($value, $key, $message, $propertyPath); - static::notEmpty($value[$key], $message, $propertyPath); - - return true; - } - - /** - * Assert that value is not blank. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function notBlank($value, $message = null, string $propertyPath = null): bool - { - if (false === $value || (empty($value) && '0' != $value) || (\is_string($value) && '' === \trim($value))) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is blank, but was expected to contain a value.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_NOT_BLANK, $propertyPath); - } - - return true; - } - - /** - * Assert that value is instance of given class-name. - * - * @param mixed $value - * @param string $className - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function isInstanceOf($value, $className, $message = null, string $propertyPath = null): bool - { - if (!($value instanceof $className)) { - $message = \sprintf( - static::generateMessage($message ?: 'Class "%s" was expected to be instanceof of "%s" but is not.'), - static::stringify($value), - $className - ); - - throw static::createException($value, $message, static::INVALID_INSTANCE_OF, $propertyPath, ['class' => $className]); - } - - return true; - } - - /** - * Assert that value is not instance of given class-name. - * - * @param mixed $value - * @param string $className - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function notIsInstanceOf($value, $className, $message = null, string $propertyPath = null): bool - { - if ($value instanceof $className) { - $message = \sprintf( - static::generateMessage($message ?: 'Class "%s" was not expected to be instanceof of "%s".'), - static::stringify($value), - $className - ); - - throw static::createException($value, $message, static::INVALID_NOT_INSTANCE_OF, $propertyPath, ['class' => $className]); - } - - return true; - } - - /** - * Assert that value is subclass of given class-name. - * - * @param mixed $value - * @param string $className - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function subclassOf($value, $className, $message = null, string $propertyPath = null): bool - { - if (!\is_subclass_of($value, $className)) { - $message = \sprintf( - static::generateMessage($message ?: 'Class "%s" was expected to be subclass of "%s".'), - static::stringify($value), - $className - ); - - throw static::createException($value, $message, static::INVALID_SUBCLASS_OF, $propertyPath, ['class' => $className]); - } - - return true; - } - - /** - * Assert that value is in range of numbers. - * - * @param mixed $value - * @param mixed $minValue - * @param mixed $maxValue - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function range($value, $minValue, $maxValue, $message = null, string $propertyPath = null): bool - { - static::numeric($value, $message, $propertyPath); - - if ($value < $minValue || $value > $maxValue) { - $message = \sprintf( - static::generateMessage($message ?: 'Number "%s" was expected to be at least "%d" and at most "%d".'), - static::stringify($value), - static::stringify($minValue), - static::stringify($maxValue) - ); - - throw static::createException($value, $message, static::INVALID_RANGE, $propertyPath, ['min' => $minValue, 'max' => $maxValue]); - } - - return true; - } - - /** - * Assert that a value is at least as big as a given limit. - * - * @param mixed $value - * @param mixed $minValue - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function min($value, $minValue, $message = null, string $propertyPath = null): bool - { - static::numeric($value, $message, $propertyPath); - - if ($value < $minValue) { - $message = \sprintf( - static::generateMessage($message ?: 'Number "%s" was expected to be at least "%s".'), - static::stringify($value), - static::stringify($minValue) - ); - - throw static::createException($value, $message, static::INVALID_MIN, $propertyPath, ['min' => $minValue]); - } - - return true; - } - - /** - * Assert that a number is smaller as a given limit. - * - * @param mixed $value - * @param mixed $maxValue - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function max($value, $maxValue, $message = null, string $propertyPath = null): bool - { - static::numeric($value, $message, $propertyPath); - - if ($value > $maxValue) { - $message = \sprintf( - static::generateMessage($message ?: 'Number "%s" was expected to be at most "%s".'), - static::stringify($value), - static::stringify($maxValue) - ); - - throw static::createException($value, $message, static::INVALID_MAX, $propertyPath, ['max' => $maxValue]); - } - - return true; - } - - /** - * Assert that a file exists. - * - * @param string $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function file($value, $message = null, string $propertyPath = null): bool - { - static::string($value, $message, $propertyPath); - static::notEmpty($value, $message, $propertyPath); - - if (!\is_file($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'File "%s" was expected to exist.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_FILE, $propertyPath); - } - - return true; - } - - /** - * Assert that a directory exists. - * - * @param string $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function directory($value, $message = null, string $propertyPath = null): bool - { - static::string($value, $message, $propertyPath); - - if (!\is_dir($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Path "%s" was expected to be a directory.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_DIRECTORY, $propertyPath); - } - - return true; - } - - /** - * Assert that the value is something readable. - * - * @param string $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function readable($value, $message = null, string $propertyPath = null): bool - { - static::string($value, $message, $propertyPath); - - if (!\is_readable($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Path "%s" was expected to be readable.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_READABLE, $propertyPath); - } - - return true; - } - - /** - * Assert that the value is something writeable. - * - * @param string $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function writeable($value, $message = null, string $propertyPath = null): bool - { - static::string($value, $message, $propertyPath); - - if (!\is_writable($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Path "%s" was expected to be writeable.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_WRITEABLE, $propertyPath); - } - - return true; - } - - /** - * Assert that value is an email address (using input_filter/FILTER_VALIDATE_EMAIL). - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function email($value, $message = null, string $propertyPath = null): bool - { - static::string($value, $message, $propertyPath); - - if (!\filter_var($value, FILTER_VALIDATE_EMAIL)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" was expected to be a valid e-mail address.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_EMAIL, $propertyPath); - } - - return true; - } - - /** - * Assert that value is an URL. - * - * This code snipped was taken from the Symfony project and modified to the special demands of this method. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - * - * @see https://github.com/symfony/Validator/blob/master/Constraints/UrlValidator.php - * @see https://github.com/symfony/Validator/blob/master/Constraints/Url.php - */ - public static function url($value, $message = null, string $propertyPath = null): bool - { - static::string($value, $message, $propertyPath); - - $protocols = ['http', 'https']; - - $pattern = '~^ - (%s):// # protocol - (([\.\pL\pN-]+:)?([\.\pL\pN-]+)@)? # basic auth - ( - ([\pL\pN\pS\-\.])+(\.?([\pL\pN]|xn\-\-[\pL\pN-]+)+\.?) # a domain name - | # or - \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} # an IP address - | # or - \[ - (?:(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){6})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:::(?:(?:(?:[0-9a-f]{1,4})):){5})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){4})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,1}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){3})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,2}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){2})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,3}(?:(?:[0-9a-f]{1,4})))?::(?:(?:[0-9a-f]{1,4})):)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,4}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,5}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,6}(?:(?:[0-9a-f]{1,4})))?::)))) - \] # an IPv6 address - ) - (:[0-9]+)? # a port (optional) - (?:/ (?:[\pL\pN\-._\~!$&\'()*+,;=:@]|%%[0-9A-Fa-f]{2})* )* # a path - (?:\? (?:[\pL\pN\-._\~!$&\'\[\]()*+,;=:@/?]|%%[0-9A-Fa-f]{2})* )? # a query (optional) - (?:\# (?:[\pL\pN\-._\~!$&\'()*+,;=:@/?]|%%[0-9A-Fa-f]{2})* )? # a fragment (optional) - $~ixu'; - - $pattern = \sprintf($pattern, \implode('|', $protocols)); - - if (!\preg_match($pattern, $value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" was expected to be a valid URL starting with http or https'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_URL, $propertyPath); - } - - return true; - } - - /** - * Assert that value is alphanumeric. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function alnum($value, $message = null, string $propertyPath = null): bool - { - try { - static::regex($value, '(^([a-zA-Z]{1}[a-zA-Z0-9]*)$)', $message, $propertyPath); - } catch (Throwable $e) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not alphanumeric, starting with letters and containing only letters and numbers.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_ALNUM, $propertyPath); - } - - return true; - } - - /** - * Assert that the value is boolean True. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function true($value, $message = null, string $propertyPath = null): bool - { - if (true !== $value) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not TRUE.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_TRUE, $propertyPath); - } - - return true; - } - - /** - * Assert that the value is boolean False. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function false($value, $message = null, string $propertyPath = null): bool - { - if (false !== $value) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not FALSE.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_FALSE, $propertyPath); - } - - return true; - } - - /** - * Assert that the class exists. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function classExists($value, $message = null, string $propertyPath = null): bool - { - if (!\class_exists($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Class "%s" does not exist.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_CLASS, $propertyPath); - } - - return true; - } - - /** - * Assert that the interface exists. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function interfaceExists($value, $message = null, string $propertyPath = null): bool - { - if (!\interface_exists($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Interface "%s" does not exist.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_INTERFACE, $propertyPath); - } - - return true; - } - - /** - * Assert that the class implements the interface. - * - * @param mixed $class - * @param string $interfaceName - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function implementsInterface($class, $interfaceName, $message = null, string $propertyPath = null): bool - { - try { - $reflection = new ReflectionClass($class); - if (!$reflection->implementsInterface($interfaceName)) { - $message = \sprintf( - static::generateMessage($message ?: 'Class "%s" does not implement interface "%s".'), - static::stringify($class), - static::stringify($interfaceName) - ); - - throw static::createException($class, $message, static::INTERFACE_NOT_IMPLEMENTED, $propertyPath, ['interface' => $interfaceName]); - } - } catch (ReflectionException $e) { - $message = \sprintf( - static::generateMessage($message ?: 'Class "%s" failed reflection.'), - static::stringify($class) - ); - throw static::createException($class, $message, static::INTERFACE_NOT_IMPLEMENTED, $propertyPath, ['interface' => $interfaceName]); - } - - return true; - } - - /** - * Assert that the given string is a valid json string. - * - * NOTICE: - * Since this does a json_decode to determine its validity - * you probably should consider, when using the variable - * content afterwards, just to decode and check for yourself instead - * of using this assertion. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function isJsonString($value, $message = null, string $propertyPath = null): bool - { - if (null === \json_decode($value) && JSON_ERROR_NONE !== \json_last_error()) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not a valid JSON string.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_JSON_STRING, $propertyPath); - } - - return true; - } - - /** - * Assert that the given string is a valid UUID. - * - * Uses code from {@link https://github.com/ramsey/uuid} that is MIT licensed. - * - * @param string $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function uuid($value, $message = null, string $propertyPath = null): bool - { - $value = \str_replace(['urn:', 'uuid:', '{', '}'], '', $value); - - if ('00000000-0000-0000-0000-000000000000' === $value) { - return true; - } - - if (!\preg_match('/^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$/', $value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not a valid UUID.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_UUID, $propertyPath); - } - - return true; - } - - /** - * Assert that the given string is a valid E164 Phone Number. - * - * @see https://en.wikipedia.org/wiki/E.164 - * - * @param string $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function e164($value, $message = null, string $propertyPath = null): bool - { - if (!\preg_match('/^\+?[1-9]\d{1,14}$/', $value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not a valid E164.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_E164, $propertyPath); - } - - return true; - } - - /** - * Assert that the count of countable is equal to count. - * - * @param array|Countable|ResourceBundle|SimpleXMLElement $countable - * @param int $count - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function count($countable, $count, $message = null, string $propertyPath = null): bool - { - if ($count !== \count($countable)) { - $message = \sprintf( - static::generateMessage($message ?: 'List does not contain exactly %d elements (%d given).'), - static::stringify($count), - static::stringify(\count($countable)) - ); - - throw static::createException($countable, $message, static::INVALID_COUNT, $propertyPath, ['count' => $count]); - } - - return true; - } - - /** - * Assert that the countable have at least $count elements. - * - * @param array|Countable|ResourceBundle|SimpleXMLElement $countable - * @param int $count - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function minCount($countable, $count, $message = null, string $propertyPath = null): bool - { - if ($count > \count($countable)) { - $message = \sprintf( - static::generateMessage($message ?: 'List should have at least %d elements, but has %d elements.'), - static::stringify($count), - static::stringify(\count($countable)) - ); - - throw static::createException($countable, $message, static::INVALID_MIN_COUNT, $propertyPath, ['count' => $count]); - } - - return true; - } - - /** - * Assert that the countable have at most $count elements. - * - * @param array|Countable|ResourceBundle|SimpleXMLElement $countable - * @param int $count - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function maxCount($countable, $count, $message = null, string $propertyPath = null): bool - { - if ($count < \count($countable)) { - $message = \sprintf( - static::generateMessage($message ?: 'List should have at most %d elements, but has %d elements.'), - static::stringify($count), - static::stringify(\count($countable)) - ); - - throw static::createException($countable, $message, static::INVALID_MAX_COUNT, $propertyPath, ['count' => $count]); - } - - return true; - } - - /** - * static call handler to implement: - * - "null or assertion" delegation - * - "all" delegation. - * - * @param string $method - * @param array $args - * - * @return bool|mixed - * - * @throws AssertionFailedException - */ - public static function __callStatic($method, $args) - { - if (0 === \strpos($method, 'nullOr')) { - if (!\array_key_exists(0, $args)) { - throw new BadMethodCallException('Missing the first argument.'); - } - - if (null === $args[0]) { - return true; - } - - $method = \substr($method, 6); - - return \call_user_func_array([\get_called_class(), $method], $args); - } - - if (0 === \strpos($method, 'all')) { - if (!\array_key_exists(0, $args)) { - throw new BadMethodCallException('Missing the first argument.'); - } - - static::isTraversable($args[0]); - - $method = \substr($method, 3); - $values = \array_shift($args); - $calledClass = \get_called_class(); - - foreach ($values as $value) { - \call_user_func_array([$calledClass, $method], \array_merge([$value], $args)); - } - - return true; - } - - throw new BadMethodCallException('No assertion Assertion#'.$method.' exists.'); - } - - /** - * Determines if the values array has every choice as key and that this choice has content. - * - * @param array $values - * @param array $choices - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function choicesNotEmpty(array $values, array $choices, $message = null, string $propertyPath = null): bool - { - static::notEmpty($values, $message, $propertyPath); - - foreach ($choices as $choice) { - static::notEmptyKey($values, $choice, $message, $propertyPath); - } - - return true; - } - - /** - * Determines that the named method is defined in the provided object. - * - * @param string $value - * @param mixed $object - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function methodExists($value, $object, $message = null, string $propertyPath = null): bool - { - static::isObject($object, $message, $propertyPath); - - if (!\method_exists($object, $value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Expected "%s" does not exist in provided object.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_METHOD, $propertyPath, ['object' => \get_class($object)]); - } - - return true; - } - - /** - * Determines that the provided value is an object. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function isObject($value, $message = null, string $propertyPath = null): bool - { - if (!\is_object($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Provided "%s" is not a valid object.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_OBJECT, $propertyPath); - } - - return true; - } - - /** - * Determines if the value is less than given limit. - * - * @param mixed $value - * @param mixed $limit - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function lessThan($value, $limit, $message = null, string $propertyPath = null): bool - { - if ($value >= $limit) { - $message = \sprintf( - static::generateMessage($message ?: 'Provided "%s" is not less than "%s".'), - static::stringify($value), - static::stringify($limit) - ); - - throw static::createException($value, $message, static::INVALID_LESS, $propertyPath, ['limit' => $limit]); - } - - return true; - } - - /** - * Determines if the value is less or equal than given limit. - * - * @param mixed $value - * @param mixed $limit - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function lessOrEqualThan($value, $limit, $message = null, string $propertyPath = null): bool - { - if ($value > $limit) { - $message = \sprintf( - static::generateMessage($message ?: 'Provided "%s" is not less or equal than "%s".'), - static::stringify($value), - static::stringify($limit) - ); - - throw static::createException($value, $message, static::INVALID_LESS_OR_EQUAL, $propertyPath, ['limit' => $limit]); - } - - return true; - } - - /** - * Determines if the value is greater than given limit. - * - * @param mixed $value - * @param mixed $limit - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function greaterThan($value, $limit, $message = null, string $propertyPath = null): bool - { - if ($value <= $limit) { - $message = \sprintf( - static::generateMessage($message ?: 'Provided "%s" is not greater than "%s".'), - static::stringify($value), - static::stringify($limit) - ); - - throw static::createException($value, $message, static::INVALID_GREATER, $propertyPath, ['limit' => $limit]); - } - - return true; - } - - /** - * Determines if the value is greater or equal than given limit. - * - * @param mixed $value - * @param mixed $limit - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function greaterOrEqualThan($value, $limit, $message = null, string $propertyPath = null): bool - { - if ($value < $limit) { - $message = \sprintf( - static::generateMessage($message ?: 'Provided "%s" is not greater or equal than "%s".'), - static::stringify($value), - static::stringify($limit) - ); - - throw static::createException($value, $message, static::INVALID_GREATER_OR_EQUAL, $propertyPath, ['limit' => $limit]); - } - - return true; - } - - /** - * Assert that a value is greater or equal than a lower limit, and less than or equal to an upper limit. - * - * @param mixed $value - * @param mixed $lowerLimit - * @param mixed $upperLimit - * @param string|callable|null $message - * @param string $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function between($value, $lowerLimit, $upperLimit, $message = null, string $propertyPath = null): bool - { - if ($lowerLimit > $value || $value > $upperLimit) { - $message = \sprintf( - static::generateMessage($message ?: 'Provided "%s" is neither greater than or equal to "%s" nor less than or equal to "%s".'), - static::stringify($value), - static::stringify($lowerLimit), - static::stringify($upperLimit) - ); - - throw static::createException($value, $message, static::INVALID_BETWEEN, $propertyPath, ['lower' => $lowerLimit, 'upper' => $upperLimit]); - } - - return true; - } - - /** - * Assert that a value is greater than a lower limit, and less than an upper limit. - * - * @param mixed $value - * @param mixed $lowerLimit - * @param mixed $upperLimit - * @param string|callable|null $message - * @param string $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function betweenExclusive($value, $lowerLimit, $upperLimit, $message = null, string $propertyPath = null): bool - { - if ($lowerLimit >= $value || $value >= $upperLimit) { - $message = \sprintf( - static::generateMessage($message ?: 'Provided "%s" is neither greater than "%s" nor less than "%s".'), - static::stringify($value), - static::stringify($lowerLimit), - static::stringify($upperLimit) - ); - - throw static::createException($value, $message, static::INVALID_BETWEEN_EXCLUSIVE, $propertyPath, ['lower' => $lowerLimit, 'upper' => $upperLimit]); - } - - return true; - } - - /** - * Assert that extension is loaded. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function extensionLoaded($value, $message = null, string $propertyPath = null): bool - { - if (!\extension_loaded($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Extension "%s" is required.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_EXTENSION, $propertyPath); - } - - return true; - } - - /** - * Assert that date is valid and corresponds to the given format. - * - * @param string $value - * @param string $format supports all of the options date(), except for the following: - * N, w, W, t, L, o, B, a, A, g, h, I, O, P, Z, c, r - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - * - * @see http://php.net/manual/function.date.php#refsect1-function.date-parameters - */ - public static function date($value, $format, $message = null, string $propertyPath = null): bool - { - static::string($value, $message, $propertyPath); - static::string($format, $message, $propertyPath); - - $dateTime = DateTime::createFromFormat('!'.$format, $value); - - if (false === $dateTime || $value !== $dateTime->format($format)) { - $message = \sprintf( - static::generateMessage($message ?: 'Date "%s" is invalid or does not match format "%s".'), - static::stringify($value), - static::stringify($format) - ); - - throw static::createException($value, $message, static::INVALID_DATE, $propertyPath, ['format' => $format]); - } - - return true; - } - - /** - * Assert that the value is an object, or a class that exists. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function objectOrClass($value, $message = null, string $propertyPath = null): bool - { - if (!\is_object($value)) { - static::classExists($value, $message, $propertyPath); - } - - return true; - } - - /** - * Assert that the value is an object or class, and that the property exists. - * - * @param mixed $value - * @param string $property - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function propertyExists($value, $property, $message = null, string $propertyPath = null): bool - { - static::objectOrClass($value); - - if (!\property_exists($value, $property)) { - $message = \sprintf( - static::generateMessage($message ?: 'Class "%s" does not have property "%s".'), - static::stringify($value), - static::stringify($property) - ); - - throw static::createException($value, $message, static::INVALID_PROPERTY, $propertyPath, ['property' => $property]); - } - - return true; - } - - /** - * Assert that the value is an object or class, and that the properties all exist. - * - * @param mixed $value - * @param array $properties - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function propertiesExist($value, array $properties, $message = null, string $propertyPath = null): bool - { - static::objectOrClass($value); - static::allString($properties, $message, $propertyPath); - - $invalidProperties = []; - foreach ($properties as $property) { - if (!\property_exists($value, $property)) { - $invalidProperties[] = $property; - } - } - - if ($invalidProperties) { - $message = \sprintf( - static::generateMessage($message ?: 'Class "%s" does not have these properties: %s.'), - static::stringify($value), - static::stringify(\implode(', ', $invalidProperties)) - ); - - throw static::createException($value, $message, static::INVALID_PROPERTY, $propertyPath, ['properties' => $properties]); - } - - return true; - } - - /** - * Assert comparison of two versions. - * - * @param string $version1 - * @param string $operator - * @param string $version2 - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function version($version1, $operator, $version2, $message = null, string $propertyPath = null): bool - { - static::notEmpty($operator, 'versionCompare operator is required and cannot be empty.'); - - if (true !== \version_compare($version1, $version2, $operator)) { - $message = \sprintf( - static::generateMessage($message ?: 'Version "%s" is not "%s" version "%s".'), - static::stringify($version1), - static::stringify($operator), - static::stringify($version2) - ); - - throw static::createException($version1, $message, static::INVALID_VERSION, $propertyPath, ['operator' => $operator, 'version' => $version2]); - } - - return true; - } - - /** - * Assert on PHP version. - * - * @param string $operator - * @param mixed $version - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function phpVersion($operator, $version, $message = null, string $propertyPath = null): bool - { - static::defined('PHP_VERSION'); - - return static::version(PHP_VERSION, $operator, $version, $message, $propertyPath); - } - - /** - * Assert that extension is loaded and a specific version is installed. - * - * @param string $extension - * @param string $operator - * @param mixed $version - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function extensionVersion($extension, $operator, $version, $message = null, string $propertyPath = null): bool - { - static::extensionLoaded($extension, $message, $propertyPath); - - return static::version(\phpversion($extension), $operator, $version, $message, $propertyPath); - } - - /** - * Determines that the provided value is callable. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function isCallable($value, $message = null, string $propertyPath = null): bool - { - if (!\is_callable($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Provided "%s" is not a callable.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_CALLABLE, $propertyPath); - } - - return true; - } - - /** - * Assert that the provided value is valid according to a callback. - * - * If the callback returns `false` the assertion will fail. - * - * @param mixed $value - * @param callable $callback - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function satisfy($value, $callback, $message = null, string $propertyPath = null): bool - { - static::isCallable($callback); - - if (false === \call_user_func($callback, $value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Provided "%s" is invalid according to custom rule.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_SATISFY, $propertyPath); - } - - return true; - } - - /** - * Assert that value is an IPv4 or IPv6 address - * (using input_filter/FILTER_VALIDATE_IP). - * - * @param string $value - * @param int|null $flag - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - * - * @see http://php.net/manual/filter.filters.flags.php - */ - public static function ip($value, $flag = null, $message = null, string $propertyPath = null): bool - { - static::string($value, $message, $propertyPath); - if (!\filter_var($value, FILTER_VALIDATE_IP, $flag)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" was expected to be a valid IP address.'), - static::stringify($value) - ); - throw static::createException($value, $message, static::INVALID_IP, $propertyPath, ['flag' => $flag]); - } - - return true; - } - - /** - * Assert that value is an IPv4 address - * (using input_filter/FILTER_VALIDATE_IP). - * - * @param string $value - * @param int|null $flag - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - * - * @see http://php.net/manual/filter.filters.flags.php - */ - public static function ipv4($value, $flag = null, $message = null, string $propertyPath = null): bool - { - static::ip($value, $flag | FILTER_FLAG_IPV4, static::generateMessage($message ?: 'Value "%s" was expected to be a valid IPv4 address.'), $propertyPath); - - return true; - } - - /** - * Assert that value is an IPv6 address - * (using input_filter/FILTER_VALIDATE_IP). - * - * @param string $value - * @param int|null $flag - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - * - * @see http://php.net/manual/filter.filters.flags.php - */ - public static function ipv6($value, $flag = null, $message = null, string $propertyPath = null): bool - { - static::ip($value, $flag | FILTER_FLAG_IPV6, static::generateMessage($message ?: 'Value "%s" was expected to be a valid IPv6 address.'), $propertyPath); - - return true; - } - - /** - * Assert that a constant is defined. - * - * @param mixed $constant - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - */ - public static function defined($constant, $message = null, string $propertyPath = null): bool - { - if (!\defined($constant)) { - $message = \sprintf(static::generateMessage($message ?: 'Value "%s" expected to be a defined constant.'), $constant); - - throw static::createException($constant, $message, static::INVALID_CONSTANT, $propertyPath); - } - - return true; - } - - /** - * Assert that a constant is defined. - * - * @param string $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function base64($value, $message = null, string $propertyPath = null): bool - { - if (false === \base64_decode($value, true)) { - $message = \sprintf(static::generateMessage($message ?: 'Value "%s" is not a valid base64 string.'), $value); - - throw static::createException($value, $message, static::INVALID_BASE64, $propertyPath); - } - - return true; - } - - /** - * Helper method that handles building the assertion failure exceptions. - * They are returned from this method so that the stack trace still shows - * the assertions method. - * - * @param mixed $value - * @param string|callable|null $message - * @param int $code - * @param string|null $propertyPath - * @param array $constraints - * - * @return mixed - */ - protected static function createException($value, $message, $code, string $propertyPath = null, array $constraints = []) - { - $exceptionClass = static::$exceptionClass; - - return new $exceptionClass($message, $code, $propertyPath, $value, $constraints); - } - - /** - * Make a string version of a value. - * - * @param mixed $value - * - * @return string - */ - protected static function stringify($value): string - { - $result = \gettype($value); - - if (\is_bool($value)) { - $result = $value ? '' : ''; - } elseif (\is_scalar($value)) { - $val = (string)$value; - - if (\strlen($val) > 100) { - $val = \substr($val, 0, 97).'...'; - } - - $result = $val; - } elseif (\is_array($value)) { - $result = ''; - } elseif (\is_object($value)) { - $result = \get_class($value); - } elseif (\is_resource($value)) { - $result = \get_resource_type($value); - } elseif (null === $value) { - $result = ''; - } - - return $result; - } - - /** - * Generate the message. - * - * @param string|callable|null $message - * - * @return string - */ - protected static function generateMessage($message): string - { - if (\is_callable($message)) { - $traces = \debug_backtrace(0); - - $parameters = []; - - try { - $reflection = new ReflectionClass($traces[1]['class']); - $method = $reflection->getMethod($traces[1]['function']); - foreach ($method->getParameters() as $index => $parameter) { - if ('message' !== $parameter->getName()) { - $parameters[$parameter->getName()] = \array_key_exists($index, $traces[1]['args']) - ? $traces[1]['args'][$index] - : $parameter->getDefaultValue(); - } - } - - $parameters['::assertion'] = \sprintf('%s%s%s', $traces[1]['class'], $traces[1]['type'], $traces[1]['function']); - - $message = \call_user_func_array($message, [$parameters]); - } // @codeCoverageIgnoreStart - catch (Throwable $exception) { - $message = \sprintf('Unable to generate message : %s', $exception->getMessage()); - } // @codeCoverageIgnoreEnd - } - - return (string)$message; - } -} diff --git a/admin/tool/mfa/factor/totp/extlib/Assert/AssertionFailedException.php b/admin/tool/mfa/factor/totp/extlib/Assert/AssertionFailedException.php deleted file mode 100644 index bf0334fe6f5..00000000000 --- a/admin/tool/mfa/factor/totp/extlib/Assert/AssertionFailedException.php +++ /dev/null @@ -1,35 +0,0 @@ -propertyPath = $propertyPath; - $this->value = $value; - $this->constraints = $constraints; - } - - /** - * User controlled way to define a sub-property causing - * the failure of a currently asserted objects. - * - * Useful to transport information about the nature of the error - * back to higher layers. - * - * @return string|null - */ - public function getPropertyPath() - { - return $this->propertyPath; - } - - /** - * Get the value that caused the assertion to fail. - * - * @return mixed - */ - public function getValue() - { - return $this->value; - } - - /** - * Get the constraints that applied to the failed assertion. - * - * @return array - */ - public function getConstraints(): array - { - return $this->constraints; - } -} \ No newline at end of file diff --git a/admin/tool/mfa/factor/totp/extlib/Assert/LICENSE b/admin/tool/mfa/factor/totp/extlib/Assert/LICENSE deleted file mode 100644 index 43672e7e62d..00000000000 --- a/admin/tool/mfa/factor/totp/extlib/Assert/LICENSE +++ /dev/null @@ -1,11 +0,0 @@ -Copyright (c) 2011-2013, Benjamin Eberlei -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -- Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. -- Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. diff --git a/admin/tool/mfa/factor/totp/extlib/Assert/composer.json b/admin/tool/mfa/factor/totp/extlib/Assert/composer.json deleted file mode 100644 index 37784796a9b..00000000000 --- a/admin/tool/mfa/factor/totp/extlib/Assert/composer.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "beberlei/assert", - "description": "Thin assertion library for input validation in business models.", - "authors": [ - {"name": "Benjamin Eberlei", "email": "kontakt@beberlei.de"} - ], - "license": "BSD-2-Clause", - "keywords": ["assert", "assertion", "validation"], - "require": { - "ext-mbstring": "*" - }, - "autoload": { - "psr-0": { - "Assert": "lib/" - }, - "files": ["lib/Assert/functions.php"] - }, - "extra": { - "branch-alias": { - "dev-master": "2.0.x-dev" - } - } -} diff --git a/admin/tool/mfa/factor/totp/extlib/Assert/readme_moodle.txt b/admin/tool/mfa/factor/totp/extlib/Assert/readme_moodle.txt deleted file mode 100644 index bccc0a3edbf..00000000000 --- a/admin/tool/mfa/factor/totp/extlib/Assert/readme_moodle.txt +++ /dev/null @@ -1,17 +0,0 @@ -Assert 2.1 --------------- -https://github.com/beberlei/assert/releases/tag/v2.1 - -Instructions to import WebAuthn into Moodle: - -1. Download the latest release from https://github.com/beberlei/assert/releases/tag/vx.x - (choose "Source code") -2. Unzip the source code -3. Copy the following files from assert-x.x/lib/Assert into admin/tool/mfa/factor/totp/extlib/Assert: - 1. Assertion.php - 2. AssertionFailedException.php - 3. InvalidArgumentException.php - -4. Copy the following files from assert-x.x into admin/tool/mfa/factor/totp/extlib/Assert: - 1. LICENSE - 2. composer.json diff --git a/admin/tool/mfa/factor/totp/tests/factor_test.php b/admin/tool/mfa/factor/totp/tests/factor_test.php index ff09290a523..d9376022006 100644 --- a/admin/tool/mfa/factor/totp/tests/factor_test.php +++ b/admin/tool/mfa/factor/totp/tests/factor_test.php @@ -24,9 +24,6 @@ require_once(__DIR__.'/../extlib/OTPHP/ParameterTrait.php'); require_once(__DIR__.'/../extlib/OTPHP/OTP.php'); require_once(__DIR__.'/../extlib/OTPHP/TOTP.php'); -require_once(__DIR__.'/../extlib/Assert/Assertion.php'); -require_once(__DIR__.'/../extlib/Assert/AssertionFailedException.php'); -require_once(__DIR__.'/../extlib/Assert/InvalidArgumentException.php'); require_once(__DIR__.'/../extlib/ParagonIE/ConstantTime/EncoderInterface.php'); require_once(__DIR__.'/../extlib/ParagonIE/ConstantTime/Binary.php'); require_once(__DIR__.'/../extlib/ParagonIE/ConstantTime/Base32.php'); diff --git a/admin/tool/mfa/factor/totp/thirdpartylibs.xml b/admin/tool/mfa/factor/totp/thirdpartylibs.xml index 3b7eea47169..734b191277a 100644 --- a/admin/tool/mfa/factor/totp/thirdpartylibs.xml +++ b/admin/tool/mfa/factor/totp/thirdpartylibs.xml @@ -1,12 +1,5 @@ - - extlib/Assert - Assert - 2.1 - MIT - https://github.com/beberlei/assert - extlib/OTPHP OTPHP From dc25c83a5295921a526829c438c6843a2ddc48a2 Mon Sep 17 00:00:00 2001 From: Daniel Ziegenberg Date: Fri, 15 Mar 2024 13:18:54 +0100 Subject: [PATCH 3/4] MDL-79678 tool_mfa: Adapt to OTPHP changes in v11 With the OTPHP upgrade from v10.x to v11.x, the behaviour of the window feature changed substantially. With version 10, the window of timestamps goes from `timestamp - window * period` to `timestamp + window * period`. For example, if the window is 5, the period 30 and the timestamp 1476822000, the OTP tested are within 1476821850 (`1476822000 - 5 * 30`) and 1476822150 (`1476822000 + 5 * 30`). In other words, this validated the 5 OTP before and after the current timestamp. With version 11, the TOTP window acts as a time drift. If the window is 15, the period 30, and the current timestamp is 147682209, the OTP tested are within 147682194 (`147682209 - 15`), 147682209 and 147682224 (`147682209 + 15`). The window shall be lower than the period. Therefore, this test includes the previous OTP but not the next one. This change required an adaption to align our implementation with OTPHP. The window of valid TOTP tokens is now much narrower. This change in functionality is a security improvement, but it also means that the time on the device generating the TOTP token must be more accurate. As OTPHP restricts the window to be strictly lower than the period, our admin setting now has a maximum allowed value of 29. To ensure we only have valid window values, we need to update the admin setting to a value lower than 30; therefore, we include an upgrade step. Signed-off-by: Daniel Ziegenberg --- admin/tool/mfa/factor/totp/classes/factor.php | 55 ++++++++++--------- admin/tool/mfa/factor/totp/db/upgrade.php | 43 +++++++++++++++ .../mfa/factor/totp/lang/en/factor_totp.php | 7 ++- admin/tool/mfa/factor/totp/settings.php | 6 +- .../mfa/factor/totp/tests/factor_test.php | 18 ++---- admin/tool/mfa/factor/totp/version.php | 4 +- 6 files changed, 89 insertions(+), 44 deletions(-) create mode 100644 admin/tool/mfa/factor/totp/db/upgrade.php diff --git a/admin/tool/mfa/factor/totp/classes/factor.php b/admin/tool/mfa/factor/totp/classes/factor.php index 88911b6987e..ce4f4ad6239 100644 --- a/admin/tool/mfa/factor/totp/classes/factor.php +++ b/admin/tool/mfa/factor/totp/classes/factor.php @@ -29,6 +29,7 @@ require_once(__DIR__.'/../extlib/ParagonIE/ConstantTime/EncoderInterface.php'); require_once(__DIR__.'/../extlib/ParagonIE/ConstantTime/Binary.php'); require_once(__DIR__.'/../extlib/ParagonIE/ConstantTime/Base32.php'); +use MoodleQuickForm; use tool_mfa\local\factor\object_factor_base; use OTPHP\TOTP; use stdClass; @@ -116,10 +117,10 @@ class factor extends object_factor_base { /** * TOTP Factor implementation. * - * @param \MoodleQuickForm $mform - * @return \MoodleQuickForm $mform + * @param MoodleQuickForm $mform + * @return MoodleQuickForm $mform */ - public function setup_factor_form_definition(\MoodleQuickForm $mform): \MoodleQuickForm { + public function setup_factor_form_definition(MoodleQuickForm $mform): MoodleQuickForm { $secret = $this->generate_secret_code(); $mform->addElement('hidden', 'secret', $secret); $mform->setType('secret', PARAM_ALPHANUM); @@ -130,10 +131,10 @@ class factor extends object_factor_base { /** * TOTP Factor implementation. * - * @param \MoodleQuickForm $mform - * @return \MoodleQuickForm $mform + * @param MoodleQuickForm $mform + * @return MoodleQuickForm $mform */ - public function setup_factor_form_definition_after_data(\MoodleQuickForm $mform): \MoodleQuickForm { + public function setup_factor_form_definition_after_data(MoodleQuickForm $mform): MoodleQuickForm { global $OUTPUT, $SITE, $USER; // Array of elements to allow XSS. @@ -242,10 +243,10 @@ class factor extends object_factor_base { /** * TOTP Factor implementation. * - * @param \MoodleQuickForm $mform - * @return \MoodleQuickForm $mform + * @param MoodleQuickForm $mform + * @return MoodleQuickForm $mform */ - public function login_form_definition(\MoodleQuickForm $mform): \MoodleQuickForm { + public function login_form_definition(MoodleQuickForm $mform): MoodleQuickForm { $mform->disable_form_change_checker(); $mform->addElement(new \tool_mfa\local\form\verification_field()); @@ -264,12 +265,10 @@ class factor extends object_factor_base { global $USER; $factors = $this->get_active_user_factors($USER); $result = ['verificationcode' => get_string('error:wrongverification', 'factor_totp')]; - $windowconfig = get_config('factor_totp', 'window'); + $window = get_config('factor_totp', 'window'); foreach ($factors as $factor) { $totp = TOTP::create($factor->secret); - // Convert seconds to windows. - $window = (int) floor($windowconfig / $totp->getPeriod()); $factorresult = $this->validate_code($data['verificationcode'], $window, $totp, $factor); $time = userdate(time(), get_string('systimeformat', 'factor_totp')); @@ -311,23 +310,27 @@ class factor extends object_factor_base { return self::TOTP_USED; } - // The window in which to check for clock skew, 5 increments past valid window. - $skewwindow = $window + 5; - $pasttimestamp = time() - ($skewwindow * $totp->getPeriod()); - $futuretimestamp = time() + ($skewwindow * $totp->getPeriod()); - + // Check if the code is valid, returning early. if ($totp->verify($code, time(), $window)) { return self::TOTP_VALID; - } else if ($totp->verify($code, $pasttimestamp, $skewwindow)) { - // Check for clock skew in the past 10 periods. - return self::TOTP_OLD; - } else if ($totp->verify($code, $futuretimestamp, $skewwindow)) { - // Check for clock skew in the future 10 periods. - return self::TOTP_FUTURE; - } else { - // In all other cases, code is invalid. - return self::TOTP_INVALID; } + + // Check for clock skew in the past and future 10 periods. + for ($i = 1; $i <= 10; $i++) { + $pasttimestamp = time() - $i * $totp->getPeriod(); + $futuretimestamp = time() + $i * $totp->getPeriod(); + + if ($totp->verify($code, $pasttimestamp, $window)) { + return self::TOTP_OLD; + } + + if ($totp->verify($code, $futuretimestamp, $window)) { + return self::TOTP_FUTURE; + } + } + + // In all other cases, the code is invalid. + return self::TOTP_INVALID; } /** diff --git a/admin/tool/mfa/factor/totp/db/upgrade.php b/admin/tool/mfa/factor/totp/db/upgrade.php new file mode 100644 index 00000000000..0676bfcaebc --- /dev/null +++ b/admin/tool/mfa/factor/totp/db/upgrade.php @@ -0,0 +1,43 @@ +. + +/** + * factor_totp upgrade library. + * + * @package factor_totp + * @copyright 2024 Daniel Ziegenberg + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +/** + * Factor totp upgrade helper function + * + * @param int $oldversion + */ +function xmldb_factor_totp_upgrade($oldversion): bool { + if ($oldversion < 2024081600) { + + $window = get_config('factor_totp', 'window'); + if ($window && $window >= 30) { + set_config('window', 29, 'factor_totp'); + } + + // Savepoint reached. + upgrade_plugin_savepoint(true, 2024081600, 'factor', 'auth'); + } + + return true; +} diff --git a/admin/tool/mfa/factor/totp/lang/en/factor_totp.php b/admin/tool/mfa/factor/totp/lang/en/factor_totp.php index 4e471a97f80..bd532808c87 100644 --- a/admin/tool/mfa/factor/totp/lang/en/factor_totp.php +++ b/admin/tool/mfa/factor/totp/lang/en/factor_totp.php @@ -54,8 +54,11 @@ $string['revokefactorconfirmation'] = 'Remove \'{$a}\' authenticator app?'; $string['settings:totplink'] = 'Show mobile app setup link'; $string['settings:totplink_help'] = 'If enabled the user will see a 3rd setup option with a direct otpauth:// link'; $string['settings:window'] = 'TOTP verification window'; -$string['settings:window_help'] = 'How long each code is valid for. You can set this to a higher value as a workaround if your users device clocks are often slightly wrong. -Rounded down to the nearest 30 seconds, which is the time between new generated codes.'; +$string['settings:window_help'] = 'The window of TOTP acts as time drift and specifies how long each code is valid for. + The period, which is the time between newly generated codes, is 30 seconds. + If the window is 15 (the default) and the current timestamp is 147682209, the OTP tested are within 147682194 (147682209 - 15), 147682209 and 147682224 (147682209 + 15). + The window shall be lower than 30. Therefore, this test includes the previous OTP but not the next one. + You can set this to a higher value (up to 29) as a workaround if your user\'s device clocks are often slightly wrong.'; $string['setupfactor'] = 'Set up authenticator app'; $string['setupfactorbutton'] = 'Set up'; $string['setupfactor:account'] = 'Account:'; diff --git a/admin/tool/mfa/factor/totp/settings.php b/admin/tool/mfa/factor/totp/settings.php index d2189c8a48d..7e752d865e7 100644 --- a/admin/tool/mfa/factor/totp/settings.php +++ b/admin/tool/mfa/factor/totp/settings.php @@ -38,9 +38,11 @@ $settings->add(new admin_setting_configtext('factor_totp/weight', new lang_string('settings:weight', 'tool_mfa'), new lang_string('settings:weight_help', 'tool_mfa'), 100, PARAM_INT)); -$settings->add(new admin_setting_configduration('factor_totp/window', +$window = new admin_setting_configduration('factor_totp/window', new lang_string('settings:window', 'factor_totp'), - new lang_string('settings:window_help', 'factor_totp'), 30)); + new lang_string('settings:window_help', 'factor_totp'), 15); +$window->set_max_duration(29); +$settings->add($window); $settings->add(new admin_setting_configcheckbox('factor_totp/totplink', new lang_string('settings:totplink', 'factor_totp'), diff --git a/admin/tool/mfa/factor/totp/tests/factor_test.php b/admin/tool/mfa/factor/totp/tests/factor_test.php index d9376022006..34ce1ade101 100644 --- a/admin/tool/mfa/factor/totp/tests/factor_test.php +++ b/admin/tool/mfa/factor/totp/tests/factor_test.php @@ -50,7 +50,7 @@ class factor_test extends \advanced_testcase { $this->setUser($user); // Setup test staples. $totp = \OTPHP\TOTP::create('fakekey'); - $window = 10; + $window = 29; set_config('enabled', 1, 'factor_totp'); $totpfactor = \tool_mfa\plugininfo\factor::get_factor('totp'); @@ -67,21 +67,15 @@ class factor_test extends \advanced_testcase { $result = $totpfactor->validate_code($code, $window, $totp, $factorinstance); $this->assertEquals($totpfactor::TOTP_VALID, $result); - // Now update timeverified to 2 mins ago, and check codes within window are blocked. - $code = $totp->at(time() - (2 * MINSECS)); - $DB->set_field('tool_mfa', 'lastverified', time() - (2 * MINSECS), ['id' => $factorinstance->id]); + // Now update timeverified to 45 seconds ago, and check codes within window is blocked. + $code = $totp->at(time() - (20)); + $DB->set_field('tool_mfa', 'lastverified', time() - (20), ['id' => $factorinstance->id]); $result = $totpfactor->validate_code($code, $window, $totp, $factorinstance); $this->assertEquals($totpfactor::TOTP_USED, $result); - // Now update timeverified to 2 mins ago, and check codes within window are blocked. + // Now update timeverified to 45 seconds ago, and check code from current increment within window is blocked. $code = $totp->at(time()); - $DB->set_field('tool_mfa', 'lastverified', time() - (2 * MINSECS), ['id' => $factorinstance->id]); - $result = $totpfactor->validate_code($code, $window, $totp, $factorinstance); - $this->assertEquals($totpfactor::TOTP_USED, $result); - - // Now update timeverified to 2 mins ago, and check codes within window are blocked. - $code = $totp->at(time() - (4 * MINSECS)); - $DB->set_field('tool_mfa', 'lastverified', time() - (2 * MINSECS), ['id' => $factorinstance->id]); + $DB->set_field('tool_mfa', 'lastverified', time() - (20), ['id' => $factorinstance->id]); $result = $totpfactor->validate_code($code, $window, $totp, $factorinstance); $this->assertEquals($totpfactor::TOTP_USED, $result); diff --git a/admin/tool/mfa/factor/totp/version.php b/admin/tool/mfa/factor/totp/version.php index 726d89d90d5..935a9d51bdf 100644 --- a/admin/tool/mfa/factor/totp/version.php +++ b/admin/tool/mfa/factor/totp/version.php @@ -26,7 +26,7 @@ defined('MOODLE_INTERNAL') || die(); -$plugin->version = 2024042200; // The current plugin version (Date: YYYYMMDDXX). -$plugin->requires = 2024041600; // Requires this Moodle version. +$plugin->version = 2024081600; // The current plugin version (Date: YYYYMMDDXX). +$plugin->requires = 2024041600; // Requires this Moodle version. $plugin->component = 'factor_totp'; // Full name of the plugin (used for diagnostics). $plugin->maturity = MATURITY_STABLE; From 229b0dc6bf15a0da18a9ed314a360e6ef4689417 Mon Sep 17 00:00:00 2001 From: Daniel Ziegenberg Date: Fri, 14 Jun 2024 22:57:16 +0200 Subject: [PATCH 4/4] MDL-79678 tool_mfa: use DI and PSR-20: clock As the OTPHP library now utilizes a PSR-20: clock we can make use of it. Also the the parameter '' will become mandatory in 12.0.0. So we are asked to set a valid PSR Clock implementation instead of 'null'. Signed-off-by: Daniel Ziegenberg --- admin/tool/mfa/factor/totp/classes/factor.php | 37 +++++++++++++------ .../mfa/factor/totp/tests/factor_test.php | 33 +++++++++-------- 2 files changed, 44 insertions(+), 26 deletions(-) diff --git a/admin/tool/mfa/factor/totp/classes/factor.php b/admin/tool/mfa/factor/totp/classes/factor.php index ce4f4ad6239..131b9dd4081 100644 --- a/admin/tool/mfa/factor/totp/classes/factor.php +++ b/admin/tool/mfa/factor/totp/classes/factor.php @@ -33,6 +33,8 @@ use MoodleQuickForm; use tool_mfa\local\factor\object_factor_base; use OTPHP\TOTP; use stdClass; +use core\clock; +use core\di; /** * TOTP factor class. @@ -63,6 +65,19 @@ class factor extends object_factor_base { /** @var string Factor icon */ protected $icon = 'fa-mobile-screen'; + /** @var clock */ + private readonly clock $clock; + + /** + * Constructor. + * + * @param string $name + */ + public function __construct(string $name) { + parent::__construct($name); + $this->clock = di::get(clock::class); + } + /** * Generates TOTP URI for given secret key. @@ -77,7 +92,7 @@ class factor extends object_factor_base { $host = parse_url($CFG->wwwroot, PHP_URL_HOST); $sitename = str_replace(':', '', $SITE->fullname); $issuer = $sitename.' '.$host; - $totp = TOTP::create($secret); + $totp = TOTP::create($secret, clock: $this->clock); $totp->setLabel($USER->username); $totp->setIssuer($issuer); return $totp->getProvisioningUri(); @@ -232,8 +247,8 @@ class factor extends object_factor_base { public function setup_factor_form_validation(array $data): array { $errors = []; - $totp = TOTP::create($data['secret']); - if (!$totp->verify($data['verificationcode'], time(), 1)) { + $totp = TOTP::create($data['secret'], clock: $this->clock); + if (!$totp->verify($data['verificationcode'], $this->clock->time(), 1)) { $errors['verificationcode'] = get_string('error:wrongverification', 'factor_totp'); } @@ -268,9 +283,9 @@ class factor extends object_factor_base { $window = get_config('factor_totp', 'window'); foreach ($factors as $factor) { - $totp = TOTP::create($factor->secret); + $totp = TOTP::create($factor->secret, clock: $this->clock); $factorresult = $this->validate_code($data['verificationcode'], $window, $totp, $factor); - $time = userdate(time(), get_string('systimeformat', 'factor_totp')); + $time = userdate($this->clock->time(), get_string('systimeformat', 'factor_totp')); switch ($factorresult) { case self::TOTP_USED: @@ -311,14 +326,14 @@ class factor extends object_factor_base { } // Check if the code is valid, returning early. - if ($totp->verify($code, time(), $window)) { + if ($totp->verify($code, $this->clock->time(), $window)) { return self::TOTP_VALID; } // Check for clock skew in the past and future 10 periods. for ($i = 1; $i <= 10; $i++) { - $pasttimestamp = time() - $i * $totp->getPeriod(); - $futuretimestamp = time() + $i * $totp->getPeriod(); + $pasttimestamp = $this->clock->time() - $i * $totp->getPeriod(); + $futuretimestamp = $this->clock->time() + $i * $totp->getPeriod(); if ($totp->verify($code, $pasttimestamp, $window)) { return self::TOTP_OLD; @@ -339,7 +354,7 @@ class factor extends object_factor_base { * @return string */ public function generate_secret_code(): string { - $totp = TOTP::create(); + $totp = TOTP::create(clock: $this->clock); return substr($totp->getSecret(), 0, 16); } @@ -358,9 +373,9 @@ class factor extends object_factor_base { $row->factor = $this->name; $row->secret = $data->secret; $row->label = $data->devicename; - $row->timecreated = time(); + $row->timecreated = $this->clock->time(); $row->createdfromip = $USER->lastip; - $row->timemodified = time(); + $row->timemodified = $this->clock->time(); $row->lastverified = 0; $row->revoked = 0; diff --git a/admin/tool/mfa/factor/totp/tests/factor_test.php b/admin/tool/mfa/factor/totp/tests/factor_test.php index 34ce1ade101..79203d0357e 100644 --- a/admin/tool/mfa/factor/totp/tests/factor_test.php +++ b/admin/tool/mfa/factor/totp/tests/factor_test.php @@ -21,6 +21,7 @@ defined('MOODLE_INTERNAL') || die(); require_once(__DIR__.'/../extlib/OTPHP/OTPInterface.php'); require_once(__DIR__.'/../extlib/OTPHP/TOTPInterface.php'); require_once(__DIR__.'/../extlib/OTPHP/ParameterTrait.php'); +require_once(__DIR__.'/../extlib/OTPHP/InternalClock.php'); require_once(__DIR__.'/../extlib/OTPHP/OTP.php'); require_once(__DIR__.'/../extlib/OTPHP/TOTP.php'); @@ -37,7 +38,7 @@ require_once(__DIR__.'/../extlib/ParagonIE/ConstantTime/Base32.php'); * @copyright Catalyst IT * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class factor_test extends \advanced_testcase { +final class factor_test extends \advanced_testcase { /** * Test code validation of the TOTP factor @@ -45,11 +46,13 @@ class factor_test extends \advanced_testcase { public function test_validate_code(): void { global $DB; + $clock = $this->mock_clock_with_frozen(10000000); + $this->resetAfterTest(true); $user = $this->getDataGenerator()->create_user(); $this->setUser($user); // Setup test staples. - $totp = \OTPHP\TOTP::create('fakekey'); + $totp = \OTPHP\TOTP::create('fakekey', clock: $clock); $window = 29; set_config('enabled', 1, 'factor_totp'); @@ -61,44 +64,44 @@ class factor_test extends \advanced_testcase { $factorinstance = $totpfactor->setup_user_factor((object) $totpdata); // First check that a valid code is actually valid. - $code = $totp->at(time()); + $code = $totp->at($clock->time()); // Manually set timeverified of factor. - $DB->set_field('tool_mfa', 'lastverified', time() - WEEKSECS, ['id' => $factorinstance->id]); + $DB->set_field('tool_mfa', 'lastverified', $clock->time() - WEEKSECS, ['id' => $factorinstance->id]); $result = $totpfactor->validate_code($code, $window, $totp, $factorinstance); $this->assertEquals($totpfactor::TOTP_VALID, $result); - // Now update timeverified to 45 seconds ago, and check codes within window is blocked. - $code = $totp->at(time() - (20)); - $DB->set_field('tool_mfa', 'lastverified', time() - (20), ['id' => $factorinstance->id]); + // Now update timeverified to 20 seconds ago, and check codes within window is blocked. + $code = $totp->at($clock->time() - (20)); + $DB->set_field('tool_mfa', 'lastverified', $clock->time() - (20), ['id' => $factorinstance->id]); $result = $totpfactor->validate_code($code, $window, $totp, $factorinstance); $this->assertEquals($totpfactor::TOTP_USED, $result); - // Now update timeverified to 45 seconds ago, and check code from current increment within window is blocked. - $code = $totp->at(time()); - $DB->set_field('tool_mfa', 'lastverified', time() - (20), ['id' => $factorinstance->id]); + // Now update timeverified to 20 seconds ago, and check code from current increment within window is blocked. + $code = $totp->at($clock->time()); + $DB->set_field('tool_mfa', 'lastverified', $clock->time() - (20), ['id' => $factorinstance->id]); $result = $totpfactor->validate_code($code, $window, $totp, $factorinstance); $this->assertEquals($totpfactor::TOTP_USED, $result); // Now check future codes. $window = 1; - $code = $totp->at(time() + (2 * MINSECS)); - $DB->set_field('tool_mfa', 'lastverified', time() - WEEKSECS, ['id' => $factorinstance->id]); + $code = $totp->at($clock->time() + (2 * MINSECS)); + $DB->set_field('tool_mfa', 'lastverified', $clock->time() - WEEKSECS, ['id' => $factorinstance->id]); $result = $totpfactor->validate_code($code, $window, $totp, $factorinstance); $this->assertEquals($totpfactor::TOTP_FUTURE, $result); // Codes in far future are invalid. - $code = $totp->at(time() + (20 * MINSECS)); + $code = $totp->at($clock->time() + (20 * MINSECS)); $result = $totpfactor->validate_code($code, $window, $totp, $factorinstance); $this->assertEquals($totpfactor::TOTP_INVALID, $result); // Do the same for past codes. $window = 1; - $code = $totp->at(time() - (2 * MINSECS)); + $code = $totp->at($clock->time() - (2 * MINSECS)); $result = $totpfactor->validate_code($code, $window, $totp, $factorinstance); $this->assertEquals($totpfactor::TOTP_OLD, $result); // Codes in far future are invalid. - $code = $totp->at(time() - (20 * MINSECS)); + $code = $totp->at($clock->time() - (20 * MINSECS)); $result = $totpfactor->validate_code($code, $window, $totp, $factorinstance); $this->assertEquals($totpfactor::TOTP_INVALID, $result);