Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
70.83% covered (warning)
70.83%
17 / 24
50.00% covered (danger)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
SerialNumberService
70.83% covered (warning)
70.83%
17 / 24
50.00% covered (danger)
50.00%
1 / 2
5.62
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 generateUniqueSerial
69.57% covered (warning)
69.57%
16 / 23
0.00% covered (danger)
0.00%
0 / 1
4.45
1<?php
2
3declare(strict_types=1);
4
5/**
6 * SPDX-FileCopyrightText: 2025 LibreCode coop and contributors
7 * SPDX-License-Identifier: AGPL-3.0-or-later
8 */
9
10namespace OCA\Libresign\Service;
11
12use DateTime;
13use OCA\Libresign\Db\CrlMapper;
14use OCP\DB\Exception as DBException;
15
16class 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}