codecop 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.
- codecop/__init__.py +7 -0
- codecop/access.py +140 -0
- codecop/access_postgres.py +284 -0
- codecop/advisor.py +1512 -0
- codecop/advisor_bench.py +493 -0
- codecop/advisor_ch.py +2080 -0
- codecop/advisor_view.py +381 -0
- codecop/advisors.py +184 -0
- codecop/agent.py +221 -0
- codecop/agentfacts.py +745 -0
- codecop/apply/__init__.py +327 -0
- codecop/apply/check.py +344 -0
- codecop/apply/cli.py +162 -0
- codecop/apply/clickhouse.py +379 -0
- codecop/apply/common.py +238 -0
- codecop/apply/html.py +264 -0
- codecop/apply/patch.py +213 -0
- codecop/apply/postgres.py +102 -0
- codecop/apply/trial.py +166 -0
- codecop/assemble.py +104 -0
- codecop/baseline.py +1043 -0
- codecop/bench.py +2464 -0
- codecop/blockers.py +935 -0
- codecop/budget.py +980 -0
- codecop/catalog_profile.py +525 -0
- codecop/changed.py +261 -0
- codecop/cicmd.py +1002 -0
- codecop/cli.py +5421 -0
- codecop/client.py +729 -0
- codecop/coverage.py +1067 -0
- codecop/coverage_reasons.py +116 -0
- codecop/crashlog.py +70 -0
- codecop/datagen.py +766 -0
- codecop/datagen_postgres.py +630 -0
- codecop/datagen_sqlite.py +323 -0
- codecop/dbcli.py +885 -0
- codecop/definitions.py +457 -0
- codecop/discover/__init__.py +702 -0
- codecop/discover/arms.py +160 -0
- codecop/discover/base.py +234 -0
- codecop/discover/dialect.py +296 -0
- codecop/discover/elixir.py +64 -0
- codecop/discover/engine_go.py +320 -0
- codecop/discover/go.py +1947 -0
- codecop/discover/java.py +1528 -0
- codecop/discover/loops.py +1671 -0
- codecop/discover/named_go.py +258 -0
- codecop/discover/origins.py +4565 -0
- codecop/discover/origins_ts.py +1584 -0
- codecop/discover/orm_django.py +2772 -0
- codecop/discover/orm_django_models.py +814 -0
- codecop/discover/orm_django_sql.py +662 -0
- codecop/discover/orm_ent.py +565 -0
- codecop/discover/orm_ex_ecto.py +2138 -0
- codecop/discover/orm_go.py +2134 -0
- codecop/discover/orm_go_bun.py +602 -0
- codecop/discover/orm_go_run.py +636 -0
- codecop/discover/orm_go_types.py +1082 -0
- codecop/discover/orm_java.py +1450 -0
- codecop/discover/orm_jdbi.py +743 -0
- codecop/discover/orm_jooq.py +806 -0
- codecop/discover/orm_jpa.py +1307 -0
- codecop/discover/orm_mybatis.py +730 -0
- codecop/discover/orm_py.py +557 -0
- codecop/discover/orm_py_peewee.py +1266 -0
- codecop/discover/orm_py_prisma.py +298 -0
- codecop/discover/orm_rb_activerecord.py +1906 -0
- codecop/discover/orm_rust.py +1248 -0
- codecop/discover/orm_rust_seaorm.py +734 -0
- codecop/discover/orm_sqlalchemy.py +2475 -0
- codecop/discover/orm_stats.py +307 -0
- codecop/discover/orm_tables.py +29 -0
- codecop/discover/orm_ts.py +503 -0
- codecop/discover/orm_ts_drizzle.py +697 -0
- codecop/discover/orm_ts_knex.py +1117 -0
- codecop/discover/orm_ts_kysely.py +861 -0
- codecop/discover/orm_ts_prisma.py +1045 -0
- codecop/discover/orm_ts_schema.py +169 -0
- codecop/discover/orm_ts_sequelize.py +1401 -0
- codecop/discover/orm_ts_typeorm.py +1067 -0
- codecop/discover/probes.py +323 -0
- codecop/discover/python.py +595 -0
- codecop/discover/ruby.py +793 -0
- codecop/discover/rust.py +2378 -0
- codecop/discover/schema.py +520 -0
- codecop/discover/schema_ent.py +145 -0
- codecop/discover/schema_ts.py +420 -0
- codecop/discover/tsresolve.py +257 -0
- codecop/discover/typescript.py +1728 -0
- codecop/discover/xml_mapper.py +526 -0
- codecop/engines/__init__.py +515 -0
- codecop/engines/base.py +498 -0
- codecop/engines/clickhouse.py +1558 -0
- codecop/engines/pg_ddl.py +444 -0
- codecop/engines/pg_hints.py +137 -0
- codecop/engines/postgres.py +1060 -0
- codecop/engines/sqlite.py +742 -0
- codecop/families/__init__.py +3 -0
- codecop/families/build.py +280 -0
- codecop/families/cli.py +177 -0
- codecop/families/coverage_hook.py +62 -0
- codecop/families/driver.py +221 -0
- codecop/families/goslice.py +229 -0
- codecop/families/goslice_tool/go.mod +3 -0
- codecop/families/goslice_tool/main.go +403 -0
- codecop/families/holes.py +451 -0
- codecop/families/images/Dockerfile.go +5 -0
- codecop/families/images/Dockerfile.python +4 -0
- codecop/families/images/Dockerfile.rust +4 -0
- codecop/families/isolate.py +171 -0
- codecop/families/locate.py +270 -0
- codecop/families/model.py +301 -0
- codecop/families/plangate.py +271 -0
- codecop/families/tagpatch.py +174 -0
- codecop/fidelity.py +671 -0
- codecop/fixgroups.py +130 -0
- codecop/formerly.py +91 -0
- codecop/grantscript.py +254 -0
- codecop/groupbench.py +1375 -0
- codecop/groups.py +594 -0
- codecop/groups_view.py +186 -0
- codecop/heat.py +1405 -0
- codecop/heatcli.py +219 -0
- codecop/joins.py +1749 -0
- codecop/joins_view.py +127 -0
- codecop/kinds/__init__.py +507 -0
- codecop/kinds/calls/__init__.py +501 -0
- codecop/kinds/calls/extract.py +1097 -0
- codecop/kinds/calls/harness.py +408 -0
- codecop/kinds/calls/measure.py +342 -0
- codecop/kinds/calls/rules.py +139 -0
- codecop/kinds/calls/runners/RunCalls.java +167 -0
- codecop/kinds/calls/runners/run_go.go +141 -0
- codecop/kinds/calls/runners/run_node.js +186 -0
- codecop/kinds/calls/runners/run_python.py +319 -0
- codecop/kinds/calls/runners/run_rust.rs +200 -0
- codecop/kinds/calls/standin.py +340 -0
- codecop/kinds/pipeline.py +288 -0
- codecop/kinds/regex/__init__.py +1167 -0
- codecop/kinds/regex/engines/RegexHarness.java +129 -0
- codecop/kinds/regex/engines/run_go.go +294 -0
- codecop/kinds/regex/engines/run_node.js +99 -0
- codecop/kinds/regex/engines/run_python.py +295 -0
- codecop/kinds/regex/engines/run_rust.rs +149 -0
- codecop/kinds/regex/extract.py +1438 -0
- codecop/kinds/regex/harness.py +235 -0
- codecop/kinds/regex/measure.py +270 -0
- codecop/kinds/regex/shapes.py +418 -0
- codecop/kinds/regex/syntax.py +1721 -0
- codecop/kinds/testkind.py +107 -0
- codecop/kinds/transaction/__init__.py +228 -0
- codecop/kinds/transaction/bind.py +355 -0
- codecop/kinds/transaction/measure.py +264 -0
- codecop/kinds/transaction/plan.py +462 -0
- codecop/kinds/transaction/rules.py +540 -0
- codecop/kinds/transaction/sandbox.py +94 -0
- codecop/kinds/transaction/scenarios.py +520 -0
- codecop/kinds/transaction/schedule.py +483 -0
- codecop/kinds/transaction/shapes.py +418 -0
- codecop/kinds/transaction/verify.py +293 -0
- codecop/live.py +237 -0
- codecop/loopbench.py +2071 -0
- codecop/loopschema.py +591 -0
- codecop/mcpserver.py +120 -0
- codecop/mechanism.py +214 -0
- codecop/members.py +200 -0
- codecop/multi.py +443 -0
- codecop/observed.py +1868 -0
- codecop/parts.py +102 -0
- codecop/patterns.py +830 -0
- codecop/patterns_view.py +559 -0
- codecop/plangate.py +242 -0
- codecop/profile.py +439 -0
- codecop/prompts/areas.md +19 -0
- codecop/prompts/observed_variants.md +20 -0
- codecop/prompts/profile.md +60 -0
- codecop/prompts/profile_postgres.md +68 -0
- codecop/prompts/profile_sizes.md +26 -0
- codecop/prompts/profile_sqlite.md +69 -0
- codecop/prompts/rank.md +84 -0
- codecop/prompts/rank_postgres.md +96 -0
- codecop/prompts/rank_sqlite.md +94 -0
- codecop/prompts/scenario_variants.md +20 -0
- codecop/rank.py +1473 -0
- codecop/realdb/__init__.py +688 -0
- codecop/realdb/clickhouse.py +1223 -0
- codecop/realdb/facts.py +815 -0
- codecop/realdb/locality.py +964 -0
- codecop/realdb/locks.py +355 -0
- codecop/realdb/match.py +531 -0
- codecop/realdb/postgres.py +643 -0
- codecop/realdb/ratios.py +77 -0
- codecop/realdb/sample.py +126 -0
- codecop/relations.py +227 -0
- codecop/report.py +1854 -0
- codecop/resources.py +332 -0
- codecop/resources_view.py +266 -0
- codecop/rules/entry_points.toml +1013 -0
- codecop/rules/sinks.toml +362 -0
- codecop/runsonce.py +8 -0
- codecop/sandboxschema.py +555 -0
- codecop/scenario_agent.py +172 -0
- codecop/scenario_bind.py +507 -0
- codecop/scenario_sql.py +971 -0
- codecop/scenarios.py +675 -0
- codecop/scenarios_view.py +274 -0
- codecop/schemacli.py +67 -0
- codecop/schemas/areas_output.schema.json +21 -0
- codecop/schemas/profile_output.schema.json +362 -0
- codecop/schemas/rank_output.schema.json +385 -0
- codecop/sizes.py +200 -0
- codecop/sqlinfo.py +558 -0
- codecop/typedparams.py +576 -0
- codecop/verdicts.py +212 -0
- codecop/writebench.py +720 -0
- codecop/writecost.py +440 -0
- codecop/writes.py +1208 -0
- codecop-0.1.0.dist-info/METADATA +42 -0
- codecop-0.1.0.dist-info/RECORD +222 -0
- codecop-0.1.0.dist-info/WHEEL +4 -0
- codecop-0.1.0.dist-info/entry_points.txt +2 -0
- codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,451 @@
|
|
|
1
|
+
"""Role-typed filling of a template's run-time parts, and its conditional arms: the static family (no code runs).
|
|
2
|
+
|
|
3
|
+
Each «expr» of a site's template gets a role from the SQL around it (role()):
|
|
4
|
+
|
|
5
|
+
value becomes a typed bind (`?`), or the literal the placeholder holds
|
|
6
|
+
table, column, list, cte
|
|
7
|
+
a name: resolved through constants, the string arms of the statement that defines it, string-returning
|
|
8
|
+
helpers, and struct-literal fields taken jointly per literal (cfg.Table and cfg.KeyCol vary together)
|
|
9
|
+
predicate, tail, order
|
|
10
|
+
when not resolvable, left out (`TRUE`, nothing, `1`): the statement is a superset of what runs and its
|
|
11
|
+
basis is `part_left_out` (a baseline only, never a fix)
|
|
12
|
+
«or: …» an optional arm: two variants, with and without it
|
|
13
|
+
|
|
14
|
+
Variants are the base choice plus one alternative at a time, never every combination.
|
|
15
|
+
|
|
16
|
+
Reads repository source as text only. Never executes anything.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import collections
|
|
22
|
+
import os
|
|
23
|
+
import re
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
from ..mechanism import VALUE_CALL
|
|
27
|
+
from . import model
|
|
28
|
+
|
|
29
|
+
PH = re.compile(r"«([^»]*)»")
|
|
30
|
+
EXT = {"rust": ".rs", "go": ".go", "python": ".py", "typescript": ".ts", "java": ".java"}
|
|
31
|
+
DEFAULTS = {"max_choices": 12, "max_variants": 36, "max_package_bytes": 3_000_000}
|
|
32
|
+
STRLIT = r'(?:r#"(?P<raw>.*?)"#|"(?P<s>(?:[^"\\\n]|\\.)*)"|`(?P<bt>[^`]*)`)'
|
|
33
|
+
BIND = "\x00BIND\x00"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Source:
|
|
37
|
+
"""Repository files read as text, with the sibling files of a package (tests left out)."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, root: Path | str, max_package_bytes: int = DEFAULTS["max_package_bytes"]):
|
|
40
|
+
self.root = Path(root)
|
|
41
|
+
self.files: dict[str, str] = {}
|
|
42
|
+
self.dirs: dict[tuple[str, str], str] = {}
|
|
43
|
+
self.max_package_bytes = max_package_bytes
|
|
44
|
+
|
|
45
|
+
def text(self, rel: str) -> str:
|
|
46
|
+
if rel not in self.files:
|
|
47
|
+
try:
|
|
48
|
+
self.files[rel] = (self.root / rel).read_text(encoding="utf-8", errors="replace")
|
|
49
|
+
except OSError:
|
|
50
|
+
self.files[rel] = ""
|
|
51
|
+
return self.files[rel]
|
|
52
|
+
|
|
53
|
+
def repo_consts(self, name: str, lang: str) -> set[str]:
|
|
54
|
+
"""String constants named `name` anywhere in the repository's non-test source of that language (a constant in
|
|
55
|
+
another module of the crate or package). Built once per language."""
|
|
56
|
+
key = ("__consts__", lang)
|
|
57
|
+
if key not in self.dirs:
|
|
58
|
+
from ..discover import list_files
|
|
59
|
+
from ..discover.base import is_test_path
|
|
60
|
+
idx: dict[str, set[str]] = collections.defaultdict(set)
|
|
61
|
+
pat = re.compile(r"(?:const|static)\s+([A-Z][A-Z0-9_]+)\s*(?::\s*&(?:'static\s+)?str)?\s*=\s*" + STRLIT + r"\s*;", re.S) \
|
|
62
|
+
if lang == "rust" else re.compile(r"(?m)^\s*(?:const\s+|final\s+static\s+String\s+|static\s+final\s+String\s+|public\s+static\s+final\s+String\s+|private\s+static\s+final\s+String\s+)?([A-Z][A-Z0-9_]+)\s*(?:string\s*|:\s*str\s*)?=\s*" + STRLIT + r"\s*;?\s*$")
|
|
63
|
+
ext = EXT.get(lang, ".x")
|
|
64
|
+
try:
|
|
65
|
+
files = [f for f in list_files(self.root) if f.endswith(ext) and not is_test_path(f)]
|
|
66
|
+
except OSError:
|
|
67
|
+
files = []
|
|
68
|
+
for f in files:
|
|
69
|
+
for m in pat.finditer(self.text(f)):
|
|
70
|
+
idx[m.group(1)].add(lit_value(m))
|
|
71
|
+
self.dirs[key] = idx # type: ignore[assignment]
|
|
72
|
+
return set(self.dirs[key].get(name, ())) # type: ignore[union-attr]
|
|
73
|
+
|
|
74
|
+
def package(self, rel: str, lang: str) -> str:
|
|
75
|
+
d = os.path.dirname(rel)
|
|
76
|
+
if (d, lang) not in self.dirs:
|
|
77
|
+
out = []
|
|
78
|
+
try:
|
|
79
|
+
for f in sorted(os.listdir(self.root / d)):
|
|
80
|
+
if f.endswith(EXT.get(lang, ".x")) and not re.search(r"_test\.|^test_|tests\.rs$", f):
|
|
81
|
+
out.append(self.text(os.path.join(d, f)))
|
|
82
|
+
except OSError:
|
|
83
|
+
pass
|
|
84
|
+
self.dirs[(d, lang)] = "\n".join(out)[: self.max_package_bytes]
|
|
85
|
+
return self.dirs[(d, lang)]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def lit_value(m: re.Match) -> str:
|
|
89
|
+
if m.group("raw") is not None:
|
|
90
|
+
return m.group("raw")
|
|
91
|
+
if m.group("bt") is not None:
|
|
92
|
+
return m.group("bt")
|
|
93
|
+
return m.group("s").replace('\\"', '"').replace("\\n", "\n").replace("\\'", "'")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def as_literal(expr: str) -> str | None:
|
|
97
|
+
m = re.fullmatch(r"(?:String::from\()?" + STRLIT + r"\)?(?:\.(?:to_string|into|to_owned)\(\))?", expr.strip(), re.S)
|
|
98
|
+
return lit_value(m) if m else None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def func_window(text: str, line: int, lang: str) -> str:
|
|
102
|
+
lines = text.split("\n")
|
|
103
|
+
i = min(max(line - 1, 0), max(len(lines) - 1, 0))
|
|
104
|
+
start = max(0, i - 400)
|
|
105
|
+
pat = {"rust": r"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:const\s+)?(?:async\s+)?fn\s", "go": r"^func\s",
|
|
106
|
+
"python": r"^\s*(?:async\s+)?def\s"}.get(lang, r"^\S")
|
|
107
|
+
j = i
|
|
108
|
+
while j > start and not re.match(pat, lines[j]):
|
|
109
|
+
j -= 1
|
|
110
|
+
return "\n".join(lines[j:i + 60])
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def consts(text: str, name: str) -> set[str]:
|
|
114
|
+
out = set()
|
|
115
|
+
n = re.escape(name)
|
|
116
|
+
for m in re.finditer(r"(?:const|static|pub const|let)\s+" + n + r"\s*(?::\s*&(?:'static\s+)?str)?\s*=\s*" + STRLIT + r"\s*;", text, re.S):
|
|
117
|
+
out.add(lit_value(m))
|
|
118
|
+
for m in re.finditer(r"(?m)^\s*(?:const\s+|var\s+)?" + n + r"\s*(?:string\s*)?=\s*" + STRLIT + r"\s*$", text):
|
|
119
|
+
out.add(lit_value(m))
|
|
120
|
+
for m in re.finditer(r"(?:const|static)\s+" + n + r"\s*:\s*(?:usize|u64|u32|i64|i32|u16|u8)\s*=\s*([\d_]+)\s*;", text):
|
|
121
|
+
out.add(m.group(1).replace("_", ""))
|
|
122
|
+
for m in re.finditer(r"(?m)^\s*(?:const\s+)?" + n + r"\s*(?:int\d*\s*)?=\s*(\d+)\s*$", text):
|
|
123
|
+
out.add(m.group(1))
|
|
124
|
+
return out
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def local_arms(win: str, name: str, lang: str) -> list[str] | None:
|
|
128
|
+
"""String literals of the statement that defines `name`; None when it also formats or calls."""
|
|
129
|
+
m = None
|
|
130
|
+
for m in re.finditer(r"(?:let\s+(?:mut\s+)?" + re.escape(name) + r"\b[^=;]*=|\b" + re.escape(name) + r"\s*:?=)(?!=)", win):
|
|
131
|
+
pass
|
|
132
|
+
if not m:
|
|
133
|
+
return None
|
|
134
|
+
rest = win[m.end():]
|
|
135
|
+
depth = 0
|
|
136
|
+
end = len(rest)
|
|
137
|
+
for i, ch in enumerate(rest):
|
|
138
|
+
if ch in "({[":
|
|
139
|
+
depth += 1
|
|
140
|
+
elif ch in ")}]":
|
|
141
|
+
depth -= 1
|
|
142
|
+
elif (ch == ";" or (ch == "\n" and lang in ("go", "python"))) and depth <= 0:
|
|
143
|
+
end = i
|
|
144
|
+
break
|
|
145
|
+
if depth < 0:
|
|
146
|
+
end = i
|
|
147
|
+
break
|
|
148
|
+
stmt = rest[:end]
|
|
149
|
+
if re.search(r"format!|Sprintf|\.join\(|Join\(|\+|f\"|\.format\(|push", stmt):
|
|
150
|
+
return None
|
|
151
|
+
bare = re.sub(r"\.(?:to_string|to_owned|into|as_str|clone|as_ref)\(\)|\bString::from\(|\bSome\(|\bOk\(", "",
|
|
152
|
+
re.sub(STRLIT, '""', stmt, flags=re.S))
|
|
153
|
+
if re.search(r"[\w$\])]\s*\(", bare):
|
|
154
|
+
return None # `timeExpr(query, "hour")`: the call's string arguments are not its values
|
|
155
|
+
vals = [lit_value(x) for x in re.finditer(STRLIT, stmt, re.S)]
|
|
156
|
+
if lang == "rust" and "match" in stmt:
|
|
157
|
+
vals = [lit_value(x) for x in re.finditer(r"=>\s*" + STRLIT, stmt, re.S)] or vals
|
|
158
|
+
return list(dict.fromkeys(vals)) or None
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
_EMPTY = r"(?:\"\"|''|``|null|undefined|None)"
|
|
162
|
+
EMPTY_ARM = re.compile(r"^(?P<c1>[^?]+?)\s*\?\s*(?P<a1>.+?)\s*:\s*" + _EMPTY + r"\s*$|^(?P<c2>[^?]+?)\s*\?\s*" + _EMPTY
|
|
163
|
+
+ r"\s*:\s*(?P<a2>.+?)\s*$|^(?P<a3>.+?)\s+if\s+(?P<c3>.+?)\s+else\s+" + _EMPTY + r"\s*$", re.S)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def empty_arm(expr: str) -> tuple[str, str] | None:
|
|
167
|
+
"""(condition, other arm) of `c ? x : ""` / `c ? "" : x` / `x if c else ""`: the empty arm is a statement the site
|
|
168
|
+
really sends (the clause is simply not there), so it is an exact variant, not a part left out."""
|
|
169
|
+
m = EMPTY_ARM.match(expr.strip())
|
|
170
|
+
if not m:
|
|
171
|
+
return None
|
|
172
|
+
for c, a in (("c1", "a1"), ("c2", "a2"), ("c3", "a3")):
|
|
173
|
+
if m.group(c) is not None:
|
|
174
|
+
return m.group(c).strip(), m.group(a).strip()
|
|
175
|
+
return None
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def def_stmt(win: str, name: str, lang: str) -> str | None:
|
|
179
|
+
"""The right-hand side of the last statement in `win` that assigns `name`."""
|
|
180
|
+
m = None
|
|
181
|
+
for m in re.finditer(r"(?:(?:let|const|var)\s+(?:mut\s+)?" + re.escape(name) + r"\b[^=;]*=|\b" + re.escape(name) + r"\s*:?=)(?![=>])", win):
|
|
182
|
+
pass
|
|
183
|
+
if not m:
|
|
184
|
+
return None
|
|
185
|
+
rest, depth = win[m.end():], 0
|
|
186
|
+
for i, ch in enumerate(rest):
|
|
187
|
+
if ch in "({[":
|
|
188
|
+
depth += 1
|
|
189
|
+
elif ch in ")}]":
|
|
190
|
+
depth -= 1
|
|
191
|
+
if depth < 0:
|
|
192
|
+
return rest[:i]
|
|
193
|
+
elif (ch == ";" or (ch == "\n" and lang in ("go", "python"))) and depth <= 0:
|
|
194
|
+
return rest[:i]
|
|
195
|
+
return rest
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def fn_returns(text: str, name: str, lang: str) -> list[str] | None:
|
|
199
|
+
pat = {"rust": r"fn\s+%s\s*(?:<[^>]*>)?\s*\(([^)]*)\)[^{;]*\{", "go": r"func\s+(?:\([^)]*\)\s*)?%s\s*\(([^)]*)\)[^{]*\{",
|
|
200
|
+
"python": r"def\s+%s\s*\(([^)]*)\)[^:]*:"}.get(lang)
|
|
201
|
+
if not pat:
|
|
202
|
+
return None
|
|
203
|
+
m = re.search(pat % re.escape(name), text)
|
|
204
|
+
if not m:
|
|
205
|
+
return None
|
|
206
|
+
body = text[m.end():]
|
|
207
|
+
end = len(body)
|
|
208
|
+
if lang == "python":
|
|
209
|
+
mm = re.search(r"\n(?=\S)", body)
|
|
210
|
+
end = mm.start() if mm else len(body)
|
|
211
|
+
else:
|
|
212
|
+
depth = 1
|
|
213
|
+
for i, ch in enumerate(body):
|
|
214
|
+
if ch == "{":
|
|
215
|
+
depth += 1
|
|
216
|
+
elif ch == "}":
|
|
217
|
+
depth -= 1
|
|
218
|
+
if depth == 0:
|
|
219
|
+
end = i
|
|
220
|
+
break
|
|
221
|
+
body = body[:end]
|
|
222
|
+
if re.search(r"format!|Sprintf|Fprintf|\.join\(|Join\(|push_str|WriteString|f\"|\.format\(", body):
|
|
223
|
+
return None
|
|
224
|
+
vals = [v for v in dict.fromkeys(lit_value(x) for x in re.finditer(STRLIT, body, re.S)) if v.strip()]
|
|
225
|
+
return vals[:8] or None
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def struct_groups(pkg: str, fields: list[str]) -> list[dict]:
|
|
229
|
+
"""Joint values: every {...} literal (no nested braces) that sets all `fields` to strings."""
|
|
230
|
+
out: list[dict] = []
|
|
231
|
+
for g in re.finditer(r"\{([^{}]{0,1500})\}", pkg):
|
|
232
|
+
body = g.group(1)
|
|
233
|
+
vals = {}
|
|
234
|
+
for f in fields:
|
|
235
|
+
m = re.search(r"\b" + re.escape(f) + r"\s*:\s*" + STRLIT, body)
|
|
236
|
+
if not m:
|
|
237
|
+
break
|
|
238
|
+
vals[f] = lit_value(m)
|
|
239
|
+
else:
|
|
240
|
+
if vals not in out:
|
|
241
|
+
out.append(vals)
|
|
242
|
+
return out
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def raw_role(left: str, right: str) -> str:
|
|
246
|
+
"""The prototype's fine role of a part from the SQL text around it."""
|
|
247
|
+
l = left.rstrip()
|
|
248
|
+
r = right.lstrip()
|
|
249
|
+
lu = l.upper()
|
|
250
|
+
if left.endswith("'") and right.startswith("'"):
|
|
251
|
+
return "qvalue"
|
|
252
|
+
if l.count("'") % 2 == 1 and "'" in right.split("\n")[0]:
|
|
253
|
+
return "instring"
|
|
254
|
+
if re.search(r"(\bLIMIT|\bOFFSET|[=<>]|!=|\bLIKE|\bILIKE|\bIN\s*\(|\bANY\s*\(|\bINTERVAL|toInterval\w+\(|\bVALUES\s*\((?:[^()]|\([^()]*\))*|\bTOP|\bSET\s+\w+\s*=|\bTHEN|\bELSE|\bBETWEEN)\s*$", lu):
|
|
255
|
+
return "value"
|
|
256
|
+
if re.search(r"(\bFROM|\bJOIN|\bINTO|\bUPDATE|\bTABLE|\bEXISTS|\bONLY)\s*$", lu) or (
|
|
257
|
+
re.search(r"\w\.$", l) and re.search(r"(\bFROM|\bJOIN|\bINTO|\bUPDATE|\bTABLE)\s+[\w\"`]+\.$", lu)):
|
|
258
|
+
return "table"
|
|
259
|
+
if re.search(r"(\bWHERE|\bAND|\bOR|\bON|\bHAVING|\bPREWHERE|\bNOT|\bWHEN)\s*\(?\s*$", lu):
|
|
260
|
+
return "bool"
|
|
261
|
+
if re.search(r"\bWITH\s*$", lu) or (re.search(r"\),\s*$", l) and re.match(r"\s*,?\s*(SELECT|\w+\s+AS\s*\()", right, re.I)):
|
|
262
|
+
return "cte"
|
|
263
|
+
if re.search(r"\bORDER\s+BY\s*$", lu):
|
|
264
|
+
return "order"
|
|
265
|
+
if re.search(r"(\bSELECT|\bDISTINCT|,|\bBY|\()\s*$", lu):
|
|
266
|
+
return "expr"
|
|
267
|
+
if re.search(r"\w\.$", l):
|
|
268
|
+
return "colname"
|
|
269
|
+
if r.startswith("."):
|
|
270
|
+
return "alias"
|
|
271
|
+
if re.match(r"\s*(AND|OR|ORDER|GROUP|LIMIT|\)|$|UNION|SETTINGS|FORMAT)", PH.sub(" ", right), re.I):
|
|
272
|
+
return "tail" # (a run-time part followed by more of them and then a clause end: a tail too)
|
|
273
|
+
return "unknown"
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def whole(text: str) -> bool:
|
|
277
|
+
"""A string that can stand for a whole part: balanced parentheses, not ending or starting in an operator."""
|
|
278
|
+
t = text.strip()
|
|
279
|
+
if not t or t.count("(") != t.count(")") or t.count("'") % 2:
|
|
280
|
+
return False
|
|
281
|
+
return not re.search(r"(=|<|>|\bAND|\bOR|\bNOT|\(|,|\bWHERE|\bON)\s*$", t, re.I) and not re.match(r"^\s*(\)|AND\b|OR\b|,)", t, re.I)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
ROLE_OF = {"qvalue": "value", "instring": "value", "value": "value", "table": "table", "bool": "predicate", "cte": "cte",
|
|
285
|
+
"order": "order", "expr": "list", "colname": "column", "alias": "column", "tail": "tail", "unknown": "unknown"}
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def role(left: str, right: str) -> str:
|
|
289
|
+
"""The family data model's role of a part (model.ROLES)."""
|
|
290
|
+
return ROLE_OF[raw_role(left, right)]
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def fill(site: dict, src: Source, settings: dict | None = None) -> tuple[list[dict], list[str]]:
|
|
294
|
+
"""The static variants of one site: ([model.variant], reasons it could not be filled). Never both empty when the
|
|
295
|
+
site has parts: either variants or at least one reason."""
|
|
296
|
+
cfg = {**DEFAULTS, **(settings or {})}
|
|
297
|
+
maxc = int(cfg["max_choices"])
|
|
298
|
+
sql = site.get("sql") or ""
|
|
299
|
+
lang = site.get("language") or ""
|
|
300
|
+
holes = [(m.start(), m.end(), m.group(1)) for m in PH.finditer(sql)]
|
|
301
|
+
if not holes:
|
|
302
|
+
return [], []
|
|
303
|
+
file = site.get("file") or ""
|
|
304
|
+
text = src.text(file)
|
|
305
|
+
pkg = src.package(file, lang)
|
|
306
|
+
win = func_window(text, int(site.get("line") or 1), lang)
|
|
307
|
+
bases: dict[str, set[str]] = collections.defaultdict(set)
|
|
308
|
+
for _, _, e in holes:
|
|
309
|
+
m = re.fullmatch(r"(?:&)?(\w+(?:\[[^\]]*\])?)\.(\w+)", e.strip())
|
|
310
|
+
if m and m.group(1) != "self":
|
|
311
|
+
bases[m.group(1)].add(m.group(2))
|
|
312
|
+
m = re.fullmatch(r"self\.(\w+)\.(\w+)", e.strip())
|
|
313
|
+
if m:
|
|
314
|
+
bases["self." + m.group(1)].add(m.group(2))
|
|
315
|
+
joint = {b: struct_groups(pkg, sorted(fs)) for b, fs in bases.items()}
|
|
316
|
+
choices: list[tuple[str, object]] = []
|
|
317
|
+
fails: list[str] = []
|
|
318
|
+
approx: list[str] = []
|
|
319
|
+
for (a, b, e) in holes:
|
|
320
|
+
left, right = sql[max(0, a - 200):a], sql[b:b + 80]
|
|
321
|
+
es = e.strip()
|
|
322
|
+
ro = raw_role(left, right)
|
|
323
|
+
if es.startswith("or:"):
|
|
324
|
+
arm = es[3:].strip()
|
|
325
|
+
choices.append(("opt", [(" " + arm + " " if arm else "", f"with {arm[:40]}"), ("", f"without {arm[:40]}")]))
|
|
326
|
+
continue
|
|
327
|
+
lv = as_literal(es)
|
|
328
|
+
if lv is not None:
|
|
329
|
+
choices.append(("lit", [(lv, "literal")]))
|
|
330
|
+
continue
|
|
331
|
+
name_only = re.fullmatch(r"[A-Za-z_$][\w$]*", es)
|
|
332
|
+
ea = empty_arm(es) or (empty_arm(def_stmt(win, es, lang) or "") if name_only else None)
|
|
333
|
+
if ea is not None: # the clause is optional: the statement without it is sent (base), the arm when known
|
|
334
|
+
cond, arm = ea
|
|
335
|
+
opts = [("", f"without {arm[:40]} ({cond[:30]} false)")]
|
|
336
|
+
av = as_literal(arm)
|
|
337
|
+
if av is not None and "${" not in av and "{" not in av and whole(av):
|
|
338
|
+
opts.append((" " + av + " ", f"with {av.strip()[:40]}"))
|
|
339
|
+
choices.append(("opt", opts))
|
|
340
|
+
continue
|
|
341
|
+
if ro in ("qvalue", "instring"):
|
|
342
|
+
choices.append(("bindq", [(BIND, "value")]))
|
|
343
|
+
continue
|
|
344
|
+
if ro != "table" and VALUE_CALL.match(es): # `SqlString.escape(tz)`, `sql.string(x)`: a quoted literal
|
|
345
|
+
choices.append(("bind", [(BIND, "value")]))
|
|
346
|
+
continue
|
|
347
|
+
cands = None
|
|
348
|
+
mfield = re.fullmatch(r"(?:&)?((?:self\.)?\w+(?:\[[^\]]*\])?)\.(\w+)", es)
|
|
349
|
+
mname = re.fullmatch(r"(?:&)?(?:self\.)?(\w+)(?:\.as_str\(\)|\.to_string\(\)|\.clone\(\))?", es)
|
|
350
|
+
mcall = re.fullmatch(r"(?:&)?(?:self\.|Self::|\w+::)?(\w+)\((.*)\)", es, re.S)
|
|
351
|
+
if mfield and joint.get(mfield.group(1)):
|
|
352
|
+
choices.append(("joint", (mfield.group(1), mfield.group(2))))
|
|
353
|
+
continue
|
|
354
|
+
if mname:
|
|
355
|
+
n = mname.group(1)
|
|
356
|
+
c = consts(text, n) or consts(pkg, n)
|
|
357
|
+
if not c and re.fullmatch(r"[A-Z][A-Z0-9_]+", n):
|
|
358
|
+
c = src.repo_consts(n, lang)
|
|
359
|
+
if len(c) == 1:
|
|
360
|
+
cands = [(next(iter(c)), "constant")]
|
|
361
|
+
else:
|
|
362
|
+
la = local_arms(win, n, lang)
|
|
363
|
+
if la:
|
|
364
|
+
cands = [(v, "arm") for v in la]
|
|
365
|
+
if cands is None and mfield:
|
|
366
|
+
vals: list[str] = []
|
|
367
|
+
for m in re.finditer(r"\b" + re.escape(mfield.group(2)) + r"\s*:\s*" + STRLIT, pkg):
|
|
368
|
+
v = lit_value(m)
|
|
369
|
+
if v not in vals:
|
|
370
|
+
vals.append(v)
|
|
371
|
+
if vals:
|
|
372
|
+
cands = [(v, "struct field") for v in vals]
|
|
373
|
+
elif mcall:
|
|
374
|
+
fr = fn_returns(text, mcall.group(1), lang) or fn_returns(pkg, mcall.group(1), lang)
|
|
375
|
+
if fr:
|
|
376
|
+
cands = [(v, "helper returns") for v in fr]
|
|
377
|
+
if cands: # a fragment of a clause (`tenant_id =`, `(`, `OR`) is not a value of the part
|
|
378
|
+
cands = [c for c in cands if whole(c[0])] or None
|
|
379
|
+
if cands and ro == "value" and not all(re.fullmatch(r"[\d.]+", c[0]) for c in cands):
|
|
380
|
+
cands = None
|
|
381
|
+
if cands:
|
|
382
|
+
choices.append(("cand", cands[:maxc]))
|
|
383
|
+
continue
|
|
384
|
+
if ro == "value":
|
|
385
|
+
choices.append(("bind", [(BIND, "value")]))
|
|
386
|
+
continue
|
|
387
|
+
if ro == "bool":
|
|
388
|
+
choices.append(("omit", [("TRUE", "predicate left out")]))
|
|
389
|
+
approx.append("predicate left out: " + es[:60])
|
|
390
|
+
continue
|
|
391
|
+
if ro == "tail":
|
|
392
|
+
choices.append(("omit", [("", "tail left out")]))
|
|
393
|
+
approx.append("tail left out: " + es[:60])
|
|
394
|
+
continue
|
|
395
|
+
if ro == "order":
|
|
396
|
+
choices.append(("omit", [("1", "order left out")]))
|
|
397
|
+
approx.append("order left out: " + es[:60])
|
|
398
|
+
continue
|
|
399
|
+
fails.append(f"{ROLE_OF[ro]} from {'a call' if mcall else 'a field' if mfield else 'a name' if mname else 'an expression'}: {es[:60]}")
|
|
400
|
+
choices.append(("fail", [("NULL", "")]))
|
|
401
|
+
if fails:
|
|
402
|
+
return [], fails
|
|
403
|
+
|
|
404
|
+
def render(pick: dict, jpick: dict) -> tuple[str, list[str]]:
|
|
405
|
+
out: list[str] = []
|
|
406
|
+
last = 0
|
|
407
|
+
cond: list[str] = []
|
|
408
|
+
for i, ((a, b, e), (k, opts)) in enumerate(zip(holes, choices)):
|
|
409
|
+
out.append(sql[last:a])
|
|
410
|
+
last = b
|
|
411
|
+
if k == "joint":
|
|
412
|
+
base, f = opts
|
|
413
|
+
v = joint[base][jpick.get(base, 0)][f]
|
|
414
|
+
out.append(v)
|
|
415
|
+
if len(joint[base]) > 1:
|
|
416
|
+
cond.append(f"{base}.{f} = {v}")
|
|
417
|
+
continue
|
|
418
|
+
t, note = opts[pick.get(i, 0)]
|
|
419
|
+
if t == BIND:
|
|
420
|
+
if k == "bindq" and out[-1].endswith("'") and sql[b:b + 1] == "'":
|
|
421
|
+
out[-1] = out[-1][:-1]
|
|
422
|
+
last = b + 1
|
|
423
|
+
t = "?"
|
|
424
|
+
elif k == "bindq":
|
|
425
|
+
t = "x"
|
|
426
|
+
else:
|
|
427
|
+
t = "?"
|
|
428
|
+
out.append(t)
|
|
429
|
+
if k in ("cand", "opt") and len(opts) > 1:
|
|
430
|
+
cond.append(f"{e.strip()[:40]} = {t.strip()[:40]}" if k == "cand" else note)
|
|
431
|
+
out.append(sql[last:])
|
|
432
|
+
return "".join(out), list(dict.fromkeys(cond))
|
|
433
|
+
|
|
434
|
+
rendered = [render({}, {})]
|
|
435
|
+
for i, (k, opts) in enumerate(choices):
|
|
436
|
+
if k in ("cand", "opt"):
|
|
437
|
+
for j in range(1, len(opts)):
|
|
438
|
+
rendered.append(render({i: j}, {}))
|
|
439
|
+
for bname, groups in joint.items():
|
|
440
|
+
for j in range(1, len(groups)):
|
|
441
|
+
rendered.append(render({}, {bname: j}))
|
|
442
|
+
basis = "part_left_out" if approx else "filled"
|
|
443
|
+
out: list[dict] = []
|
|
444
|
+
seen: set[str] = set()
|
|
445
|
+
for text_, cond in rendered[: int(cfg["max_variants"])]:
|
|
446
|
+
v = model.variant(text_, basis, condition=", ".join(cond) or "base choice", source="holes", notes=approx)
|
|
447
|
+
if v["id"] in seen:
|
|
448
|
+
continue
|
|
449
|
+
seen.add(v["id"])
|
|
450
|
+
out.append(v)
|
|
451
|
+
return out, []
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
# The image an isolated builder run uses for Go: the Go toolchain and strace (every side effect is traced).
|
|
2
|
+
# Built once by `codecop families image go`; it never holds repository code.
|
|
3
|
+
FROM docker.io/library/golang:1.24-alpine
|
|
4
|
+
RUN apk add --no-cache strace
|
|
5
|
+
LABEL codecop=1 codecop.role=isolated
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""The isolation contract for running builder code: a pure slice or an agent-written driver.
|
|
2
|
+
|
|
3
|
+
- a container (the sandbox runtime CodeCop already uses: engines/base.find_runtime), labelled `codecop=1`,
|
|
4
|
+
`codecop.role=sandbox` and `codecop.isolated=1` (the hosted runner's Docker filter forces no network for it), removed after the run;
|
|
5
|
+
- no network (`--network none`; the hosted runner's Docker filter forces `none` for this role);
|
|
6
|
+
- the repository is never mounted: the only input is the copied program (the slice or the driver), handed in as
|
|
7
|
+
environment chunks of a gzip'd tar, so no host path is mounted at all (the hosted runner's filter refuses host paths);
|
|
8
|
+
- env files are never present: the input is built from an explicit file list that refuses any `.env*` / `envs/` path;
|
|
9
|
+
- read-only root file system, no capabilities, no new privileges, pid/CPU/memory caps; the working directory is a
|
|
10
|
+
scratch tmpfs `/work`, and every tool's cache and temp directory points inside it;
|
|
11
|
+
- every side effect is logged: the run is traced with strace (`%network`, `%file`, `%process`), and the trace is
|
|
12
|
+
reduced to an audit record: network calls, writes outside the scratch directory, programs started. A run whose audit
|
|
13
|
+
shows a network call or a write outside the scratch directory is refused: its output is not used.
|
|
14
|
+
|
|
15
|
+
Each run appends one line to `families_audit.jsonl` in the out dir.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import base64
|
|
21
|
+
import io
|
|
22
|
+
import json
|
|
23
|
+
import re
|
|
24
|
+
import subprocess
|
|
25
|
+
import tarfile
|
|
26
|
+
import time
|
|
27
|
+
import uuid
|
|
28
|
+
from datetime import datetime, timezone
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
|
|
31
|
+
AUDIT_FILE = "families_audit.jsonl"
|
|
32
|
+
SCRATCH = "/work"
|
|
33
|
+
DEFAULTS = {
|
|
34
|
+
"cpus": "2",
|
|
35
|
+
"memory": "2g",
|
|
36
|
+
"pids": 512,
|
|
37
|
+
"timeout_s": 600,
|
|
38
|
+
"scratch_size": "2g",
|
|
39
|
+
"env_chunk": 100_000, # bytes of base64 per environment variable (the kernel's limit per string is 128 KiB)
|
|
40
|
+
"max_input_bytes": 8_000_000,
|
|
41
|
+
"max_output_bytes": 32_000_000,
|
|
42
|
+
"images": {"go": "codecop-isolated-go:1", "python": "codecop-isolated-python:1"},
|
|
43
|
+
}
|
|
44
|
+
ENV_FILE = re.compile(r"(^|/)\.env|(^|/)envs?/|\.pem$|\.key$|(^|/)\.git/")
|
|
45
|
+
# what may be written without counting as a side effect outside the scratch directory
|
|
46
|
+
WRITE_OK = re.compile(r"^(/work(/|$)|/dev/(null|stdout|stderr|tty|pts/)|pipe:|socket:|/proc/self/)")
|
|
47
|
+
WRITE_FLAGS = re.compile(r"O_WRONLY|O_RDWR|O_CREAT|O_TRUNC|O_APPEND")
|
|
48
|
+
NET_CALLS = ("connect", "sendto", "sendmsg", "bind", "listen", "accept", "accept4")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class IsolationError(RuntimeError):
|
|
52
|
+
pass
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def pack(files: dict[str, bytes | str]) -> bytes:
|
|
56
|
+
"""A gzip'd tar of the program's files. Refuses env files and paths that leave the directory."""
|
|
57
|
+
buf = io.BytesIO()
|
|
58
|
+
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
|
|
59
|
+
for name, data in sorted(files.items()):
|
|
60
|
+
if name.startswith("/") or ".." in Path(name).parts or ENV_FILE.search(name):
|
|
61
|
+
raise IsolationError(f"refused input path {name!r}")
|
|
62
|
+
raw = data.encode() if isinstance(data, str) else data
|
|
63
|
+
info = tarfile.TarInfo(name)
|
|
64
|
+
info.size = len(raw)
|
|
65
|
+
info.mtime = 0
|
|
66
|
+
info.mode = 0o644
|
|
67
|
+
tar.addfile(info, io.BytesIO(raw))
|
|
68
|
+
return buf.getvalue()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def parse_trace(text: str) -> dict:
|
|
72
|
+
"""The audit record of an strace -f log: network calls, writes outside the scratch directory, programs run."""
|
|
73
|
+
net, writes, tried, execs, files_read = [], [], [], [], 0
|
|
74
|
+
for line in text.splitlines():
|
|
75
|
+
m = re.match(r"^(?:\[pid\s+\d+\]\s+|\d+\s+)?(\w+)\((.*)$", line.strip())
|
|
76
|
+
if not m:
|
|
77
|
+
continue
|
|
78
|
+
call, rest = m.group(1), m.group(2)
|
|
79
|
+
if call in NET_CALLS or (call == "socket" and not re.search(r"AF_UNIX|AF_LOCAL", rest)):
|
|
80
|
+
if call == "socket" and "= -1" in rest:
|
|
81
|
+
net.append(line[:200])
|
|
82
|
+
elif call != "socket" or "= -1" not in rest:
|
|
83
|
+
net.append(line[:200])
|
|
84
|
+
elif call in ("openat", "open", "creat"):
|
|
85
|
+
pm = re.search(r'"([^"]*)"', rest)
|
|
86
|
+
path = pm.group(1) if pm else ""
|
|
87
|
+
if call == "creat" or WRITE_FLAGS.search(rest):
|
|
88
|
+
if not WRITE_OK.match(path) and path.startswith("/"):
|
|
89
|
+
(writes if "= -1" not in rest else tried).append(line[:200])
|
|
90
|
+
else:
|
|
91
|
+
files_read += 1
|
|
92
|
+
elif call in ("mkdir", "mkdirat", "unlink", "unlinkat", "rename", "renameat", "renameat2", "rmdir", "symlink",
|
|
93
|
+
"symlinkat", "link", "linkat", "chmod", "fchmodat", "truncate"):
|
|
94
|
+
paths = re.findall(r'"([^"]*)"', rest)
|
|
95
|
+
if any(p.startswith("/") and not WRITE_OK.match(p) for p in paths):
|
|
96
|
+
(writes if "= -1" not in rest else tried).append(line[:200])
|
|
97
|
+
elif call == "execve":
|
|
98
|
+
pm = re.search(r'"([^"]*)"', rest)
|
|
99
|
+
if pm and "= -1" not in rest:
|
|
100
|
+
execs.append(pm.group(1))
|
|
101
|
+
return {"network_calls": len(net), "network_examples": net[:5], "writes_outside_scratch": len(writes),
|
|
102
|
+
"write_examples": writes[:5], "write_attempts_outside_scratch": len(tried), "write_attempt_examples": tried[:5], "programs": sorted(set(execs))[:40], "files_opened_for_read": files_read}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def run(files: dict[str, bytes | str], script: str, *, image: str, out_dir: Path | None, purpose: str, ref: str = "",
|
|
106
|
+
settings: dict | None = None, env: dict | None = None, runtime: str | None = None) -> dict:
|
|
107
|
+
"""Run `script` (sh) in /work/in with the files there, isolated and traced. Returns {exit, stdout, stderr, audit,
|
|
108
|
+
accepted, seconds}. `accepted` is False when the audit found a network call or a write outside the scratch
|
|
109
|
+
directory, or when the trace could not be read: the output is then not to be used."""
|
|
110
|
+
from ..engines.base import find_runtime
|
|
111
|
+
cfg = {**DEFAULTS, **(settings or {})}
|
|
112
|
+
rt = runtime or find_runtime()
|
|
113
|
+
blob = pack(files)
|
|
114
|
+
if len(blob) > int(cfg["max_input_bytes"]):
|
|
115
|
+
raise IsolationError(f"input of {len(blob)} bytes is over the max_input_bytes setting")
|
|
116
|
+
b64 = base64.b64encode(blob).decode()
|
|
117
|
+
n = int(cfg["env_chunk"])
|
|
118
|
+
chunks = [b64[i:i + n] for i in range(0, len(b64), n)] or [""]
|
|
119
|
+
name = f"codecop-iso-{uuid.uuid4().hex[:10]}"
|
|
120
|
+
inner_env = {"HOME": SCRATCH, "TMPDIR": f"{SCRATCH}/tmp", "GOCACHE": f"{SCRATCH}/.gocache", "GOTMPDIR": f"{SCRATCH}/tmp",
|
|
121
|
+
"GOPATH": f"{SCRATCH}/.gopath", "GOFLAGS": "-mod=mod", "GOPROXY": "off", "GOTOOLCHAIN": "local",
|
|
122
|
+
"GOTELEMETRY": "off", "CGO_ENABLED": "0", "PYTHONDONTWRITEBYTECODE": "1", **(env or {})}
|
|
123
|
+
unpack = ("set -e; mkdir -p /work/in /work/tmp /work/.audit; "
|
|
124
|
+
+ "printf '%s' " + " ".join(f'"$CODECOP_IN_{i}"' for i in range(len(chunks)))
|
|
125
|
+
+ " | base64 -d | tar -xz -C /work/in; "
|
|
126
|
+
+ " ".join(f"unset CODECOP_IN_{i};" for i in range(len(chunks))) + " cd /work/in; ")
|
|
127
|
+
traced = ("set +e; if command -v strace >/dev/null 2>&1; then "
|
|
128
|
+
"strace -f -qq -s 200 -e trace=%network,%file,%process -o /work/.audit/trace sh -c \"$CODECOP_SCRIPT\"; rc=$?; "
|
|
129
|
+
"else echo CODECOP_NO_TRACE >&2; sh -c \"$CODECOP_SCRIPT\"; rc=$?; fi; "
|
|
130
|
+
"echo; echo '@@CODECOP_TRACE@@'; cat /work/.audit/trace 2>/dev/null | tail -c 20000000; exit $rc")
|
|
131
|
+
# detached, then wait and logs: the calls the hosted runner's Docker filter allows (it has no attach route)
|
|
132
|
+
args = [rt, "run", "-d", "--name", name, "--network", "none", "--read-only", "--cap-drop", "ALL",
|
|
133
|
+
"--security-opt", "no-new-privileges", "--pids-limit", str(cfg["pids"]), "--cpus", str(cfg["cpus"]),
|
|
134
|
+
"--memory", str(cfg["memory"]), "--tmpfs", f"{SCRATCH}:rw,exec,nosuid,nodev,size={cfg['scratch_size']}",
|
|
135
|
+
"--tmpfs", "/tmp:rw,noexec,nosuid,nodev,size=16m", "-w", SCRATCH,
|
|
136
|
+
"--label", "codecop=1", "--label", "codecop.role=sandbox", "--label", "codecop.isolated=1", "--label", f"codecop.purpose={purpose}"]
|
|
137
|
+
for k, v in inner_env.items():
|
|
138
|
+
args += ["-e", f"{k}={v}"]
|
|
139
|
+
for i, c in enumerate(chunks):
|
|
140
|
+
args += ["-e", f"CODECOP_IN_{i}={c}"]
|
|
141
|
+
args += ["-e", f"CODECOP_SCRIPT={script}", image, "sh", "-c", unpack + traced]
|
|
142
|
+
began = time.monotonic()
|
|
143
|
+
try:
|
|
144
|
+
started = subprocess.run(args, capture_output=True, timeout=120)
|
|
145
|
+
if started.returncode != 0:
|
|
146
|
+
rc, out, err = started.returncode, b"", started.stderr
|
|
147
|
+
else:
|
|
148
|
+
waited = subprocess.run([rt, "wait", name], capture_output=True, timeout=int(cfg["timeout_s"]))
|
|
149
|
+
rc = int((waited.stdout or b"1").split()[-1]) if waited.returncode == 0 else 125
|
|
150
|
+
logs = subprocess.run([rt, "logs", name], capture_output=True, timeout=300)
|
|
151
|
+
out, err = logs.stdout, logs.stderr
|
|
152
|
+
except subprocess.TimeoutExpired:
|
|
153
|
+
rc, out, err = 124, b"", b"timeout"
|
|
154
|
+
finally:
|
|
155
|
+
subprocess.run([rt, "rm", "-f", name], capture_output=True, timeout=120)
|
|
156
|
+
seconds = round(time.monotonic() - began, 1)
|
|
157
|
+
out = out[: int(cfg["max_output_bytes"])].decode("utf-8", "replace")
|
|
158
|
+
err = err.decode("utf-8", "replace")
|
|
159
|
+
stdout, _, trace = out.rpartition("\n@@CODECOP_TRACE@@\n") if "@@CODECOP_TRACE@@" in out else (out, "", "")
|
|
160
|
+
traced_ok = "CODECOP_NO_TRACE" not in err and bool(trace.strip())
|
|
161
|
+
audit = parse_trace(trace) if traced_ok else {"network_calls": None, "writes_outside_scratch": None}
|
|
162
|
+
record = {"at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "purpose": purpose, "ref": ref, "image": image,
|
|
163
|
+
"container": name, "network": "none", "repository_mounted": False, "mounts": [], "read_only_root": True,
|
|
164
|
+
"input_files": sorted(files), "input_bytes": len(blob), "scratch": SCRATCH, "exit": rc, "seconds": seconds,
|
|
165
|
+
"traced": traced_ok, **audit}
|
|
166
|
+
record["accepted"] = traced_ok and audit["network_calls"] == 0 and audit["writes_outside_scratch"] == 0 \
|
|
167
|
+
and audit.get("write_attempts_outside_scratch") == 0
|
|
168
|
+
if out_dir is not None:
|
|
169
|
+
with open(Path(out_dir) / AUDIT_FILE, "a") as fh:
|
|
170
|
+
fh.write(json.dumps(record) + "\n")
|
|
171
|
+
return {"exit": rc, "stdout": stdout, "stderr": err[-4000:], "audit": record, "accepted": record["accepted"], "seconds": seconds}
|