@handfly/sandbox 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,226 @@
1
+ """Handfly prediction harness: import a module by path, call one function with literal inputs, print a canonical result.
2
+
3
+ Usage: python harness.py <module_path> <qualified_function> <args_python_literal> [--trace | --count] [--scale N]
4
+ Prints one line: OK:<json> or RAISES:<ExceptionType>. Never touches the network (none exists here).
5
+ With --trace it prints TRACE:<json> instead: a checkpoint inside the call (line, hit number, variable, value) chosen
6
+ deterministically, for "state at checkpoint" items.
7
+ With --count it prints COUNT:<json>: how many times each line of the target function ran (cost-scale items).
8
+ """
9
+
10
+ import ast
11
+ import importlib.util
12
+ import json
13
+ import os
14
+ import sys
15
+ from decimal import Decimal
16
+
17
+
18
+ def _eval_args(src: str):
19
+ tree = ast.parse(src, mode="eval")
20
+ allowed = (
21
+ ast.Expression,
22
+ ast.Tuple,
23
+ ast.List,
24
+ ast.Dict,
25
+ ast.Set,
26
+ ast.Constant,
27
+ ast.UnaryOp,
28
+ ast.USub,
29
+ ast.UAdd,
30
+ ast.Call,
31
+ ast.Name,
32
+ ast.Load,
33
+ ast.keyword,
34
+ )
35
+ for node in ast.walk(tree):
36
+ if not isinstance(node, allowed):
37
+ raise ValueError(f"unsupported input syntax: {type(node).__name__}")
38
+ if isinstance(node, ast.Call) and not (isinstance(node.func, ast.Name) and node.func.id == "Decimal"):
39
+ raise ValueError("only Decimal(...) calls are allowed in inputs")
40
+ if isinstance(node, ast.Name) and node.id not in ("Decimal", "True", "False", "None"):
41
+ raise ValueError(f"unknown name {node.id}")
42
+ return eval(compile(tree, "<args>", "eval"), {"__builtins__": {}, "Decimal": Decimal}) # noqa: S307 - AST-whitelisted
43
+
44
+
45
+ def _canon(v):
46
+ if isinstance(v, Decimal):
47
+ return {"__decimal__": format(v, "f")}
48
+ if isinstance(v, float):
49
+ return {"__float__": repr(v)}
50
+ if isinstance(v, (list, tuple)):
51
+ return [_canon(x) for x in v]
52
+ if isinstance(v, dict):
53
+ return {str(k): _canon(x) for k, x in sorted(v.items(), key=lambda kv: str(kv[0]))}
54
+ if isinstance(v, (str, int, bool)) or v is None:
55
+ return v
56
+ return {"__repr__": repr(v)[:200]}
57
+
58
+
59
+ def _dotted(base: str, path: str) -> str | None:
60
+ """`pkg/sub/mod.py` → `pkg.sub.mod` when every directory on the way is a package."""
61
+ rel = os.path.relpath(path, base)
62
+ if rel.startswith(".."):
63
+ return None
64
+ parts = rel[:-3].split(os.sep) if rel.endswith(".py") else None
65
+ if not parts:
66
+ return None
67
+ if parts[-1] == "__init__":
68
+ parts = parts[:-1]
69
+ for i in range(1, len(parts)):
70
+ if not os.path.exists(os.path.join(base, *parts[:i], "__init__.py")):
71
+ return None
72
+ return ".".join(parts) or None
73
+
74
+
75
+ def _load(root: str, path: str):
76
+ """Import the target under its real package name (relative imports work); src/ layouts are supported."""
77
+ full = os.path.join(root, path)
78
+ bases = [b for b in (os.path.join(root, "src"), root) if os.path.isdir(b)]
79
+ for b in reversed(bases):
80
+ sys.path.insert(0, b)
81
+ for b in bases:
82
+ name = _dotted(b, full)
83
+ if name:
84
+ try:
85
+ return importlib.import_module(name)
86
+ except ImportError:
87
+ continue
88
+ spec = importlib.util.spec_from_file_location("handfly_target", full)
89
+ mod = importlib.util.module_from_spec(spec)
90
+ spec.loader.exec_module(mod)
91
+ return mod
92
+
93
+
94
+ def main() -> None:
95
+ path, qual, args_src = sys.argv[1], sys.argv[2], sys.argv[3]
96
+ mod = _load(os.getcwd(), path)
97
+ fn = mod
98
+ for part in qual.split("."):
99
+ fn = getattr(fn, part)
100
+ args = _eval_args(args_src)
101
+ if not isinstance(args, tuple):
102
+ args = (args,)
103
+ if "--trace" in sys.argv:
104
+ print("TRACE:" + json.dumps(_trace(fn, args), sort_keys=True))
105
+ return
106
+ if "--scale" in sys.argv:
107
+ n = int(sys.argv[sys.argv.index("--scale") + 1])
108
+ args = tuple(_scaled(a, n) for a in args)
109
+ if "--count" in sys.argv:
110
+ print("COUNT:" + json.dumps(_count(fn, args), sort_keys=True))
111
+ return
112
+ try:
113
+ out = fn(*args)
114
+ except Exception as e: # noqa: BLE001
115
+ print(f"RAISES:{type(e).__name__}")
116
+ return
117
+ print("OK:" + json.dumps(_canon(out), sort_keys=True))
118
+
119
+
120
+ def _trace(fn, args):
121
+ """Record the target function's locals at every line event, then pick a checkpoint: the line executed most often
122
+ (at least twice), its 2nd hit, and the first variable (by name) whose value changed since the 1st hit. The value is
123
+ what the variable holds when that line is about to run. Returns null when nothing qualifies."""
124
+ code = getattr(fn, "__code__", None)
125
+ hits: dict[int, list[dict]] = {}
126
+ order: list[tuple[int, int, dict]] = []
127
+
128
+ def tracer(frame, event, arg):
129
+ if frame.f_code is not code:
130
+ return None
131
+ if event == "line":
132
+ snap = {}
133
+ for k, v in frame.f_locals.items():
134
+ if k.startswith("__"):
135
+ continue
136
+ try:
137
+ c = _canon(v)
138
+ text = json.dumps(c, sort_keys=True)
139
+ except Exception: # noqa: BLE001, S112
140
+ continue
141
+ if len(text) <= 120:
142
+ snap[k] = c
143
+ hits.setdefault(frame.f_lineno, []).append(snap)
144
+ order.append((frame.f_lineno, len(hits[frame.f_lineno]), snap))
145
+ return tracer
146
+
147
+ if code is None:
148
+ return None
149
+ sys.settrace(tracer)
150
+ try:
151
+ fn(*args)
152
+ except Exception: # noqa: BLE001, S110
153
+ pass
154
+ finally:
155
+ sys.settrace(None)
156
+
157
+ def counter(a, b): # a loop index stepping by one is too easy to be worth asking about
158
+ return isinstance(a, int) and isinstance(b, int) and not isinstance(a, bool) and b - a == 1
159
+
160
+ fallback = None
161
+ for line, snaps in sorted(hits.items(), key=lambda kv: (-len(kv[1]), kv[0])):
162
+ if len(snaps) < 2:
163
+ break
164
+ for k in range(1, min(3, len(snaps))): # 2nd, then 3rd hit
165
+ prev, cur = snaps[k - 1], snaps[k]
166
+ for var in sorted(cur):
167
+ if var in prev and prev[var] != cur[var]:
168
+ found = {"line": line, "hit": k + 1, "var": var, "value": cur[var], "hits": len(snaps)}
169
+ if not counter(prev[var], cur[var]):
170
+ return found
171
+ fallback = fallback or found
172
+ if fallback:
173
+ return fallback
174
+ # No loops: the last line reached where a variable computed during the call exists (not an argument).
175
+ first = order[0][2] if order else {}
176
+ for line, hit, snap in reversed(order):
177
+ computed = sorted(v for v in snap if v not in first)
178
+ if computed:
179
+ var = computed[0]
180
+ return {"line": line, "hit": hit, "var": var, "value": snap[var], "hits": len(hits[line])}
181
+ return None
182
+
183
+
184
+ def _scaled(value, n: int):
185
+ """A list input stretched (or cut) to n elements by repeating it: the same shape of data, at size n."""
186
+ if isinstance(value, list) and value:
187
+ return [value[i % len(value)] for i in range(n)]
188
+ return value
189
+
190
+
191
+ def _count(fn, args):
192
+ """Line executions inside the target function's lines: its own frames (so recursion counts) and the code nested
193
+ in it (generator expressions, lambdas, inner functions), which run in frames of their own."""
194
+ import inspect # noqa: PLC0415
195
+
196
+ code = getattr(fn, "__code__", None)
197
+ if code is None:
198
+ return None
199
+ try:
200
+ first = code.co_firstlineno
201
+ last = first + len(inspect.getsourcelines(fn)[0]) - 1
202
+ except (OSError, TypeError):
203
+ first, last = code.co_firstlineno, code.co_firstlineno
204
+ filename = code.co_filename
205
+ counts: dict[int, int] = {}
206
+
207
+ def tracer(frame, event, arg):
208
+ c = frame.f_code
209
+ if c.co_filename != filename or not first <= c.co_firstlineno <= last:
210
+ return None
211
+ if event == "line" and first <= frame.f_lineno <= last:
212
+ counts[frame.f_lineno] = counts.get(frame.f_lineno, 0) + 1
213
+ return tracer
214
+
215
+ sys.settrace(tracer)
216
+ try:
217
+ fn(*args)
218
+ except Exception: # noqa: BLE001, S110
219
+ pass
220
+ finally:
221
+ sys.settrace(None)
222
+ return {str(k): v for k, v in sorted(counts.items())}
223
+
224
+
225
+ if __name__ == "__main__":
226
+ main()
@@ -0,0 +1,173 @@
1
+ """Handfly query capture (pytest plugin, loaded with `-p hf_queries`).
2
+
3
+ Counts the SQL each Django test-client request executes, from the moment the handler gets the request until it
4
+ returns the response. Savepoint statements are left out (they come from test transactions, not from the code).
5
+ For each request it records where it was made (test file and line), which view served it, and the shape of each
6
+ query: verb and first table only. Never the SQL text or its parameters, which can hold test literals.
7
+
8
+ At the end of the session it prints one line: `QUERIES:<json>` with the records of passing tests only.
9
+ """
10
+
11
+ import inspect
12
+ import json
13
+ import os
14
+ import re
15
+ import sys
16
+ from contextlib import ExitStack
17
+
18
+ _records: dict[str, list[dict]] = {}
19
+ _passed: set[str] = set()
20
+ _tests: dict[str, dict] = {}
21
+ _current: str | None = None
22
+ _SAVEPOINT = re.compile(r"^\s*(SAVEPOINT|RELEASE SAVEPOINT|ROLLBACK TO SAVEPOINT)\b", re.I)
23
+ _SHAPE = (
24
+ ("select", re.compile(r"^\s*SELECT\b.*?\bFROM\s+[\"`\[]?(\w+)", re.I | re.S)),
25
+ ("insert", re.compile(r"^\s*INSERT\s+INTO\s+[\"`\[]?(\w+)", re.I)),
26
+ ("update", re.compile(r"^\s*UPDATE\s+[\"`\[]?(\w+)", re.I)),
27
+ ("delete", re.compile(r"^\s*DELETE\s+FROM\s+[\"`\[]?(\w+)", re.I)),
28
+ )
29
+
30
+
31
+ def _shape(sql: str) -> dict:
32
+ for verb, rx in _SHAPE:
33
+ m = rx.match(sql)
34
+ if m:
35
+ return {"verb": verb, "table": m.group(1)}
36
+ return {"verb": sql.lstrip().split(" ", 1)[0].lower()[:12], "table": ""}
37
+
38
+
39
+ def _in_repo(path: str | None) -> str | None:
40
+ if not path:
41
+ return None
42
+ rel = os.path.relpath(os.path.abspath(path), os.getcwd())
43
+ return None if rel.startswith("..") or "site-packages" in rel else rel
44
+
45
+
46
+ def _span(obj) -> dict | None:
47
+ try:
48
+ path = _in_repo(inspect.getsourcefile(obj))
49
+ lines, start = inspect.getsourcelines(obj)
50
+ except (OSError, TypeError):
51
+ return None
52
+ return {"path": path, "start": start, "end": start + len(lines) - 1} if path else None
53
+
54
+
55
+ def _route(pattern: str) -> str:
56
+ """Readable route pattern: `api/^orders/(?P<pk>[^/.]+)/quote/$` -> `/api/orders/<pk>/quote/`."""
57
+ r = re.sub(r"\(\?P<(\w+)>[^)]*\)", r"<\1>", pattern).replace("^", "").replace("$", "")
58
+ r = re.sub(r"\\\.?", "", r) if "\\" in r else r
59
+ return "/" + r.lstrip("/")
60
+
61
+
62
+ def _serializer(cls) -> dict | None:
63
+ """DRF: the view's serializer class plus the nested serializers it declares in the same file, as one span.
64
+ Nested serializers are where per-row queries usually hide (a related field resolved once per item)."""
65
+ ser = getattr(cls, "serializer_class", None) if cls is not None else None
66
+ main = _span(ser) if isinstance(ser, type) else None
67
+ if not main:
68
+ return None
69
+ spans = [main]
70
+ for field in (getattr(ser, "_declared_fields", None) or {}).values():
71
+ child = getattr(field, "child", field)
72
+ if getattr(child, "_declared_fields", None) is not None:
73
+ sp = _span(type(child))
74
+ if sp and sp["path"] == main["path"]:
75
+ spans.append(sp)
76
+ return {"path": main["path"], "start": min(x["start"] for x in spans), "end": max(x["end"] for x in spans)}
77
+
78
+
79
+ def _view(request) -> dict | None:
80
+ match = getattr(request, "resolver_match", None)
81
+ if match is None:
82
+ return None
83
+ func = match.func
84
+ cls = getattr(func, "cls", None) or getattr(func, "view_class", None)
85
+ actions = getattr(func, "actions", None) or {}
86
+ action = actions.get(request.method.lower())
87
+ target = cls if cls is not None else func
88
+ span = _span(target)
89
+ return {
90
+ "route": _route(match.route) if match.route else None,
91
+ "name": getattr(target, "__qualname__", getattr(target, "__name__", "")),
92
+ "action": action,
93
+ "span": span,
94
+ "serializer": _serializer(cls),
95
+ }
96
+
97
+
98
+ def _caller_line(test_path: str | None) -> int | None:
99
+ if not test_path:
100
+ return None
101
+ for frame in inspect.stack(context=0):
102
+ if _in_repo(frame.filename) == test_path:
103
+ return frame.lineno
104
+ return None
105
+
106
+
107
+ def _install() -> None:
108
+ try:
109
+ from django.core.handlers.base import BaseHandler
110
+ except ImportError:
111
+ return
112
+ original = BaseHandler.get_response
113
+
114
+ def get_response(self, request):
115
+ from django.db import connections
116
+
117
+ if _current is None:
118
+ return original(self, request)
119
+ shapes: list[dict] = []
120
+
121
+ def count(execute, sql, params, many, context):
122
+ if not _SAVEPOINT.match(sql):
123
+ shapes.append(_shape(sql))
124
+ return execute(sql, params, many, context)
125
+
126
+ with ExitStack() as stack:
127
+ for conn in connections.all():
128
+ stack.enter_context(conn.execute_wrapper(count))
129
+ response = original(self, request)
130
+ test = _tests.get(_current) or {}
131
+ _records.setdefault(_current, []).append(
132
+ {
133
+ "method": request.method,
134
+ "status": getattr(response, "status_code", None),
135
+ "line": _caller_line(test.get("path")),
136
+ "view": _view(request),
137
+ "count": len(shapes),
138
+ "shapes": shapes,
139
+ }
140
+ )
141
+ return response
142
+
143
+ BaseHandler.get_response = get_response
144
+
145
+
146
+ def pytest_configure(config):
147
+ _install()
148
+
149
+
150
+ def pytest_runtest_setup(item):
151
+ global _current
152
+ _current = item.nodeid
153
+ fn = getattr(item, "function", None)
154
+ span = _span(fn) if fn is not None else None
155
+ _tests[item.nodeid] = {"path": span["path"] if span else None, "span": span, "name": item.name}
156
+
157
+
158
+ def pytest_runtest_teardown(item):
159
+ global _current
160
+ _current = None
161
+
162
+
163
+ def pytest_runtest_logreport(report):
164
+ if report.when == "call" and report.passed:
165
+ _passed.add(report.nodeid)
166
+
167
+
168
+ def pytest_unconfigure(config):
169
+ out = {
170
+ nid: {"test": _tests.get(nid), "requests": reqs} for nid, reqs in _records.items() if nid in _passed and reqs
171
+ }
172
+ sys.__stdout__.write("QUERIES:" + json.dumps(out, sort_keys=True) + "\n")
173
+ sys.__stdout__.flush()
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "@handfly/sandbox",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Run untrusted repo code without network: Docker (+gVisor when available), read-only, resource-limited.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "images"
18
+ ],
19
+ "dependencies": {
20
+ "@handfly/indexer": "0.1.0",
21
+ "@handfly/protocol": "0.1.0",
22
+ "@handfly/itemgen": "0.1.0"
23
+ },
24
+ "homepage": "https://handfly.dev",
25
+ "scripts": {
26
+ "build": "tsc -p tsconfig.json && node scripts/copy-images.mjs",
27
+ "typecheck": "tsc -p tsconfig.json --noEmit",
28
+ "test": "vitest run"
29
+ }
6
30
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.