-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathBuildDBLogHandler.php
More file actions
121 lines (103 loc) · 2.88 KB
/
Copy pathBuildDBLogHandler.php
File metadata and controls
121 lines (103 loc) · 2.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
<?php
declare(strict_types=1);
namespace PHPCensor\Logging;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Logger;
use PHPCensor\Model\Build;
use PHPCensor\Model\Secret;
use PHPCensor\Store\BuildStore;
use PHPCensor\Store\SecretStore;
/**
* Class BuildDBLogHandler writes the build log to the database.
*
* @package PHP Censor
* @subpackage Application
*
* @author Dmitry Khomutov <poisoncorpsee@gmail.com>
*/
class BuildDBLogHandler extends AbstractProcessingHandler
{
protected Build $build;
protected BuildStore $buildStore;
private SecretStore $secretStore;
protected string $logValue;
/**
* @var int last flush timestamp
*/
protected int $flushTimestamp = 0;
/**
* @var int flush delay, seconds
*/
protected int $flushDelay = 1;
public function __construct(
SecretStore $secretStore,
BuildStore $buildStore,
Build $build,
int $level = Logger::INFO,
bool $bubble = true
) {
parent::__construct($level, $bubble);
$this->secretStore = $secretStore;
$this->build = $build;
$this->buildStore = $buildStore;
// We want to add to any existing saved log information.
$this->logValue = (string)$build->getLog();
}
public function __destruct()
{
$this->flushData();
}
/**
* Flush buffered data
*/
protected function flushData(): void
{
$this->build->setLog($this->logValue);
$this->buildStore->save($this->build);
$this->flushTimestamp = \time();
}
private function sanitize(string $message): string
{
return \str_replace([
'\/',
'//',
$this->build->getBuildPath(),
ROOT_DIR,
], [
'/',
'//',
'<BUILD_PATH>/',
'<PHP_CENSOR_PATH>/',
], $message);
}
private function sanitizeSecrets(string $message): string
{
$replace = [];
$secrets = $this->secretStore->getAll();
if (\count($secrets['items']) > 0) {
/** @var Secret $secret */
foreach ($secrets['items'] as $secret) {
$value = $secret->getValue();
$name = '%' . \sprintf('SECRET:%s', $secret->getName()) . '%';
if (\trim($value)) {
$replace[$name] = $secret->getValue();
}
}
}
return \str_replace($replace, \array_keys($replace), $message);
}
/**
* Write a log entry to the build log.
*/
protected function write(array $record): void
{
$this->logValue .= $this->sanitize(
$this->sanitizeSecrets(
(string)$record['message']
)
) . PHP_EOL;
if ($this->flushTimestamp < (\time() - $this->flushDelay)) {
$this->flushData();
}
}
}