Skip to content

refactor(security): improve SecureRandom implementation, tests, and docs - #56224

Open
joshtrichards wants to merge 8 commits into
masterfrom
jtr/refactor-SecureRandom
Open

joshtrichards wants to merge 8 commits into
masterfrom
jtr/refactor-SecureRandom

Conversation

@joshtrichards

Copy link
Copy Markdown
Member

Summary

This PR improves the SecureRandom implementation along with its related tests and documentation.

Key changes

  • Refactored implementation:

    • Added strict checks to prevent accidental use of non-ASCII, duplicate-containing, or overly short character sets.
      • This is a security-hardening change: it prevents developers from making subtle, security-impacting mistakes.
      • Previously, passing a character set shorter than 4 characters, containing multibyte characters, or with duplicates would (most likely) have resulted in unexpected, but not necessarily fatal, behavior. The function would still "work," but might return poor quality random strings, cause subtle bugs, or perhaps fail in different ways.
      • Technically a backward-incompatible (breaking) change, but unlikely to be disruptive in practice:
        • No known use cases intentionally violate these checks (any that do are likely unintentional, so this will surface them while preventing future occurrences).
    • Established a new constant containing the (existing) default $characters set passed to generate().
    • Improved docblocks and in-code documentation for ISecureRandom and SecureRandom to better describe behavior, parameters, and usage.
  • Expanded and updated tests:

    • Added new tests for:
      • Invalid character sets (duplicates, too short, non-ASCII)
      • Unusual/oddball lengths (e.g., 31) to check for off-by-one and fencepost errors
      • Minimum viable character set size and large custom sets
      • Output uniqueness (basic sanity check)
      • Default and user-supplied character sets
    • Improved existing test coverage and runtime performance:
      • Replaced impractically large test lengths (e.g., 64,000) with more practical ranges for CI, while still ensuring coverage of edge cases and real-world needs.

TODO

Checklist

@joshtrichards joshtrichards added enhancement tests Related to tests ♻️ refactor Refactor code (not a bug fix, not a feature just refactoring) labels Nov 5, 2025
@joshtrichards
joshtrichards marked this pull request as ready for review November 6, 2025 19:57
@joshtrichards
joshtrichards requested a review from a team as a code owner November 6, 2025 19:57
@joshtrichards
joshtrichards requested review from ArtificialOwl, CarlSchwan, icewind1991 and leftybournes and removed request for a team November 6, 2025 19:57
@joshtrichards joshtrichards added the 3. to review Waiting for reviews label Nov 6, 2025
Comment thread tests/lib/Security/SecureRandomTest.php Resolved
Comment thread tests/lib/Security/SecureRandomTest.php Resolved
Comment thread tests/lib/Security/SecureRandomTest.php Outdated
Comment on lines +116 to +117
$this->assertMatchesRegularExpression('/^[abcd]+$/', $randomString);
$this->assertEquals(500, strlen($randomString));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
$this->assertMatchesRegularExpression('/^[abcd]+$/', $randomString);
$this->assertEquals(500, strlen($randomString));
$this->assertMatchesRegularExpression('/^[abcd]{500}$/', $randomString);

Or keep the length check separate but then you can also do that upstairs.

Comment thread tests/lib/Security/SecureRandomTest.php Resolved
Comment thread lib/public/Security/ISecureRandom.php Resolved
@joshtrichards
joshtrichards force-pushed the jtr/refactor-SecureRandom branch from f2cdc9b to 971a1fe Compare June 1, 2026 16:48
@susnux susnux added the community pull requests from community label Jun 9, 2026
joshtrichards and others added 8 commits December 5, 2026 23:25
- Add constant for default $characters set
- Update docs for accuracy and clarity

Signed-off-by: Josh <josh.t.richards@gmail.com>
Assisted-by: ClaudeCode:claude-opus-5-5
- Use a constant for the default $characters set (still same chars)
- Add more robust  reasonableness checks for $characters set
- Switch docblocks to point at interface docs to avoid duplication

Signed-off-by: Josh <josh.t.richards@gmail.com>
Assisted-by: ClaudeCode:claude-opus-5-5
New test coverage for:

- charset validation failures (duplicates, too short, non-ASCII).
- default charset (CHAR_BASE64_RFC4648).
- randomness/unique output.
- minimum-sized valid charsets and large printable ASCII charset.
- a caller-provided, valid (non-predefined) custom charset.

And adjusts the length ranges tests:

- Added some smaller / more frequently used ranges.
- Added an "oddball" range to possibly catch weird stuff.
- Dropped excessive 64K test which does not need to run within our CI during standard PR runs (if deemed desirable maybe add it to an occasional stress tester, but I don't think it's necessary for now)

Signed-off-by: Josh <josh.t.richards@gmail.com>
Signed-off-by: Josh <josh.t.richards@gmail.com>
Signed-off-by: Josh <josh.t.richards@gmail.com>
Signed-off-by: Josh <josh.t.richards@gmail.com>
Signed-off-by: Josh <josh.t.richards@gmail.com>
…hanges

The changes land in 36, and the generator now uses Random\Randomizer instead of random_int().

Signed-off-by: Ferdinand Thiessen <opensource@fthiessen.de>
Assisted-by: ClaudeCode:claude-opus-5-5
@susnux
susnux force-pushed the jtr/refactor-SecureRandom branch from 97d7fb0 to c75e7e3 Compare December 5, 2026 22:25
// Check for ASCII-only (no multibyte characters)
!mb_check_encoding($characters, 'ASCII')
// Check for uniqueness: number of unique bytes must equal original length
|| strlen(count_chars($characters, 3)) !== strlen($characters)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This check rejects one of our own constants: ISecureRandom::CHAR_SYMBOLS is 34 bytes but has only 32 unique characters, because the single-quoted literal contains the backslash three times (\", \\ and [\] each leave one). So every generate($n, ISecureRandom::CHAR_SYMBOLS) throws now.

In server this breaks UsersController::addUser() in provisioning_api: when a user is created with an email but no password and no password_policy listener provides one, the fallback generate(1, ISecureRandom::CHAR_SYMBOLS) throws and the user is not created.

Could you fix the constant? Then it is exactly the 32 ASCII punctuation characters:

public const CHAR_SYMBOLS = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~';

AbstractDatabase::generateDbPassword() then needs '"' instead of '\"' in its str_replace(), otherwise " ends up in generated database passwords.

);
}

if (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This turns input that has worked since 8.0 into an exception in a public API, e.g. overlapping concatenations like ISecureRandom::CHAR_ALPHANUMERIC . ISecureRandom::CHAR_DIGITS or small sets like '01'.

I agree duplicates are a bug (they skew the distribution), but for apps this is a hard break without notice. What do you think about deduplicating (count_chars($characters, 3)) or logging a deprecation for now, and throwing only in a later release? Either way it should go into the developer upgrade notes for 36.

*
* @param int $length Number of characters (must be > 0).
* @param string $characters Optional list of unique, single-byte (ASCII) characters
* to use. Defaults to the CHAR_BASE64_RFC4648 alphabet. A custom set should contain at least 4

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The implementation enforces the minimum, so this is a "must":

Suggested change
* to use. Defaults to the CHAR_BASE64_RFC4648 alphabet. A custom set should contain at least 4
* to use. Defaults to the CHAR_BASE64_RFC4648 alphabet. A custom set must contain at least 4

Also "which all meet the requirements" only holds once CHAR_SYMBOLS is fixed, and not for concatenations of overlapping constants. Maybe worth mentioning that.

[64, 64],
[128, 128],
[256, 256],
[1024, 1024],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we keep one large length? Otherwise nothing covers long outputs anymore.

Suggested change
[1024, 1024],
[1024, 1024],
[64000, 64000],

public function testInvalidCharacterSets(string $invalidCharset): void {
$this->expectException(\InvalidArgumentException::class);
$this->rng->generate(10, $invalidCharset);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a test that runs generate() with every predefined constant. It would have caught the CHAR_SYMBOLS issue (the mocked ISecureRandom in the provisioning_api tests cannot):

Suggested change
}
}
public static function predefinedCharsets(): array {
return [
['CHAR_UPPER'],
['CHAR_LOWER'],
['CHAR_DIGITS'],
['CHAR_SYMBOLS'],
['CHAR_ALPHANUMERIC'],
['CHAR_HUMAN_READABLE'],
['CHAR_BASE64_RFC4648'],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider('predefinedCharsets')]
public function testPredefinedCharsets(string $constant): void {
$charset = constant('OCP\Security\ISecureRandom::' . $constant);
$randomString = $this->rng->generate(100, $charset);
$this->assertSame(100, strlen($randomString));
$this->assertSame('', str_replace(str_split($charset), '', $randomString));
}

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

3. to review Waiting for reviews AI assisted community pull requests from community enhancement ♻️ refactor Refactor code (not a bug fix, not a feature just refactoring) tests Related to tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants