-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqliteQueryGuard.php
More file actions
97 lines (82 loc) · 2.87 KB
/
Copy pathSqliteQueryGuard.php
File metadata and controls
97 lines (82 loc) · 2.87 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
<?php
declare(strict_types=1);
namespace Plugin\SqliteAdmin\Security;
use InvalidArgumentException;
use Plugin\SqliteAdmin\Database\SqliteStatementSplitter;
use Plugin\SqliteAdmin\DomainLocaleAware;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Qubus\Exception\Data\TypeException;
use Qubus\Exception\Exception;
use ReflectionException;
use function Qubus\Security\Helpers\t__;
final readonly class SqliteQueryGuard
{
use DomainLocaleAware;
public function __construct(
private DatabaseAccessPolicy $policy,
private SqliteTableScope $scope,
private SqliteStatementSplitter $splitter,
) {
}
/**
* @throws NotFoundExceptionInterface
* @throws ReflectionException
* @throws ContainerExceptionInterface
* @throws TypeException
* @throws \Psr\SimpleCache\InvalidArgumentException
* @throws Exception
*/
public function assertAllowed(string $sql): void
{
$statements = $this->splitter->split($sql);
if ($statements === []) {
throw new InvalidArgumentException(t__('SQL query is empty.', $this->domain()));
}
if (! $this->policy->canRunWriteSql() && count($statements) > 1) {
throw new InvalidArgumentException(
t__('Subsite users may only run one read-only query at a time.', $this->domain())
);
}
foreach ($statements as $statement) {
$this->assertStatementAllowed($statement);
}
}
/**
* @throws NotFoundExceptionInterface
* @throws ContainerExceptionInterface
* @throws ReflectionException
* @throws TypeException
* @throws \Psr\SimpleCache\InvalidArgumentException
* @throws Exception
*/
private function assertStatementAllowed(string $sql): void
{
if ($this->policy->canRunWriteSql()) {
return;
}
$normalized = strtolower(ltrim($sql));
if (
! str_starts_with($normalized, 'select')
&& ! str_starts_with($normalized, 'pragma table_info')
&& ! str_starts_with($normalized, 'pragma index_list')
&& ! str_starts_with($normalized, 'pragma table_xinfo')
) {
throw new InvalidArgumentException(
t__('Only read-only SELECT and safe PRAGMA queries are allowed.', $this->domain())
);
}
preg_match_all(
'/\\b(?:from|join)\\s+[\"`]?([A-Za-z_][A-Za-z0-9_]*)[\"`]?/i',
$sql,
$matches
);
foreach ($matches[1] ?? [] as $table) {
if (! str_starts_with($table, $this->scope->sitePrefix())) {
throw new InvalidArgumentException(
t__('This query references a table outside the current site.', $this->domain())
);
}
}
}
}