Skip to content

Commit

Permalink
Add assertion to validate a distinguished name
Browse files Browse the repository at this point in the history
  • Loading branch information
tvdijen committed Jul 26, 2024
1 parent 57428a3 commit 7b7ef2a
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/CustomAssertionTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@
*/
trait CustomAssertionTrait
{
/** @var string */
private static string $distinguished_name_regex = '/(?i)(?:^|,\s*)([a-z]+\s*=\s*(?:[^,+="<>;\\\\]|\\\\.)+(?:(?:\s*\+\s*[a-z]+\s*=\s*(?:[^,+="<>;\\\\]|\\\\.)+)*))/';

/** @var string */
private static string $datetime_regex = '/-?[0-9]{4}-(((0(1|3|5|7|8)|1(0|2))-(0[1-9]|(1|2)[0-9]|3[0-1]))|((0(4|6|9)|11)-(0[1-9]|(1|2)[0-9]|30))|(02-(0[1-9]|(1|2)[0-9])))T([0-1][0-9]|2[0-4]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9])(\.[0-999])?((\+|-)([0-1][0-9]|2[0-4]):(0[0-9]|[1-5][0-9])|Z)?/i';

Expand Down Expand Up @@ -49,6 +52,25 @@ trait CustomAssertionTrait
***********************************************************************************/


/**
* @param string $value
* @param string $message
*/
private static function validDistinguishedName(string $value, string $message = ''): void
{
if (filter_var(
$value,
FILTER_VALIDATE_REGEXP,
['options' => ['regexp' => self::$distinguished_name_regex]],
) === false) {
throw new InvalidArgumentException(sprintf(
$message ?: '\'%s\' is not a valid RFC4514 compliant distinguished name.',
$value,
));
}
}


/**
* @param string $value
* @param string $message
Expand Down
52 changes: 52 additions & 0 deletions tests/Assert/DistinguishedNameTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

declare(strict_types=1);

namespace SimpleSAML\Test\Assert;

use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use SimpleSAML\Assert\Assert;
use SimpleSAML\Assert\AssertionFailedException;

/**
* Class \SimpleSAML\Assert\DistinguishedNameTest
*
* @package simplesamlphp/assert
*/
#[CoversClass(Assert::class)]
final class DistinguishedNameTest extends TestCase
{
/**
* @param boolean $shouldPass
* @param string $name
*/
#[DataProvider('provideDistinguishedName')]
public function testValidDistinguishedName(bool $shouldPass, string $name): void
{
try {
Assert::validDistinguishedName($name);
$this->assertTrue($shouldPass);
} catch (AssertionFailedException $e) {
$this->assertFalse($shouldPass);
}
}


/**
* @return array<int, array{0: bool, 1: string}>
*/
public static function provideDistinguishedName(): array
{
return [
[true, 'CN=Dijen\, Tim van,OU=Accounts,DC=simplesamlphp,DC=org'],
[false, 'Test'],
[false, '_Test'],
[false, '_5425e58e-e799-4884-92cc-ca64ecede32f'], // prefixed v4 UUID
[false, 'Te*st'],
[false, '1Test'],
[false, 'Te:st'],
];
}
}

0 comments on commit 7b7ef2a

Please sign in to comment.