• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

LibreSign / libresign / 19281822204

11 Nov 2025 11:57PM UTC coverage: 39.188%. First build
19281822204

Pull #5770

github

web-flow
Merge aea055021 into b192dbfa1
Pull Request #5770: feat: validate crl

5 of 33 new or added lines in 5 files covered. (15.15%)

4592 of 11718 relevant lines covered (39.19%)

3.08 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

3.13
/lib/Handler/CertificateEngine/CfsslHandler.php
1
<?php
2

3
declare(strict_types=1);
4
/**
5
 * SPDX-FileCopyrightText: 2020-2024 LibreCode coop and contributors
6
 * SPDX-License-Identifier: AGPL-3.0-or-later
7
 */
8

9
namespace OCA\Libresign\Handler\CertificateEngine;
10

11
use GuzzleHttp\Client;
12
use GuzzleHttp\Exception\ConnectException;
13
use GuzzleHttp\Exception\RequestException;
14
use OC\SystemConfig;
15
use OCA\Libresign\AppInfo\Application;
16
use OCA\Libresign\Db\CrlMapper;
17
use OCA\Libresign\Exception\LibresignException;
18
use OCA\Libresign\Handler\CfsslServerHandler;
19
use OCA\Libresign\Helper\ConfigureCheckHelper;
20
use OCA\Libresign\Service\CaIdentifierService;
21
use OCA\Libresign\Service\CertificatePolicyService;
22
use OCA\Libresign\Service\Install\InstallService;
23
use OCP\Files\AppData\IAppDataFactory;
24
use OCP\IAppConfig;
25
use OCP\IConfig;
26
use OCP\IDateTimeFormatter;
27
use OCP\ITempManager;
28
use OCP\IURLGenerator;
29
use Psr\Log\LoggerInterface;
30

31
/**
32
 * Class CfsslHandler
33
 *
34
 * @package OCA\Libresign\Handler
35
 *
36
 * @method CfsslHandler setClient(Client $client)
37
 */
38
class CfsslHandler extends AEngineHandler implements IEngineHandler {
39
        public const CFSSL_URI = 'http://127.0.0.1:8888/api/v1/cfssl/';
40

41
        /** @var Client */
42
        protected $client;
43
        protected $cfsslUri;
44
        private string $binary = '';
45

46
        public function __construct(
47
                protected IConfig $config,
48
                protected IAppConfig $appConfig,
49
                private SystemConfig $systemConfig,
50
                protected IAppDataFactory $appDataFactory,
51
                protected IDateTimeFormatter $dateTimeFormatter,
52
                protected ITempManager $tempManager,
53
                protected CfsslServerHandler $cfsslServerHandler,
54
                protected CertificatePolicyService $certificatePolicyService,
55
                protected IURLGenerator $urlGenerator,
56
                protected CaIdentifierService $caIdentifierService,
57
                protected CrlMapper $crlMapper,
58
                protected LoggerInterface $logger,
59
        ) {
60
                parent::__construct(
55✔
61
                        $config,
55✔
62
                        $appConfig,
55✔
63
                        $appDataFactory,
55✔
64
                        $dateTimeFormatter,
55✔
65
                        $tempManager,
55✔
66
                        $certificatePolicyService,
55✔
67
                        $urlGenerator,
55✔
68
                        $caIdentifierService,
55✔
69
                );
55✔
70

71
                $this->cfsslServerHandler->configCallback(fn () => $this->getCurrentConfigPath());
55✔
72
        }
73

74
        #[\Override]
75
        public function generateRootCert(
76
                string $commonName,
77
                array $names = [],
78
        ): void {
79
                $this->cfsslServerHandler->createConfigServer(
×
80
                        $commonName,
×
81
                        $names,
×
82
                        $this->getCaExpiryInDays(),
×
83
                        $this->getCrlDistributionUrl(),
×
84
                );
×
85

86
                $this->gencert();
×
87

88
                $this->stopIfRunning();
×
89

90
                for ($i = 1; $i <= 4; $i++) {
×
91
                        if ($this->isUp()) {
×
92
                                break;
×
93
                        }
94
                        sleep(2);
×
95
                }
96
        }
97

98
        #[\Override]
99
        public function generateCertificate(): string {
100
                $certKeys = $this->newCert();
×
101
                $pkcs12 = parent::exportToPkcs12(
×
102
                        $certKeys['certificate'],
×
103
                        $certKeys['private_key'],
×
104
                        [
×
105
                                'friendly_name' => $this->getFriendlyName(),
×
106
                                'extracerts' => [
×
107
                                        $certKeys['certificate'],
×
108
                                        $certKeys['certificate_request'],
×
109
                                ],
×
110
                        ],
×
111
                );
×
112

113
                $parsed = $this->readCertificate($pkcs12, $this->getPassword());
×
114
                $this->persistSerialNumberToCrl($parsed);
×
115

116
                return $pkcs12;
×
117
        }
118

119
        #[\Override]
120
        public function isSetupOk(): bool {
121
                $configPath = $this->getCurrentConfigPath();
×
122
                $certificate = file_exists($configPath . DIRECTORY_SEPARATOR . 'ca.pem');
×
123
                $privateKey = file_exists($configPath . DIRECTORY_SEPARATOR . 'ca-key.pem');
×
124
                if (!$certificate || !$privateKey) {
×
125
                        return false;
×
126
                }
127
                try {
128
                        $this->getClient();
×
129
                        return true;
×
130
                } catch (\Throwable) {
×
131
                }
132
                return false;
×
133
        }
134

135
        #[\Override]
136
        protected function getConfigureCheckResourceName(): string {
137
                return 'cfssl-configure';
×
138
        }
139

140
        #[\Override]
141
        protected function getCertificateRegenerationTip(): string {
142
                return 'Consider regenerating the root certificate with: occ libresign:configure:cfssl --cn="Your CA Name"';
×
143
        }
144

145
        #[\Override]
146
        protected function getEngineSpecificChecks(): array {
147
                return $this->checkBinaries();
×
148
        }
149

150
        #[\Override]
151
        protected function getSetupSuccessMessage(): string {
152
                return 'Root certificate config files found.';
×
153
        }
154

155
        #[\Override]
156
        protected function getSetupErrorMessage(): string {
157
                return 'CFSSL (root certificate) not configured.';
×
158
        }
159

160
        #[\Override]
161
        protected function getSetupErrorTip(): string {
162
                return 'Run occ libresign:configure:cfssl --help';
×
163
        }
164

165
        #[\Override]
166
        public function toArray(): array {
167
                $return = parent::toArray();
×
168
                if (!empty($return['configPath'])) {
×
169
                        $return['cfsslUri'] = $this->appConfig->getValueString(Application::APP_ID, 'cfssl_uri');
×
170
                }
171
                return $return;
×
172
        }
173

174
        public function getCommonName(): string {
175
                $uid = $this->getUID();
×
176
                if (!$uid) {
×
177
                        return $this->commonName;
×
178
                }
179
                return $uid . ', ' . $this->commonName;
×
180
        }
181

182
        private function newCert(): array {
183
                $json = [
×
184
                        'json' => [
×
185
                                'profile' => 'client',
×
186
                                'request' => [
×
187
                                        'hosts' => $this->getHosts(),
×
188
                                        'CN' => $this->getCommonName(),
×
189
                                        'key' => [
×
190
                                                'algo' => 'rsa',
×
191
                                                'size' => 2048,
×
192
                                        ],
×
193
                                        'names' => [],
×
194
                                        'crl_url' => $this->getCrlDistributionUrl(),
×
195
                                ],
×
196
                        ],
×
197
                ];
×
198

199
                $names = $this->getNames();
×
200
                foreach ($names as $key => $value) {
×
201
                        if (!empty($value) && is_array($value)) {
×
202
                                $names[$key] = implode(', ', $value);
×
203
                        }
204
                }
205
                if (!empty($names)) {
×
206
                        $json['json']['request']['names'][] = $names;
×
207
                }
208

209
                try {
210
                        $response = $this->getClient()
×
211
                                ->request('post',
×
212
                                        'newcert',
×
213
                                        $json
×
214
                                )
×
215
                        ;
×
216
                } catch (RequestException|ConnectException $th) {
×
217
                        if ($th->getHandlerContext() && $th->getHandlerContext()['error']) {
×
218
                                throw new \Exception($th->getHandlerContext()['error'], 1);
×
219
                        }
220
                        throw new LibresignException($th->getMessage(), 500);
×
221
                }
222

223
                $responseDecoded = json_decode((string)$response->getBody(), true);
×
224
                if (!isset($responseDecoded['success']) || !$responseDecoded['success']) {
×
225
                        throw new LibresignException('Error while generating certificate keys!', 500);
×
226
                }
227

228
                return $responseDecoded['result'];
×
229
        }
230

231
        private function gencert(): void {
232
                $binary = $this->getBinary();
×
233
                $configPath = $this->getCurrentConfigPath();
×
234
                $csrFile = $configPath . '/csr_server.json';
×
235

236
                $cmd = escapeshellcmd($binary) . ' gencert -initca ' . escapeshellarg($csrFile);
×
237
                $output = shell_exec($cmd);
×
238

239
                if (!$output) {
×
240
                        throw new \RuntimeException('cfssl without output.');
×
241
                }
242

243
                $json = json_decode($output, true);
×
244
                if (!$json || !isset($json['cert'], $json['key'], $json['csr'])) {
×
245
                        throw new \RuntimeException('Error generating CA: invalid cfssl output.');
×
246
                }
247

248
                file_put_contents($configPath . '/ca.pem', $json['cert']);
×
249
                file_put_contents($configPath . '/ca-key.pem', $json['key']);
×
250
                file_put_contents($configPath . '/ca.csr', $json['csr']);
×
251

NEW
252
                $this->persistRootCertificateFromData($json['cert']);
×
253
        }
254

255
        private function getClient(): Client {
256
                if (!$this->client) {
×
257
                        $this->setClient(new Client(['base_uri' => $this->getCfsslUri()]));
×
258
                }
259
                $this->wakeUp();
×
260
                return $this->client;
×
261
        }
262

263
        private function isUp(): bool {
264
                try {
265
                        $client = $this->getClient();
×
266
                        if (!$this->portOpen()) {
×
267
                                throw new LibresignException('CFSSL server is down', 500);
×
268
                        }
269
                        $response = $client
×
270
                                ->request('get',
×
271
                                        'health',
×
272
                                        [
×
273
                                                'base_uri' => $this->getCfsslUri()
×
274
                                        ]
×
275
                                )
×
276
                        ;
×
277
                } catch (RequestException|ConnectException $th) {
×
278
                        switch ($th->getCode()) {
×
279
                                case 404:
×
280
                                        throw new \Exception('Endpoint /health of CFSSL server not found. Maybe you are using incompatible version of CFSSL server. Use latests version.', 1);
×
281
                                default:
282
                                        if ($th->getHandlerContext() && $th->getHandlerContext()['error']) {
×
283
                                                throw new \Exception($th->getHandlerContext()['error'], 1);
×
284
                                        }
285
                                        throw new LibresignException($th->getMessage(), 500);
×
286
                        }
287
                }
288

289
                $responseDecoded = json_decode((string)$response->getBody(), true);
×
290
                if (!isset($responseDecoded['success']) || !$responseDecoded['success']) {
×
291
                        throw new LibresignException('Error while check cfssl API health!', 500);
×
292
                }
293

294
                if (empty($responseDecoded['result']) || empty($responseDecoded['result']['healthy'])) {
×
295
                        return false;
×
296
                }
297

298
                return (bool)$responseDecoded['result']['healthy'];
×
299
        }
300

301
        private function wakeUp(): void {
302
                if ($this->portOpen()) {
×
303
                        return;
×
304
                }
305
                $binary = $this->getBinary();
×
306
                $configPath = $this->getCurrentConfigPath();
×
307
                if (!$configPath) {
×
308
                        throw new LibresignException('CFSSL not configured.');
×
309
                }
310
                $this->cfsslServerHandler->updateExpirity($this->getCaExpiryInDays());
×
311
                $cmd = 'nohup ' . $binary . ' serve -address=127.0.0.1 '
×
312
                        . '-ca-key ' . $configPath . DIRECTORY_SEPARATOR . 'ca-key.pem '
×
313
                        . '-ca ' . $configPath . DIRECTORY_SEPARATOR . 'ca.pem '
×
314
                        . '-config ' . $configPath . DIRECTORY_SEPARATOR . 'config_server.json > /dev/null 2>&1 & echo $!';
×
315
                shell_exec($cmd);
×
316
                $loops = 0;
×
317
                while (!$this->portOpen() && $loops <= 4) {
×
318
                        sleep(1);
×
319
                        $loops++;
×
320
                }
321
        }
322

323
        private function portOpen(): bool {
324
                $host = parse_url($this->getCfsslUri(), PHP_URL_HOST);
×
325
                $port = parse_url($this->getCfsslUri(), PHP_URL_PORT);
×
326

327
                set_error_handler(function (): void { });
×
328
                $socket = fsockopen($host, $port, $errno, $errstr, 0.1);
×
329
                restore_error_handler();
×
330
                if (!$socket || $errno || $errstr) {
×
331
                        return false;
×
332
                }
333
                fclose($socket);
×
334
                return true;
×
335
        }
336

337
        private function getServerPid(): int {
338
                $cmd = 'ps -eo pid,command|';
×
339
                $cmd .= 'grep "cfssl.*serve.*-address"|'
×
340
                        . 'grep -v grep|'
×
341
                        . 'grep -v defunct|'
×
342
                        . 'sed -e "s/^[[:space:]]*//"|cut -d" " -f1';
×
343
                $output = shell_exec($cmd);
×
344
                if (!is_string($output)) {
×
345
                        return 0;
×
346
                }
347
                $pid = trim($output);
×
348
                return (int)$pid;
×
349
        }
350

351
        /**
352
         * Parse command
353
         *
354
         * Have commands that need to be executed as sudo otherwise don't will work,
355
         * by example the command runuser or kill. To prevent error when run in a
356
         * GitHub Actions, these commands are executed prefixed by sudo when exists
357
         * an environment called GITHUB_ACTIONS.
358
         */
359
        private function parseCommand(string $command): string {
360
                if (getenv('GITHUB_ACTIONS') !== false) {
×
361
                        $command = 'sudo ' . $command;
×
362
                }
363
                return $command;
×
364
        }
365

366
        private function stopIfRunning(): void {
367
                $pid = $this->getServerPid();
×
368
                if ($pid > 0) {
×
369
                        exec($this->parseCommand('kill -9 ' . $pid));
×
370
                }
371
        }
372

373
        private function getBinary(): string {
374
                if ($this->binary) {
×
375
                        return $this->binary;
×
376
                }
377

378
                if (PHP_OS_FAMILY === 'Windows') {
×
379
                        throw new LibresignException('Incompatible with Windows');
×
380
                }
381

382
                if ($this->appConfig->hasKey(Application::APP_ID, 'cfssl_bin')) {
×
383
                        $binary = $this->appConfig->getValueString(Application::APP_ID, 'cfssl_bin');
×
384
                        if (!file_exists($binary)) {
×
385
                                $this->appConfig->deleteKey(Application::APP_ID, 'cfssl_bin');
×
386
                        }
387
                        return $binary;
×
388
                }
389
                throw new LibresignException('Binary of CFSSL not found. Install binaries.');
×
390
        }
391

392
        private function getCfsslUri(): string {
393
                if ($this->cfsslUri) {
×
394
                        return $this->cfsslUri;
×
395
                }
396

397
                if ($uri = $this->appConfig->getValueString(Application::APP_ID, 'cfssl_uri')) {
×
398
                        return $uri;
×
399
                }
400
                $this->appConfig->deleteKey(Application::APP_ID, 'cfssl_uri');
×
401

402
                $this->cfsslUri = self::CFSSL_URI;
×
403
                return $this->cfsslUri;
×
404
        }
405

406
        public function setCfsslUri($uri): void {
407
                if ($uri) {
×
408
                        $this->appConfig->setValueString(Application::APP_ID, 'cfssl_uri', $uri);
×
409
                } else {
410
                        $this->appConfig->deleteKey(Application::APP_ID, 'cfssl_uri');
×
411
                }
412
                $this->cfsslUri = $uri;
×
413
        }
414

415
        private function checkBinaries(): array {
416
                if (PHP_OS_FAMILY === 'Windows') {
×
417
                        return [
×
418
                                (new ConfigureCheckHelper())
×
419
                                        ->setErrorMessage('CFSSL is incompatible with Windows')
×
420
                                        ->setResource('cfssl'),
×
421
                        ];
×
422
                }
423
                $binary = $this->appConfig->getValueString(Application::APP_ID, 'cfssl_bin');
×
424
                if (!$binary) {
×
425
                        return [
×
426
                                (new ConfigureCheckHelper())
×
427
                                        ->setErrorMessage('CFSSL not installed.')
×
428
                                        ->setResource('cfssl')
×
429
                                        ->setTip('Run occ libresign:install --cfssl'),
×
430
                        ];
×
431
                }
432

433
                if (!file_exists($binary)) {
×
434
                        return [
×
435
                                (new ConfigureCheckHelper())
×
436
                                        ->setErrorMessage('CFSSL not found.')
×
437
                                        ->setResource('cfssl')
×
438
                                        ->setTip('Run occ libresign:install --cfssl'),
×
439
                        ];
×
440
                }
441
                $version = shell_exec("$binary version");
×
442
                if (!is_string($version) || empty($version)) {
×
443
                        return [
×
444
                                (new ConfigureCheckHelper())
×
445
                                        ->setErrorMessage(sprintf(
×
446
                                                'Failed to run the command "%s" with user %s',
×
447
                                                "$binary version",
×
448
                                                get_current_user()
×
449
                                        ))
×
450
                                        ->setResource('cfssl')
×
451
                                        ->setTip('Run occ libresign:install --cfssl')
×
452
                        ];
×
453
                }
454
                preg_match_all('/: (?<version>.*)/', $version, $matches);
×
455
                if (!$matches || !isset($matches['version']) || count($matches['version']) !== 2) {
×
456
                        return [
×
457
                                (new ConfigureCheckHelper())
×
458
                                        ->setErrorMessage(sprintf(
×
459
                                                'Failed to identify cfssl version with command %s',
×
460
                                                "$binary version"
×
461
                                        ))
×
462
                                        ->setResource('cfssl')
×
463
                                        ->setTip('Run occ libresign:install --cfssl')
×
464
                        ];
×
465
                }
466
                if (!str_contains($matches['version'][0], InstallService::CFSSL_VERSION)) {
×
467
                        return [
×
468
                                (new ConfigureCheckHelper())
×
469
                                        ->setErrorMessage(sprintf(
×
470
                                                'Invalid version. Expected: %s, actual: %s',
×
471
                                                InstallService::CFSSL_VERSION,
×
472
                                                $matches['version'][0]
×
473
                                        ))
×
474
                                        ->setResource('cfssl')
×
475
                                        ->setTip('Run occ libresign:install --cfssl')
×
476
                        ];
×
477
                }
478
                $return = [];
×
479
                $return[] = (new ConfigureCheckHelper())
×
480
                        ->setSuccessMessage('CFSSL binary path: ' . $binary)
×
481
                        ->setResource('cfssl');
×
482
                $return[] = (new ConfigureCheckHelper())
×
483
                        ->setSuccessMessage('CFSSL version: ' . $matches['version'][0])
×
484
                        ->setResource('cfssl');
×
485
                $return[] = (new ConfigureCheckHelper())
×
486
                        ->setSuccessMessage('Runtime: ' . $matches['version'][1])
×
487
                        ->setResource('cfssl');
×
488
                return $return;
×
489
        }
490

491
        #[\Override]
492
        public function generateCrlDer(array $revokedCertificates, string $instanceId, int $generation): string {
493
                try {
494
                        $queryParams = [];
×
495
                        $queryParams['expiry'] = '168h'; // 7 days * 24 hours
×
496

497
                        $response = $this->getClient()->request('GET', 'crl', [
×
498
                                'query' => $queryParams
×
499
                        ]);
×
500

501
                        $responseData = json_decode((string)$response->getBody(), true);
×
502

503
                        if (!isset($responseData['success']) || !$responseData['success']) {
×
504
                                $errorMessage = isset($responseData['errors'])
×
505
                                        ? implode(', ', array_column($responseData['errors'], 'message'))
×
506
                                        : 'Unknown CFSSL error';
×
507
                                throw new \RuntimeException('CFSSL CRL generation failed: ' . $errorMessage);
×
508
                        }
509

510
                        if (isset($responseData['result']) && is_string($responseData['result'])) {
×
511
                                return $responseData['result'];
×
512
                        }
513

514
                        throw new \RuntimeException('No CRL data returned from CFSSL');
×
515

516
                } catch (RequestException|ConnectException $e) {
×
517
                        throw new \RuntimeException('Failed to communicate with CFSSL server: ' . $e->getMessage());
×
518
                } catch (\Throwable $e) {
×
519
                        throw new \RuntimeException('CFSSL CRL generation error: ' . $e->getMessage());
×
520
                }
521
        }
522

523
        /**
524
         * Get Authority Key Identifier from certificate (needed for CFSSL revocation)
525
         *
526
         * @param string $certificatePem PEM encoded certificate
527
         * @return string Authority Key Identifier in lowercase without colons
528
         */
529
        public function getAuthorityKeyId(string $certificatePem): string {
530
                $cert = openssl_x509_read($certificatePem);
×
531
                if (!$cert) {
×
532
                        throw new \RuntimeException('Invalid certificate format');
×
533
                }
534

535
                $parsed = openssl_x509_parse($cert);
×
536
                if (!$parsed || !isset($parsed['extensions']['authorityKeyIdentifier'])) {
×
537
                        throw new \RuntimeException('Certificate does not contain Authority Key Identifier');
×
538
                }
539

540
                $authKeyId = $parsed['extensions']['authorityKeyIdentifier'];
×
541

542
                if (preg_match('/keyid:([A-Fa-f0-9:]+)/', $authKeyId, $matches)) {
×
543
                        return strtolower(str_replace(':', '', $matches[1]));
×
544
                }
545

546
                throw new \RuntimeException('Could not parse Authority Key Identifier');
×
547
        }
548

549
        /**
550
         * Revoke a certificate using CFSSL API
551
         *
552
         * @param string $serialNumber Certificate serial number in decimal format
553
         * @param string $authorityKeyId Authority key identifier (lowercase, no colons)
554
         * @param string $reason CRLReason description string (e.g., 'superseded', 'keyCompromise')
555
         */
556
        public function revokeCertificate(string $serialNumber, string $authorityKeyId, string $reason): bool {
557
                try {
558
                        $json = [
×
559
                                'json' => [
×
560
                                        'serial' => $serialNumber,
×
561
                                        'authority_key_id' => $authorityKeyId,
×
562
                                        'reason' => $reason,
×
563
                                ],
×
564
                        ];
×
565

566
                        $response = $this->getClient()->request('POST', 'revoke', $json);
×
567

568
                        $responseData = json_decode((string)$response->getBody(), true);
×
569

570
                        if (!isset($responseData['success'])) {
×
571
                                $errorMessage = isset($responseData['errors'])
×
572
                                        ? implode(', ', array_column($responseData['errors'], 'message'))
×
573
                                        : 'Unknown CFSSL error';
×
574
                                throw new \RuntimeException('CFSSL revocation failed: ' . $errorMessage);
×
575
                        }
576

577
                        return $responseData['success'];
×
578

579
                } catch (RequestException|ConnectException $e) {
×
580
                        throw new \RuntimeException('Failed to communicate with CFSSL server: ' . $e->getMessage());
×
581
                } catch (\Throwable $e) {
×
582
                        throw new \RuntimeException('CFSSL certificate revocation error: ' . $e->getMessage());
×
583
                }
584
        }
585

586
        private function persistSerialNumberToCrl(array $parsed): void {
587
                if (!isset($parsed['serialNumberHex']) || !isset($parsed['valid_to'])) {
×
588
                        return;
×
589
                }
590

591
                $serialNumber = $parsed['serialNumberHex'];
×
592

593
                $owner = $this->getCommonName() ?? 'Unknown';
×
594

595
                $expiresAt = null;
×
596
                if (isset($parsed['validTo_time_t'])) {
×
597
                        $expiresAt = new \DateTime('@' . $parsed['validTo_time_t']);
×
598
                }
599

600
                $this->crlMapper->createCertificate(
×
601
                        $serialNumber,
×
602
                        $owner,
×
603
                        'cfssl',
×
604
                        $this->caIdentifierService->getInstanceId(),
×
NEW
605
                        $this->caIdentifierService->getCaIdParsed()['generation'],
×
NEW
606
                        new \DateTime(),
×
NEW
607
                        $expiresAt
×
NEW
608
                );
×
609
        }
610

611
        private function persistRootCertificateFromData(string $certPem): void {
NEW
612
                $x509Resource = openssl_x509_read($certPem);
×
NEW
613
                if (!$x509Resource) {
×
NEW
614
                        throw new \RuntimeException('Failed to parse root certificate');
×
615
                }
616

NEW
617
                $parsed = openssl_x509_parse($x509Resource);
×
NEW
618
                if (!$parsed) {
×
NEW
619
                        throw new \RuntimeException('Failed to extract root certificate information');
×
620
                }
621

NEW
622
                $serialNumber = $parsed['serialNumberHex'] ?? '';
×
NEW
623
                if (empty($serialNumber)) {
×
NEW
624
                        throw new \RuntimeException('Root certificate has no serial number');
×
625
                }
626

NEW
627
                $owner = $this->getCommonName() ?? 'Root CA';
×
628

NEW
629
                $expiresAt = null;
×
NEW
630
                if (isset($parsed['validTo_time_t'])) {
×
NEW
631
                        $expiresAt = new \DateTime('@' . $parsed['validTo_time_t']);
×
632
                }
633

NEW
634
                $this->crlMapper->createCertificate(
×
NEW
635
                        $serialNumber,
×
NEW
636
                        $owner,
×
NEW
637
                        'cfssl',
×
NEW
638
                        $this->caIdentifierService->getInstanceId(),
×
NEW
639
                        $this->caIdentifierService->getCaIdParsed()['generation'],
×
640
                        new \DateTime(),
×
641
                        $expiresAt
×
642
                );
×
643
        }
644
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc