Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
70.83% |
17 / 24 |
|
50.00% |
1 / 2 |
CRAP | |
0.00% |
0 / 1 |
| SerialNumberService | |
70.83% |
17 / 24 |
|
50.00% |
1 / 2 |
5.62 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| generateUniqueSerial | |
69.57% |
16 / 23 |
|
0.00% |
0 / 1 |
4.45 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | /** |
| 6 | * SPDX-FileCopyrightText: 2025 LibreCode coop and contributors |
| 7 | * SPDX-License-Identifier: AGPL-3.0-or-later |
| 8 | */ |
| 9 | |
| 10 | namespace OCA\Libresign\Service; |
| 11 | |
| 12 | use DateTime; |
| 13 | use OCA\Libresign\Db\CrlMapper; |
| 14 | use OCP\DB\Exception as DBException; |
| 15 | |
| 16 | class SerialNumberService { |
| 17 | private const int MAX_RETRY_ATTEMPTS = 10; |
| 18 | private const int SERIAL_MAX_VALUE = 9223372036854775807; |
| 19 | |
| 20 | public function __construct( |
| 21 | private CrlMapper $crlMapper, |
| 22 | ) { |
| 23 | } |
| 24 | |
| 25 | public function generateUniqueSerial( |
| 26 | string $certificateOwner, |
| 27 | string $instanceId, |
| 28 | int $generation, |
| 29 | DateTime $expiresAt, |
| 30 | string $engineName, |
| 31 | ?array $issuer = null, |
| 32 | ?array $subject = null, |
| 33 | string $certificateType = 'leaf', |
| 34 | ): string { |
| 35 | for ($attempts = 0; $attempts < self::MAX_RETRY_ATTEMPTS; $attempts++) { |
| 36 | $serialInt = random_int(1, self::SERIAL_MAX_VALUE); |
| 37 | |
| 38 | $serialString = (string)$serialInt; |
| 39 | |
| 40 | try { |
| 41 | $this->crlMapper->createCertificate( |
| 42 | $serialString, |
| 43 | $certificateOwner, |
| 44 | $engineName, |
| 45 | $instanceId, |
| 46 | $generation, |
| 47 | new DateTime(), |
| 48 | $expiresAt, |
| 49 | $issuer, |
| 50 | $subject, |
| 51 | $certificateType, |
| 52 | ); |
| 53 | |
| 54 | return $serialString; |
| 55 | } catch (DBException $e) { |
| 56 | if ($e->getReason() === DBException::REASON_UNIQUE_CONSTRAINT_VIOLATION) { |
| 57 | continue; |
| 58 | } |
| 59 | throw $e; |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | throw new \RuntimeException( |
| 64 | 'Failed to generate unique serial number after ' . self::MAX_RETRY_ATTEMPTS . ' attempts' |
| 65 | ); |
| 66 | } |
| 67 | } |