codeveto 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codeveto/__init__.py +3 -0
- codeveto/__main__.py +8 -0
- codeveto/ai/__init__.py +19 -0
- codeveto/ai/harness.py +303 -0
- codeveto/ai/packets.py +855 -0
- codeveto/ai/policy.py +222 -0
- codeveto/ai/prompt.py +101 -0
- codeveto/ai/providers/__init__.py +178 -0
- codeveto/ai/providers/claude.py +247 -0
- codeveto/ai/providers/openai_compat.py +246 -0
- codeveto/ai/runner.py +293 -0
- codeveto/ai/verify.py +324 -0
- codeveto/anchor.py +211 -0
- codeveto/cli.py +247 -0
- codeveto/cli_explain.py +49 -0
- codeveto/cli_hook.py +31 -0
- codeveto/cli_init.py +254 -0
- codeveto/cli_mcp.py +29 -0
- codeveto/cli_packets.py +35 -0
- codeveto/cli_publish.py +29 -0
- codeveto/cli_review.py +362 -0
- codeveto/cli_rules.py +78 -0
- codeveto/cli_verify.py +47 -0
- codeveto/config.py +1229 -0
- codeveto/data/README.md +16 -0
- codeveto/data/ai-wire.schema.json +53 -0
- codeveto/data/prompts/system.md +57 -0
- codeveto/data/report-v1.schema.json +268 -0
- codeveto/data/templates/forgejo-codeveto.yml +104 -0
- codeveto/data/templates/github-codeveto.yml +18 -0
- codeveto/embedded.py +311 -0
- codeveto/engine.py +1570 -0
- codeveto/git.py +1549 -0
- codeveto/globs.py +348 -0
- codeveto/integrations/__init__.py +1 -0
- codeveto/integrations/hooks.py +327 -0
- codeveto/integrations/mcp.py +770 -0
- codeveto/integrations/mcp_ai.py +77 -0
- codeveto/integrations/prepush.py +222 -0
- codeveto/jsonsafe.py +60 -0
- codeveto/languages.py +539 -0
- codeveto/lexers.py +2560 -0
- codeveto/model.py +372 -0
- codeveto/publish/__init__.py +28 -0
- codeveto/publish/action.py +330 -0
- codeveto/publish/common.py +84 -0
- codeveto/publish/diff.py +208 -0
- codeveto/publish/event.py +241 -0
- codeveto/publish/forgejo.py +184 -0
- codeveto/publish/github.py +380 -0
- codeveto/publish/http.py +263 -0
- codeveto/publish/pull.py +218 -0
- codeveto/publish/untrusted.py +110 -0
- codeveto/py.typed +0 -0
- codeveto/redact.py +113 -0
- codeveto/render/__init__.py +64 -0
- codeveto/render/agent.py +43 -0
- codeveto/render/github.py +101 -0
- codeveto/render/json.py +23 -0
- codeveto/render/markdown.py +208 -0
- codeveto/render/safe.py +249 -0
- codeveto/render/sarif.py +217 -0
- codeveto/render/text.py +210 -0
- codeveto/report.py +252 -0
- codeveto/rules/__init__.py +84 -0
- codeveto/rules/agent.py +2972 -0
- codeveto/rules/base.py +1026 -0
- codeveto/rules/ci.py +1708 -0
- codeveto/rules/config.py +493 -0
- codeveto/rules/deps.py +1693 -0
- codeveto/rules/docker.py +479 -0
- codeveto/rules/examples/__init__.py +148 -0
- codeveto/rules/examples/agent.py +839 -0
- codeveto/rules/examples/ci.py +1046 -0
- codeveto/rules/examples/config.py +191 -0
- codeveto/rules/examples/deps.py +369 -0
- codeveto/rules/examples/docker.py +157 -0
- codeveto/rules/examples/go.py +241 -0
- codeveto/rules/examples/hygiene.py +466 -0
- codeveto/rules/examples/js.py +462 -0
- codeveto/rules/examples/python.py +595 -0
- codeveto/rules/examples/rust.py +268 -0
- codeveto/rules/examples/secrets.py +561 -0
- codeveto/rules/examples/security.py +608 -0
- codeveto/rules/examples/shell.py +174 -0
- codeveto/rules/examples/sql.py +194 -0
- codeveto/rules/examples/tests.py +497 -0
- codeveto/rules/go.py +328 -0
- codeveto/rules/hygiene.py +1094 -0
- codeveto/rules/js.py +768 -0
- codeveto/rules/python.py +1642 -0
- codeveto/rules/rust.py +209 -0
- codeveto/rules/secrets.py +1335 -0
- codeveto/rules/security.py +3680 -0
- codeveto/rules/shell.py +867 -0
- codeveto/rules/sql.py +629 -0
- codeveto/rules/tests.py +1404 -0
- codeveto/schema.py +384 -0
- codeveto/statements.py +607 -0
- codeveto/worktree.py +1176 -0
- codeveto/yamlish.py +1179 -0
- codeveto-0.1.0.dist-info/METADATA +253 -0
- codeveto-0.1.0.dist-info/RECORD +106 -0
- codeveto-0.1.0.dist-info/WHEEL +4 -0
- codeveto-0.1.0.dist-info/entry_points.txt +2 -0
- codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
codeveto/rules/sql.py
ADDED
|
@@ -0,0 +1,629 @@
|
|
|
1
|
+
"""SQL pack (SPEC 6.1): destructive and risky statements.
|
|
2
|
+
|
|
3
|
+
The rules read ``.sql`` files statement by statement (``ctx.statements()``,
|
|
4
|
+
comments and string contents masked) and SQL held in string literals of code
|
|
5
|
+
files. A code string counts as SQL only when it clearly is one: it starts
|
|
6
|
+
with the statement keyword in upper case, holds no interpolation, and is a
|
|
7
|
+
whole argument of a call or an element of a list (``execute("DELETE FROM t")``,
|
|
8
|
+
``[..., "TRUNCATE t"]``), so a string that is concatenated, formatted or
|
|
9
|
+
assembled later (``"UPDATE t SET a = 1" + where``) is never judged on its
|
|
10
|
+
first half. Migrations use the same rules; ``drop-table`` and ``drop-column``
|
|
11
|
+
skip down migrations (``*.down.sql``, ``down.sql``, goose, sql-migrate and
|
|
12
|
+
dbmate down sections), which revert what the up migration created.
|
|
13
|
+
|
|
14
|
+
Every rule skips test files: deleting or truncating every row is how tests
|
|
15
|
+
reset their tables.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import itertools
|
|
21
|
+
import re
|
|
22
|
+
from collections.abc import Iterator
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
|
|
25
|
+
from codeveto import lexers
|
|
26
|
+
from codeveto.rules.base import FileContext, Hit, rule
|
|
27
|
+
|
|
28
|
+
_CODE_LANGUAGES = frozenset({"python", "javascript", "typescript", "go", "rust", "java", "kotlin"})
|
|
29
|
+
_LANGUAGES = _CODE_LANGUAGES | {"sql"}
|
|
30
|
+
_CLASSES = frozenset({"source"})
|
|
31
|
+
|
|
32
|
+
_TOKEN = re.compile(r"[A-Za-z_][A-Za-z0-9_$]{0,127}|\"[^\"\n]{0,256}\"|`[^`\n]{0,256}`|[(),;.=*]")
|
|
33
|
+
_CODE_START = re.compile(r"[ \t\r\n]{0,64}(DELETE|UPDATE|DROP|TRUNCATE|GRANT|ALTER)[ \t\r\n]")
|
|
34
|
+
_DOWN_FILE = re.compile(r"(?:^|[._-])down\.sql\Z", re.IGNORECASE)
|
|
35
|
+
_SECTION = re.compile(
|
|
36
|
+
r"[ \t]{0,16}--[ \t]{0,8}(?:\+goose[ \t]{1,8}(up|down)|\+migrate[ \t]{1,8}(up|down)"
|
|
37
|
+
r"|migrate:(up|down))\b",
|
|
38
|
+
re.IGNORECASE,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
_EVIDENCE_TOKENS = 16
|
|
42
|
+
_SCAN_LIMIT = 256
|
|
43
|
+
"""Characters looked at around a code string for its call context."""
|
|
44
|
+
|
|
45
|
+
# Words that end a table reference instead of naming its alias.
|
|
46
|
+
_CLAUSE_WORDS = frozenset(
|
|
47
|
+
{
|
|
48
|
+
"WHERE",
|
|
49
|
+
"SET",
|
|
50
|
+
"USING",
|
|
51
|
+
"RETURNING",
|
|
52
|
+
"LIMIT",
|
|
53
|
+
"ORDER",
|
|
54
|
+
"JOIN",
|
|
55
|
+
"INNER",
|
|
56
|
+
"LEFT",
|
|
57
|
+
"RIGHT",
|
|
58
|
+
"FULL",
|
|
59
|
+
"CROSS",
|
|
60
|
+
"NATURAL",
|
|
61
|
+
"STRAIGHT_JOIN",
|
|
62
|
+
"FROM",
|
|
63
|
+
"ON",
|
|
64
|
+
"OUTPUT",
|
|
65
|
+
"WITH",
|
|
66
|
+
"OPTION",
|
|
67
|
+
"PARTITION",
|
|
68
|
+
}
|
|
69
|
+
)
|
|
70
|
+
_DELETE_MODIFIERS = frozenset({"LOW_PRIORITY", "QUICK", "IGNORE"})
|
|
71
|
+
_UPDATE_MODIFIERS = frozenset({"LOW_PRIORITY", "IGNORE", "ONLY"})
|
|
72
|
+
_NOT_A_COLUMN = frozenset(
|
|
73
|
+
{
|
|
74
|
+
"CONSTRAINT",
|
|
75
|
+
"INDEX",
|
|
76
|
+
"KEY",
|
|
77
|
+
"PRIMARY",
|
|
78
|
+
"FOREIGN",
|
|
79
|
+
"CHECK",
|
|
80
|
+
"PARTITION",
|
|
81
|
+
"DEFAULT",
|
|
82
|
+
"NOT",
|
|
83
|
+
"UNIQUE",
|
|
84
|
+
"FULLTEXT",
|
|
85
|
+
"SPATIAL",
|
|
86
|
+
"PERIOD",
|
|
87
|
+
"SYSTEM",
|
|
88
|
+
"IDENTITY",
|
|
89
|
+
"EXPRESSION",
|
|
90
|
+
"TRIGGER",
|
|
91
|
+
"ROW",
|
|
92
|
+
"ATTRIBUTE",
|
|
93
|
+
"CONSTRAINTS",
|
|
94
|
+
"EXCLUDE",
|
|
95
|
+
}
|
|
96
|
+
)
|
|
97
|
+
_GENERATED_VALUE = frozenset(
|
|
98
|
+
{"DEFAULT", "GENERATED", "AUTO_INCREMENT", "AUTOINCREMENT", "IDENTITY", "AS"}
|
|
99
|
+
)
|
|
100
|
+
_SERIAL_TYPES = frozenset({"SERIAL", "BIGSERIAL", "SMALLSERIAL", "SERIAL4", "SERIAL8", "SERIAL2"})
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@dataclass(frozen=True, slots=True)
|
|
104
|
+
class _Tok:
|
|
105
|
+
up: str
|
|
106
|
+
raw: str
|
|
107
|
+
start: int
|
|
108
|
+
end: int
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def is_name(self) -> bool:
|
|
112
|
+
first = self.raw[0]
|
|
113
|
+
return first in '"`' or first.isalpha() or first == "_"
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@dataclass(frozen=True, slots=True)
|
|
117
|
+
class _Finding:
|
|
118
|
+
kind: str
|
|
119
|
+
start: int
|
|
120
|
+
end: int
|
|
121
|
+
evidence: str
|
|
122
|
+
message: str
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _tokens(masked: str, base: int) -> list[_Tok]:
|
|
126
|
+
return [
|
|
127
|
+
_Tok(m.group().upper(), m.group(), base + m.start(), base + m.end())
|
|
128
|
+
for m in _TOKEN.finditer(masked)
|
|
129
|
+
]
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class _Stmt(list[_Tok]):
|
|
133
|
+
"""A statement's tokens; ``stop`` is where it ends (after its ``;``, if any)."""
|
|
134
|
+
|
|
135
|
+
stop: int = 0
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _split(tokens: list[_Tok]) -> Iterator[_Stmt]:
|
|
139
|
+
"""Statements of a token list, split at ``;``."""
|
|
140
|
+
current = _Stmt()
|
|
141
|
+
for tok in tokens:
|
|
142
|
+
if tok.up == ";":
|
|
143
|
+
if current:
|
|
144
|
+
current.stop = tok.end
|
|
145
|
+
yield current
|
|
146
|
+
current = _Stmt()
|
|
147
|
+
else:
|
|
148
|
+
current.append(tok)
|
|
149
|
+
if current:
|
|
150
|
+
current.stop = current[-1].end
|
|
151
|
+
yield current
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _evidence(tokens: list[_Tok]) -> str:
|
|
155
|
+
return " ".join(t.up if not t.is_name or t.up in _KEYWORDS else t.raw for t in tokens)[:300]
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
_KEYWORDS = frozenset(
|
|
159
|
+
{
|
|
160
|
+
"DELETE",
|
|
161
|
+
"UPDATE",
|
|
162
|
+
"DROP",
|
|
163
|
+
"TABLE",
|
|
164
|
+
"TRUNCATE",
|
|
165
|
+
"GRANT",
|
|
166
|
+
"ALL",
|
|
167
|
+
"ALTER",
|
|
168
|
+
"ADD",
|
|
169
|
+
"COLUMN",
|
|
170
|
+
"NOT",
|
|
171
|
+
"NULL",
|
|
172
|
+
"FROM",
|
|
173
|
+
"SET",
|
|
174
|
+
"ON",
|
|
175
|
+
"TO",
|
|
176
|
+
"IF",
|
|
177
|
+
"EXISTS",
|
|
178
|
+
"PRIVILEGES",
|
|
179
|
+
}
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _ups(st: list[_Tok]) -> set[str]:
|
|
184
|
+
return {t.up for t in st}
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _table_ref(tokens: list[_Tok], i: int) -> int | None:
|
|
188
|
+
"""Index after a (dotted) table name and optional alias at ``i``, or ``None``."""
|
|
189
|
+
if i >= len(tokens) or not tokens[i].is_name or tokens[i].up in _CLAUSE_WORDS:
|
|
190
|
+
return None
|
|
191
|
+
i += 1
|
|
192
|
+
for _ in range(4):
|
|
193
|
+
if i + 1 < len(tokens) and tokens[i].up == "." and tokens[i + 1].is_name:
|
|
194
|
+
i += 2
|
|
195
|
+
else:
|
|
196
|
+
break
|
|
197
|
+
if i < len(tokens) and tokens[i].up == "*":
|
|
198
|
+
i += 1
|
|
199
|
+
if i < len(tokens) and tokens[i].up == "AS":
|
|
200
|
+
return i + 2 if i + 1 < len(tokens) and tokens[i + 1].is_name else None
|
|
201
|
+
if i < len(tokens) and tokens[i].is_name and tokens[i].up not in _CLAUSE_WORDS:
|
|
202
|
+
i += 1
|
|
203
|
+
return i
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _delete_all(st: list[_Tok]) -> bool:
|
|
207
|
+
"""``DELETE FROM t [alias] [RETURNING ...]``: no WHERE, LIMIT, USING or JOIN."""
|
|
208
|
+
i = 1
|
|
209
|
+
while i < len(st) and st[i].up in _DELETE_MODIFIERS:
|
|
210
|
+
i += 1
|
|
211
|
+
if i >= len(st) or st[i].up != "FROM":
|
|
212
|
+
return False
|
|
213
|
+
i += 1
|
|
214
|
+
if i < len(st) and st[i].up == "ONLY":
|
|
215
|
+
i += 1
|
|
216
|
+
after = _table_ref(st, i)
|
|
217
|
+
if after is None:
|
|
218
|
+
return False
|
|
219
|
+
return after == len(st) or st[after].up == "RETURNING"
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _update_all(st: list[_Tok], code: bool) -> bool:
|
|
223
|
+
"""``UPDATE t [alias] SET ...`` with no WHERE, LIMIT or JOIN anywhere."""
|
|
224
|
+
i = 1
|
|
225
|
+
while i < len(st):
|
|
226
|
+
if st[i].up in _UPDATE_MODIFIERS:
|
|
227
|
+
i += 1
|
|
228
|
+
elif st[i].up == "OR" and i + 1 < len(st):
|
|
229
|
+
i += 2 # SQLite UPDATE OR REPLACE
|
|
230
|
+
else:
|
|
231
|
+
break
|
|
232
|
+
after = _table_ref(st, i)
|
|
233
|
+
if after is None or after >= len(st) or st[after].up != "SET":
|
|
234
|
+
return False
|
|
235
|
+
rest = st[after + 1 :]
|
|
236
|
+
if any(t.up in ("WHERE", "LIMIT", "JOIN") for t in rest):
|
|
237
|
+
return False
|
|
238
|
+
return not code or any(t.up == "=" for t in rest)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _names_after(st: list[_Tok], i: int) -> list[str]:
|
|
242
|
+
"""Comma-separated (dotted) names from ``i``: the last part of each, lower case."""
|
|
243
|
+
names: list[str] = []
|
|
244
|
+
while i < len(st) and st[i].is_name:
|
|
245
|
+
name = st[i].raw
|
|
246
|
+
i += 1
|
|
247
|
+
while i + 1 < len(st) and st[i].up == "." and st[i + 1].is_name:
|
|
248
|
+
name = st[i + 1].raw
|
|
249
|
+
i += 2
|
|
250
|
+
names.append(name.strip('"`').lower())
|
|
251
|
+
if i < len(st) and st[i].up == ",":
|
|
252
|
+
i += 1
|
|
253
|
+
else:
|
|
254
|
+
break
|
|
255
|
+
return names
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _created_table(st: list[_Tok]) -> str | None:
|
|
259
|
+
"""The table a ``CREATE [TEMP] TABLE [IF NOT EXISTS] name`` statement creates."""
|
|
260
|
+
if not st or st[0].up != "CREATE":
|
|
261
|
+
return None
|
|
262
|
+
i = 1
|
|
263
|
+
while i < len(st) and st[i].up in ("OR", "REPLACE", "TEMP", "TEMPORARY", "UNLOGGED", "GLOBAL"):
|
|
264
|
+
i += 1
|
|
265
|
+
if i >= len(st) or st[i].up != "TABLE":
|
|
266
|
+
return None
|
|
267
|
+
i += 1
|
|
268
|
+
if [t.up for t in st[i : i + 3]] == ["IF", "NOT", "EXISTS"]:
|
|
269
|
+
i += 3
|
|
270
|
+
names = _names_after(st, i)
|
|
271
|
+
return names[0] if names else None
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _dropped_tables(st: list[_Tok]) -> list[str] | None:
|
|
275
|
+
if len(st) < 2 or st[0].up != "DROP" or st[1].up != "TABLE":
|
|
276
|
+
return None
|
|
277
|
+
i = 2
|
|
278
|
+
if [t.up for t in st[i : i + 2]] == ["IF", "EXISTS"]:
|
|
279
|
+
i += 2
|
|
280
|
+
return _names_after(st, i)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _clauses(st: list[_Tok], i: int) -> Iterator[list[_Tok]]:
|
|
284
|
+
"""Top-level comma-separated clauses of an ``ALTER TABLE`` from token ``i``."""
|
|
285
|
+
depth = 0
|
|
286
|
+
current: list[_Tok] = []
|
|
287
|
+
for tok in st[i:]:
|
|
288
|
+
if tok.up == "(":
|
|
289
|
+
depth += 1
|
|
290
|
+
elif tok.up == ")":
|
|
291
|
+
depth = max(depth - 1, 0)
|
|
292
|
+
elif tok.up == "," and depth == 0:
|
|
293
|
+
if current:
|
|
294
|
+
yield current
|
|
295
|
+
current = []
|
|
296
|
+
continue
|
|
297
|
+
current.append(tok)
|
|
298
|
+
if current:
|
|
299
|
+
yield current
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _alter_target(st: list[_Tok]) -> tuple[str, int] | None:
|
|
303
|
+
"""``(table, index of the first clause)`` of an ``ALTER TABLE`` statement."""
|
|
304
|
+
if len(st) < 3 or st[0].up != "ALTER" or st[1].up != "TABLE":
|
|
305
|
+
return None
|
|
306
|
+
i = 2
|
|
307
|
+
if [t.up for t in st[i : i + 2]] == ["IF", "EXISTS"]:
|
|
308
|
+
i += 2
|
|
309
|
+
if i < len(st) and st[i].up == "ONLY":
|
|
310
|
+
i += 1
|
|
311
|
+
if i >= len(st) or not st[i].is_name:
|
|
312
|
+
return None
|
|
313
|
+
names = _names_after(st, i)
|
|
314
|
+
i += 1
|
|
315
|
+
while i + 1 < len(st) and st[i].up == "." and st[i + 1].is_name:
|
|
316
|
+
i += 2
|
|
317
|
+
if i < len(st) and st[i].up == "*":
|
|
318
|
+
i += 1
|
|
319
|
+
return (names[0] if names else ""), i
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _analyse(
|
|
323
|
+
st: list[_Tok], *, code: bool, down: bool, created: frozenset[str]
|
|
324
|
+
) -> Iterator[_Finding]:
|
|
325
|
+
head = st[0].up
|
|
326
|
+
whole = (st[0].start, st.stop if isinstance(st, _Stmt) else st[-1].end)
|
|
327
|
+
if head == "DELETE" and _delete_all(st):
|
|
328
|
+
yield _Finding("delete", *whole, _evidence(st[:_EVIDENCE_TOKENS]), "DELETE without WHERE")
|
|
329
|
+
elif head == "UPDATE" and _update_all(st, code):
|
|
330
|
+
yield _Finding("update", *whole, _evidence(st[:_EVIDENCE_TOKENS]), "UPDATE without WHERE")
|
|
331
|
+
elif head == "TRUNCATE" and len(st) > 1:
|
|
332
|
+
yield _Finding("truncate", *whole, _evidence(st[:_EVIDENCE_TOKENS]), "TRUNCATE")
|
|
333
|
+
elif head == "GRANT" and len(st) > 1 and st[1].up == "ALL" and {"ON", "TO"} <= _ups(st):
|
|
334
|
+
yield _Finding("grant", *whole, _evidence(st[:_EVIDENCE_TOKENS]), "GRANT ALL")
|
|
335
|
+
elif head == "DROP":
|
|
336
|
+
names = _dropped_tables(st)
|
|
337
|
+
if names and not down and not all(n in created for n in names):
|
|
338
|
+
yield _Finding("drop-table", *whole, _evidence(st[:_EVIDENCE_TOKENS]), "DROP TABLE")
|
|
339
|
+
elif head == "ALTER":
|
|
340
|
+
target = _alter_target(st)
|
|
341
|
+
if target is None:
|
|
342
|
+
return
|
|
343
|
+
table, first = target
|
|
344
|
+
for clause in _clauses(st, first):
|
|
345
|
+
yield from _alter_clause(clause, table, down=down, created=created)
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _alter_clause(
|
|
349
|
+
clause: list[_Tok], table: str, *, down: bool, created: frozenset[str]
|
|
350
|
+
) -> Iterator[_Finding]:
|
|
351
|
+
head = clause[0].up
|
|
352
|
+
span = (clause[0].start, clause[-1].end)
|
|
353
|
+
evidence = f"ALTER TABLE {table} " + _evidence(clause[:_EVIDENCE_TOKENS])
|
|
354
|
+
if head == "DROP" and len(clause) > 1 and not down:
|
|
355
|
+
nxt = clause[1]
|
|
356
|
+
if nxt.up == "COLUMN" or (nxt.is_name and nxt.up not in _NOT_A_COLUMN):
|
|
357
|
+
yield _Finding("drop-column", *span, evidence, "Column dropped")
|
|
358
|
+
elif head == "ADD" and len(clause) > 1 and table not in created:
|
|
359
|
+
if clause[1].up in _NOT_A_COLUMN:
|
|
360
|
+
return
|
|
361
|
+
ups = [t.up for t in clause]
|
|
362
|
+
not_null = any(a == "NOT" and b == "NULL" for a, b in itertools.pairwise(ups))
|
|
363
|
+
if not not_null or any(u in _GENERATED_VALUE or u in _SERIAL_TYPES for u in ups):
|
|
364
|
+
return
|
|
365
|
+
yield _Finding("not-null", *span, evidence, "NOT NULL column added without a default")
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
# --- Collecting statements ---------------------------------------------------------------
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def _down_lines(ctx: FileContext) -> tuple[bool, list[tuple[int, int]]]:
|
|
372
|
+
"""Is the whole file a down migration, and the line ranges of down sections."""
|
|
373
|
+
name = ctx.path.rsplit("/", 1)[-1]
|
|
374
|
+
if _DOWN_FILE.search(name):
|
|
375
|
+
return True, []
|
|
376
|
+
ranges: list[tuple[int, int]] = []
|
|
377
|
+
start: int | None = None
|
|
378
|
+
for number, line in enumerate(ctx.lines, start=1):
|
|
379
|
+
m = _SECTION.match(line)
|
|
380
|
+
if m is None:
|
|
381
|
+
continue
|
|
382
|
+
direction = (m.group(1) or m.group(2) or m.group(3)).lower()
|
|
383
|
+
if direction == "down" and start is None:
|
|
384
|
+
start = number
|
|
385
|
+
elif direction == "up" and start is not None:
|
|
386
|
+
ranges.append((start, number - 1))
|
|
387
|
+
start = None
|
|
388
|
+
if start is not None:
|
|
389
|
+
ranges.append((start, len(ctx.lines)))
|
|
390
|
+
return False, ranges
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _sql_file_statements(ctx: FileContext) -> Iterator[_Stmt]:
|
|
394
|
+
"""Each statement of a ``.sql`` file.
|
|
395
|
+
|
|
396
|
+
``statements()`` splits a long statement into chunks marked ``truncated``;
|
|
397
|
+
their tokens are joined again before splitting at ``;``, so a WHERE in a
|
|
398
|
+
later chunk still belongs to its DELETE.
|
|
399
|
+
"""
|
|
400
|
+
pending: list[_Tok] = []
|
|
401
|
+
for statement in ctx.statements():
|
|
402
|
+
tokens = _tokens(statement.masked, statement.start)
|
|
403
|
+
if statement.truncated:
|
|
404
|
+
pending.extend(tokens)
|
|
405
|
+
continue
|
|
406
|
+
if pending:
|
|
407
|
+
yield from _split(pending)
|
|
408
|
+
pending = []
|
|
409
|
+
yield from _split(tokens)
|
|
410
|
+
if pending:
|
|
411
|
+
yield from _split(pending)
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def _call_argument(masked: str, start: int, end: int) -> bool:
|
|
415
|
+
"""Is the literal at ``start..end`` a whole call argument or list element?"""
|
|
416
|
+
i = start - 1
|
|
417
|
+
floor = max(start - _SCAN_LIMIT, 0)
|
|
418
|
+
while i >= floor and masked[i] in " \t\r\n":
|
|
419
|
+
i -= 1
|
|
420
|
+
if i < floor or masked[i] not in "([,":
|
|
421
|
+
return False
|
|
422
|
+
j = end
|
|
423
|
+
ceiling = min(end + _SCAN_LIMIT, len(masked))
|
|
424
|
+
while j < ceiling and masked[j] in " \t\r\n":
|
|
425
|
+
j += 1
|
|
426
|
+
return j < ceiling and masked[j] in ")],"
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def _code_statements(ctx: FileContext) -> Iterator[list[_Tok]]:
|
|
430
|
+
"""Statements of the clear SQL string literals of a code file."""
|
|
431
|
+
text = ctx.new_text or ""
|
|
432
|
+
masked = ctx.masked_code
|
|
433
|
+
for span in ctx.strings():
|
|
434
|
+
if span.interpolations or span.kind not in ("plain", "raw", "template"):
|
|
435
|
+
continue
|
|
436
|
+
content = text[span.content_start : span.content_end]
|
|
437
|
+
if span.kind != "raw":
|
|
438
|
+
# Same-length stand-ins for escaped line breaks, so a "--" comment
|
|
439
|
+
# inside the literal ends where the SQL line does.
|
|
440
|
+
content = content.replace("\\n", " \n").replace("\\r", " ").replace("\\t", " ")
|
|
441
|
+
if not _CODE_START.match(content) or not _call_argument(masked, span.start, span.end):
|
|
442
|
+
continue
|
|
443
|
+
result = lexers.lex(content, "sql")
|
|
444
|
+
if result.partial:
|
|
445
|
+
continue
|
|
446
|
+
yield from _split(_tokens(lexers.mask(content, result), span.content_start))
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _findings(ctx: FileContext, kinds: frozenset[str]) -> Iterator[_Finding]:
|
|
450
|
+
if ctx.new_text is None or (not ctx.added_lines and not ctx.deletion_points):
|
|
451
|
+
return
|
|
452
|
+
if ctx.language == "sql":
|
|
453
|
+
whole_down, sections = _down_lines(ctx)
|
|
454
|
+
index = ctx.line_index
|
|
455
|
+
items = []
|
|
456
|
+
for st in _sql_file_statements(ctx):
|
|
457
|
+
line = index.line_of(st[0].start)
|
|
458
|
+
items.append((st, whole_down or any(a <= line <= b for a, b in sections)))
|
|
459
|
+
# Tables the up direction creates; a down section's CREATE restores, not rebuilds.
|
|
460
|
+
created = frozenset(
|
|
461
|
+
n for st, down in items if not down and (n := _created_table(st)) is not None
|
|
462
|
+
)
|
|
463
|
+
for st, down in items:
|
|
464
|
+
for finding in _analyse(st, code=False, down=down, created=created):
|
|
465
|
+
if finding.kind in kinds:
|
|
466
|
+
yield finding
|
|
467
|
+
return
|
|
468
|
+
statements = list(_code_statements(ctx))
|
|
469
|
+
created = frozenset(n for st in statements if (n := _created_table(st)) is not None)
|
|
470
|
+
for st in statements:
|
|
471
|
+
for finding in _analyse(st, code=True, down=False, created=created):
|
|
472
|
+
if finding.kind in kinds:
|
|
473
|
+
yield finding
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def _hits(ctx: FileContext, kind: str) -> Iterator[Hit]:
|
|
477
|
+
index = ctx.line_index
|
|
478
|
+
for finding in _findings(ctx, frozenset({kind})):
|
|
479
|
+
line, column = index.position(finding.start)
|
|
480
|
+
end_line = index.line_of(max(finding.end - 1, finding.start))
|
|
481
|
+
yield Hit(
|
|
482
|
+
line,
|
|
483
|
+
end_line=end_line if end_line > line else None,
|
|
484
|
+
column=column,
|
|
485
|
+
message=finding.message,
|
|
486
|
+
evidence=finding.evidence,
|
|
487
|
+
)
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
_COMMON = {
|
|
491
|
+
"languages": _LANGUAGES,
|
|
492
|
+
"classes": _CLASSES,
|
|
493
|
+
"scope": "line",
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
@rule(
|
|
498
|
+
id="sql/delete-without-where",
|
|
499
|
+
severity="error",
|
|
500
|
+
title="DELETE without WHERE",
|
|
501
|
+
rationale=(
|
|
502
|
+
"A DELETE with no WHERE clause removes every row of the table; it is almost always "
|
|
503
|
+
"a missing or lost condition."
|
|
504
|
+
),
|
|
505
|
+
hint="Add the WHERE clause; if emptying the table is intended, use TRUNCATE in a migration.",
|
|
506
|
+
tags={"sql", "data-loss"},
|
|
507
|
+
**_COMMON, # type: ignore[arg-type]
|
|
508
|
+
)
|
|
509
|
+
def delete_without_where(ctx: FileContext) -> Iterator[Hit]:
|
|
510
|
+
"""``DELETE FROM t`` with nothing after the table but an alias or ``RETURNING``.
|
|
511
|
+
|
|
512
|
+
Any ``WHERE`` (also after comments or on another line of the statement),
|
|
513
|
+
``LIMIT``, ``USING``, ``JOIN`` or other clause keeps it silent, as do
|
|
514
|
+
multi-table and CTE forms.
|
|
515
|
+
"""
|
|
516
|
+
return _hits(ctx, "delete")
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
@rule(
|
|
520
|
+
id="sql/update-without-where",
|
|
521
|
+
severity="error",
|
|
522
|
+
title="UPDATE without WHERE",
|
|
523
|
+
rationale=(
|
|
524
|
+
"An UPDATE with no WHERE clause rewrites every row of the table; it is almost "
|
|
525
|
+
"always a missing or lost condition."
|
|
526
|
+
),
|
|
527
|
+
hint="Add the WHERE clause that selects the rows to change.",
|
|
528
|
+
tags={"sql", "data-loss"},
|
|
529
|
+
**_COMMON, # type: ignore[arg-type]
|
|
530
|
+
)
|
|
531
|
+
def update_without_where(ctx: FileContext) -> Iterator[Hit]:
|
|
532
|
+
"""``UPDATE t SET ...`` with no ``WHERE``, ``LIMIT`` or ``JOIN`` in the statement.
|
|
533
|
+
|
|
534
|
+
``UPDATE ... FROM`` without a WHERE (a cross join) is reported; MySQL
|
|
535
|
+
multi-table updates (``UPDATE a, b SET``) and ``ON CONFLICT DO UPDATE``
|
|
536
|
+
are not.
|
|
537
|
+
"""
|
|
538
|
+
return _hits(ctx, "update")
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
@rule(
|
|
542
|
+
id="sql/drop-table",
|
|
543
|
+
severity="warning",
|
|
544
|
+
title="Table dropped",
|
|
545
|
+
rationale="Dropping a table deletes its data for good; a rollback cannot bring it back.",
|
|
546
|
+
hint="Confirm the data is no longer needed or archived, and that no code still reads it.",
|
|
547
|
+
tags={"sql", "data-loss", "migration"},
|
|
548
|
+
**_COMMON, # type: ignore[arg-type]
|
|
549
|
+
)
|
|
550
|
+
def drop_table(ctx: FileContext) -> Iterator[Hit]:
|
|
551
|
+
"""``DROP TABLE``, except in down migrations and for tables the same file creates.
|
|
552
|
+
|
|
553
|
+
``DROP TABLE IF EXISTS t; CREATE TABLE t (...)`` rebuilds a table and is
|
|
554
|
+
silent; ``DROP TEMPORARY TABLE`` is not a ``DROP TABLE``.
|
|
555
|
+
"""
|
|
556
|
+
return _hits(ctx, "drop-table")
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
@rule(
|
|
560
|
+
id="sql/drop-column",
|
|
561
|
+
severity="warning",
|
|
562
|
+
title="Column dropped",
|
|
563
|
+
rationale=(
|
|
564
|
+
"Dropping a column deletes its data and breaks every deployed version of the code "
|
|
565
|
+
"that still reads or writes it."
|
|
566
|
+
),
|
|
567
|
+
hint="Stop using the column in a release first, then drop it in a later migration.",
|
|
568
|
+
tags={"sql", "data-loss", "migration"},
|
|
569
|
+
**_COMMON, # type: ignore[arg-type]
|
|
570
|
+
)
|
|
571
|
+
def drop_column(ctx: FileContext) -> Iterator[Hit]:
|
|
572
|
+
"""``ALTER TABLE ... DROP [COLUMN] c`` (not constraints, indexes, defaults).
|
|
573
|
+
|
|
574
|
+
Down migrations are skipped.
|
|
575
|
+
"""
|
|
576
|
+
return _hits(ctx, "drop-column")
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
@rule(
|
|
580
|
+
id="sql/truncate",
|
|
581
|
+
severity="warning",
|
|
582
|
+
title="TRUNCATE",
|
|
583
|
+
rationale="TRUNCATE removes every row at once and, in most databases, cannot be undone.",
|
|
584
|
+
hint="Confirm emptying the table is intended in this environment.",
|
|
585
|
+
tags={"sql", "data-loss"},
|
|
586
|
+
**_COMMON, # type: ignore[arg-type]
|
|
587
|
+
)
|
|
588
|
+
def truncate(ctx: FileContext) -> Iterator[Hit]:
|
|
589
|
+
"""A ``TRUNCATE`` statement."""
|
|
590
|
+
return _hits(ctx, "truncate")
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
@rule(
|
|
594
|
+
id="sql/not-null-without-default",
|
|
595
|
+
severity="warning",
|
|
596
|
+
title="NOT NULL column added without a default",
|
|
597
|
+
rationale=(
|
|
598
|
+
"Adding a NOT NULL column without a default fails on a table that already has rows "
|
|
599
|
+
"(or rewrites the whole table), so the migration breaks in production."
|
|
600
|
+
),
|
|
601
|
+
hint="Add the column nullable or with a DEFAULT, backfill, then set NOT NULL.",
|
|
602
|
+
tags={"sql", "migration"},
|
|
603
|
+
**_COMMON, # type: ignore[arg-type]
|
|
604
|
+
)
|
|
605
|
+
def not_null_without_default(ctx: FileContext) -> Iterator[Hit]:
|
|
606
|
+
"""``ALTER TABLE t ADD [COLUMN] c type NOT NULL`` with no default.
|
|
607
|
+
|
|
608
|
+
``DEFAULT``, generated and identity columns, ``AUTO_INCREMENT`` and
|
|
609
|
+
serial types are fine, and so is a table the same file creates (it is
|
|
610
|
+
empty).
|
|
611
|
+
"""
|
|
612
|
+
return _hits(ctx, "not-null")
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
@rule(
|
|
616
|
+
id="sql/grant-all",
|
|
617
|
+
severity="warning",
|
|
618
|
+
title="GRANT ALL",
|
|
619
|
+
rationale=(
|
|
620
|
+
"GRANT ALL hands out every privilege, including ones the grantee never needs, such "
|
|
621
|
+
"as DROP, ALTER and TRUNCATE."
|
|
622
|
+
),
|
|
623
|
+
hint="Grant only the privileges the role needs (for example SELECT, INSERT, UPDATE).",
|
|
624
|
+
tags={"sql", "security", "least-privilege"},
|
|
625
|
+
**_COMMON, # type: ignore[arg-type]
|
|
626
|
+
)
|
|
627
|
+
def grant_all(ctx: FileContext) -> Iterator[Hit]:
|
|
628
|
+
"""``GRANT ALL [PRIVILEGES] ON ...``."""
|
|
629
|
+
return _hits(ctx, "grant")
|