vlambda 0.2.1__tar.gz → 0.2.3__tar.gz
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.
- {vlambda-0.2.1 → vlambda-0.2.3}/PKG-INFO +17 -15
- {vlambda-0.2.1 → vlambda-0.2.3}/README.md +16 -14
- {vlambda-0.2.1 → vlambda-0.2.3}/pyproject.toml +1 -1
- {vlambda-0.2.1 → vlambda-0.2.3}/python/vlambda/__main__.py +29 -10
- {vlambda-0.2.1 → vlambda-0.2.3}/python/vlambda/auth.py +7 -1
- {vlambda-0.2.1 → vlambda-0.2.3}/python/vlambda/pool.py +131 -2
- {vlambda-0.2.1 → vlambda-0.2.3}/python/vlambda/runner.py +36 -0
- vlambda-0.2.3/python/vlambda/sandbox_os.py +294 -0
- {vlambda-0.2.1 → vlambda-0.2.3}/src/vlambda_native.v +4 -2
- {vlambda-0.2.1 → vlambda-0.2.3}/tests/test_unit.py +9 -1
- {vlambda-0.2.1 → vlambda-0.2.3}/tests/test_vlambda.py +70 -1
- {vlambda-0.2.1 → vlambda-0.2.3}/vcraft.toml +1 -1
- {vlambda-0.2.1 → vlambda-0.2.3}/LICENSE +0 -0
- {vlambda-0.2.1 → vlambda-0.2.3}/python/vlambda/__init__.py +0 -0
- {vlambda-0.2.1 → vlambda-0.2.3}/python/vlambda/assets.py +0 -0
- {vlambda-0.2.1 → vlambda-0.2.3}/python/vlambda/cache.py +0 -0
- {vlambda-0.2.1 → vlambda-0.2.3}/python/vlambda/dbpool.py +0 -0
- {vlambda-0.2.1 → vlambda-0.2.3}/python/vlambda/metrics.py +0 -0
- {vlambda-0.2.1 → vlambda-0.2.3}/python/vlambda/packages.py +0 -0
- {vlambda-0.2.1 → vlambda-0.2.3}/python/vlambda/project.py +0 -0
- {vlambda-0.2.1 → vlambda-0.2.3}/python/vlambda/py.typed +0 -0
- {vlambda-0.2.1 → vlambda-0.2.3}/python/vlambda/request.py +0 -0
- {vlambda-0.2.1 → vlambda-0.2.3}/python/vlambda/reset.py +0 -0
- {vlambda-0.2.1 → vlambda-0.2.3}/python/vlambda/sandbox.py +0 -0
- {vlambda-0.2.1 → vlambda-0.2.3}/python/vlambda/shared_cache.py +0 -0
- {vlambda-0.2.1 → vlambda-0.2.3}/python/vlambda/tasks.py +0 -0
- {vlambda-0.2.1 → vlambda-0.2.3}/python/vlambda/transfer.py +0 -0
- {vlambda-0.2.1 → vlambda-0.2.3}/tests/conftest.py +0 -0
- {vlambda-0.2.1 → vlambda-0.2.3}/v.mod +0 -0
- {vlambda-0.2.1 → vlambda-0.2.3}/vcraft_build.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: vlambda
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.3
|
|
4
4
|
Summary: An ASGI-like server for Python lambdas, written in V.
|
|
5
5
|
License: MIT
|
|
6
6
|
Requires-Python: >=3.14
|
|
@@ -28,12 +28,12 @@ POST that code to `/vlambda` and it becomes `GET /f/<slug>` instantly.
|
|
|
28
28
|
|
|
29
29
|
## Features
|
|
30
30
|
|
|
31
|
-
- **No cold starts** —
|
|
31
|
+
- **No cold starts in persistent mode** — Docker uses a fresh Landlock process per invocation, which adds a small startup cost
|
|
32
32
|
- **Fast** — ~3,000 req/s (concurrent, free-threaded Python), ~0.3ms/req
|
|
33
33
|
- **Auth** — JWT-based authentication with per-user ownership
|
|
34
34
|
- **Web UI** — Dashboard for managing lambdas, code editor, metrics
|
|
35
35
|
- **Async invocation** — Fire-and-forget with task tracking
|
|
36
|
-
- **Sandbox** —
|
|
36
|
+
- **Sandbox** — Landlock + seccomp in Docker, plus restricted Python builtins and blocked modules
|
|
37
37
|
- **Metrics** — Prometheus-compatible + Chart.js dashboard
|
|
38
38
|
- **Per-lambda method** — GET, POST, PUT, PATCH, DELETE
|
|
39
39
|
- **Naming** — Human-readable names for lambdas
|
|
@@ -103,13 +103,12 @@ token with `DELETE /tokens/<id>`. Tokens do not expire.
|
|
|
103
103
|
|
|
104
104
|
The repository includes a production image (`Dockerfile`, installs from PyPI) and
|
|
105
105
|
a development image (`Dockerfile.dev`, builds the local wheel). Both use a
|
|
106
|
-
free-threaded Python 3.14 venv, run each invocation in
|
|
107
|
-
HTTP on port `8080`; Dokploy (or another proxy) handles
|
|
108
|
-
domain.
|
|
106
|
+
free-threaded Python 3.14 venv, run each invocation in a Landlock + seccomp
|
|
107
|
+
sandbox and expose plain HTTP on port `8080`; Dokploy (or another proxy) handles
|
|
108
|
+
TLS and the public domain.
|
|
109
109
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
the sandbox) or an equivalent custom profile. The compose files already set it.
|
|
110
|
+
The sandbox needs no extra Docker flags, capabilities or host sysctl changes.
|
|
111
|
+
It requires a Linux kernel with Landlock (5.13+; Ubuntu 22.04+, Debian 12+).
|
|
113
112
|
|
|
114
113
|
```bash
|
|
115
114
|
export VLAMBDA_SECRET="$(openssl rand -hex 32)"
|
|
@@ -253,11 +252,12 @@ Safe modules: `json`, `math`, `re`, `datetime`, `collections`, `itertools`, `fun
|
|
|
253
252
|
|
|
254
253
|
### Security
|
|
255
254
|
|
|
256
|
-
User code runs
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
255
|
+
User code runs in a fresh runner process confined with Landlock and seccomp.
|
|
256
|
+
Landlock limits the filesystem to `/opt`, `/usr`, `/lib`, `/etc`, the current
|
|
257
|
+
project/vendor and a private temporary directory; `/data`, `/proc`, `/sys` and
|
|
258
|
+
the rest of the server cannot be read or listed. seccomp blocks network, cross-process
|
|
259
|
+
signals, `ptrace`, `mount`, namespace changes and similar syscalls. Resource
|
|
260
|
+
limits are applied too, and each invocation gets a fresh process.
|
|
261
261
|
|
|
262
262
|
The Docker image keeps public registration open by default for toy deployments.
|
|
263
263
|
Set `VLAMBDA_REGISTRATION=0` to close it and create users with
|
|
@@ -288,6 +288,8 @@ The demo can be wiped with:
|
|
|
288
288
|
python -m vlambda reset --yes --url http://127.0.0.1:8080 --token "$VLAMBDA_ADMIN_TOKEN"
|
|
289
289
|
```
|
|
290
290
|
|
|
291
|
+
A reset also invalidates existing JWT sessions and API tokens.
|
|
292
|
+
|
|
291
293
|
For a disposable demo, run it from cron every day:
|
|
292
294
|
|
|
293
295
|
```cron
|
|
@@ -298,7 +300,7 @@ For a disposable demo, run it from cron every day:
|
|
|
298
300
|
|
|
299
301
|
| Metric | Value |
|
|
300
302
|
|--------|-------|
|
|
301
|
-
| Cold start | 0ms
|
|
303
|
+
| Cold start | 0ms in persistent mode; fresh sandbox process in Docker |
|
|
302
304
|
| Warm invocation | ~0.3ms |
|
|
303
305
|
| Throughput (concurrent, free-threaded) | ~3,000 req/s |
|
|
304
306
|
| Throughput (response cache hits) | ~100x faster |
|
|
@@ -17,12 +17,12 @@ POST that code to `/vlambda` and it becomes `GET /f/<slug>` instantly.
|
|
|
17
17
|
|
|
18
18
|
## Features
|
|
19
19
|
|
|
20
|
-
- **No cold starts** —
|
|
20
|
+
- **No cold starts in persistent mode** — Docker uses a fresh Landlock process per invocation, which adds a small startup cost
|
|
21
21
|
- **Fast** — ~3,000 req/s (concurrent, free-threaded Python), ~0.3ms/req
|
|
22
22
|
- **Auth** — JWT-based authentication with per-user ownership
|
|
23
23
|
- **Web UI** — Dashboard for managing lambdas, code editor, metrics
|
|
24
24
|
- **Async invocation** — Fire-and-forget with task tracking
|
|
25
|
-
- **Sandbox** —
|
|
25
|
+
- **Sandbox** — Landlock + seccomp in Docker, plus restricted Python builtins and blocked modules
|
|
26
26
|
- **Metrics** — Prometheus-compatible + Chart.js dashboard
|
|
27
27
|
- **Per-lambda method** — GET, POST, PUT, PATCH, DELETE
|
|
28
28
|
- **Naming** — Human-readable names for lambdas
|
|
@@ -92,13 +92,12 @@ token with `DELETE /tokens/<id>`. Tokens do not expire.
|
|
|
92
92
|
|
|
93
93
|
The repository includes a production image (`Dockerfile`, installs from PyPI) and
|
|
94
94
|
a development image (`Dockerfile.dev`, builds the local wheel). Both use a
|
|
95
|
-
free-threaded Python 3.14 venv, run each invocation in
|
|
96
|
-
HTTP on port `8080`; Dokploy (or another proxy) handles
|
|
97
|
-
domain.
|
|
95
|
+
free-threaded Python 3.14 venv, run each invocation in a Landlock + seccomp
|
|
96
|
+
sandbox and expose plain HTTP on port `8080`; Dokploy (or another proxy) handles
|
|
97
|
+
TLS and the public domain.
|
|
98
98
|
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
the sandbox) or an equivalent custom profile. The compose files already set it.
|
|
99
|
+
The sandbox needs no extra Docker flags, capabilities or host sysctl changes.
|
|
100
|
+
It requires a Linux kernel with Landlock (5.13+; Ubuntu 22.04+, Debian 12+).
|
|
102
101
|
|
|
103
102
|
```bash
|
|
104
103
|
export VLAMBDA_SECRET="$(openssl rand -hex 32)"
|
|
@@ -242,11 +241,12 @@ Safe modules: `json`, `math`, `re`, `datetime`, `collections`, `itertools`, `fun
|
|
|
242
241
|
|
|
243
242
|
### Security
|
|
244
243
|
|
|
245
|
-
User code runs
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
244
|
+
User code runs in a fresh runner process confined with Landlock and seccomp.
|
|
245
|
+
Landlock limits the filesystem to `/opt`, `/usr`, `/lib`, `/etc`, the current
|
|
246
|
+
project/vendor and a private temporary directory; `/data`, `/proc`, `/sys` and
|
|
247
|
+
the rest of the server cannot be read or listed. seccomp blocks network, cross-process
|
|
248
|
+
signals, `ptrace`, `mount`, namespace changes and similar syscalls. Resource
|
|
249
|
+
limits are applied too, and each invocation gets a fresh process.
|
|
250
250
|
|
|
251
251
|
The Docker image keeps public registration open by default for toy deployments.
|
|
252
252
|
Set `VLAMBDA_REGISTRATION=0` to close it and create users with
|
|
@@ -277,6 +277,8 @@ The demo can be wiped with:
|
|
|
277
277
|
python -m vlambda reset --yes --url http://127.0.0.1:8080 --token "$VLAMBDA_ADMIN_TOKEN"
|
|
278
278
|
```
|
|
279
279
|
|
|
280
|
+
A reset also invalidates existing JWT sessions and API tokens.
|
|
281
|
+
|
|
280
282
|
For a disposable demo, run it from cron every day:
|
|
281
283
|
|
|
282
284
|
```cron
|
|
@@ -287,7 +289,7 @@ For a disposable demo, run it from cron every day:
|
|
|
287
289
|
|
|
288
290
|
| Metric | Value |
|
|
289
291
|
|--------|-------|
|
|
290
|
-
| Cold start | 0ms
|
|
292
|
+
| Cold start | 0ms in persistent mode; fresh sandbox process in Docker |
|
|
291
293
|
| Warm invocation | ~0.3ms |
|
|
292
294
|
| Throughput (concurrent, free-threaded) | ~3,000 req/s |
|
|
293
295
|
| Throughput (response cache hits) | ~100x faster |
|
|
@@ -51,7 +51,7 @@ def main() -> None:
|
|
|
51
51
|
if not has_handler:
|
|
52
52
|
return "missing handler function"
|
|
53
53
|
return "" # valid
|
|
54
|
-
from vlambda.auth import verify_token, create_token, hash_password, check_password
|
|
54
|
+
from vlambda.auth import verify_token, create_token, hash_password, check_password, new_auth_epoch
|
|
55
55
|
import sqlite3
|
|
56
56
|
from vlambda.request import Request
|
|
57
57
|
from vlambda_native import start_server, db_init, register_pool, register_auth_verifier, register_auth_register, register_auth_login, configure, register_validate_code, register_ui_html, register_get_asset, register_get_project_json, register_save_project_json, register_list_versions, register_list_aliases, register_admin_reset, register_admin_create_user, register_list_packages, register_install_packages, register_create_task, register_get_task, register_record_metric, register_query_metrics, register_query_stats, register_query_summary, register_query_aggregate, register_query_logs, register_delete_metrics, register_delete_logs, register_export_metrics, register_pool_stats, register_run_project, register_create_project, register_delete_project, register_schedule_delete, register_get_dlq, register_export_lambda, register_import_lambda, register_duplicate_lambda, set_overloaded
|
|
@@ -143,6 +143,8 @@ def main() -> None:
|
|
|
143
143
|
vendor_dir = candidate
|
|
144
144
|
except Exception:
|
|
145
145
|
pass
|
|
146
|
+
if not timeout:
|
|
147
|
+
timeout = args.invoke_timeout
|
|
146
148
|
result = pool.execute(code, method, path, query, body, timeout, memory_mb, vendor_dir, request_id, slug)
|
|
147
149
|
if isinstance(result, str):
|
|
148
150
|
payload = result
|
|
@@ -166,19 +168,32 @@ def main() -> None:
|
|
|
166
168
|
if data is None:
|
|
167
169
|
return -1
|
|
168
170
|
try:
|
|
169
|
-
|
|
171
|
+
uid = int(data.get("sub", -1))
|
|
170
172
|
except (ValueError, TypeError):
|
|
171
173
|
return -1
|
|
174
|
+
epoch = str(data.get("epoch", ""))
|
|
175
|
+
if uid < 0 or not epoch:
|
|
176
|
+
return -1
|
|
177
|
+
from vlambda.dbpool import get as db_get
|
|
178
|
+
try:
|
|
179
|
+
with db_get(args.sqlite_path) as conn:
|
|
180
|
+
row = conn.execute("SELECT auth_epoch FROM users WHERE id = ?", (uid,)).fetchone()
|
|
181
|
+
except Exception:
|
|
182
|
+
return -1
|
|
183
|
+
if row is None or row[0] != epoch:
|
|
184
|
+
return -1
|
|
185
|
+
return uid
|
|
172
186
|
|
|
173
187
|
register_auth_verifier(_auth_verify)
|
|
174
188
|
|
|
175
189
|
# Auth: register user
|
|
176
190
|
def _auth_register(username, password):
|
|
177
191
|
from vlambda.dbpool import get as db_get
|
|
192
|
+
epoch = new_auth_epoch()
|
|
178
193
|
try:
|
|
179
194
|
with db_get(args.sqlite_path) as conn:
|
|
180
|
-
conn.execute("INSERT INTO users (username, password_hash) VALUES (?, ?)",
|
|
181
|
-
(username, hash_password(password)))
|
|
195
|
+
conn.execute("INSERT INTO users (username, password_hash, auth_epoch) VALUES (?, ?, ?)",
|
|
196
|
+
(username, hash_password(password), epoch))
|
|
182
197
|
conn.commit()
|
|
183
198
|
uid = conn.execute("SELECT id FROM users WHERE username = ?", (username,)).fetchone()[0]
|
|
184
199
|
return uid
|
|
@@ -191,13 +206,17 @@ def main() -> None:
|
|
|
191
206
|
def _auth_login(username, password):
|
|
192
207
|
from vlambda.dbpool import get as db_get
|
|
193
208
|
with db_get(args.sqlite_path) as conn:
|
|
194
|
-
row = conn.execute("SELECT id, password_hash FROM users WHERE username = ?", (username,)).fetchone()
|
|
209
|
+
row = conn.execute("SELECT id, password_hash, auth_epoch FROM users WHERE username = ?", (username,)).fetchone()
|
|
195
210
|
if row is None:
|
|
196
211
|
return ""
|
|
197
|
-
uid, stored = row
|
|
212
|
+
uid, stored, epoch = row
|
|
198
213
|
if not check_password(password, stored):
|
|
199
214
|
return ""
|
|
200
|
-
|
|
215
|
+
if not epoch:
|
|
216
|
+
epoch = new_auth_epoch()
|
|
217
|
+
conn.execute("UPDATE users SET auth_epoch = ? WHERE id = ?", (epoch, uid))
|
|
218
|
+
conn.commit()
|
|
219
|
+
return create_token(uid, username, epoch)
|
|
201
220
|
|
|
202
221
|
# Register V bridges
|
|
203
222
|
from vlambda_native import register_auth_register, register_auth_login
|
|
@@ -382,7 +401,7 @@ def main() -> None:
|
|
|
382
401
|
|
|
383
402
|
def _run_project(project_dir, entrypoint, method, path, query, body):
|
|
384
403
|
import json
|
|
385
|
-
timeout =
|
|
404
|
+
timeout = args.invoke_timeout
|
|
386
405
|
try:
|
|
387
406
|
result = pool.execute_project(project_dir, entrypoint, method, path, query, body, timeout=timeout)
|
|
388
407
|
if isinstance(result, str):
|
|
@@ -481,8 +500,8 @@ def main() -> None:
|
|
|
481
500
|
if args.max_memory_mb > 0:
|
|
482
501
|
import threading, time, resource
|
|
483
502
|
# A hard RLIMIT_AS for the whole process starves V/Python threads and
|
|
484
|
-
# mmap. Use
|
|
485
|
-
# enabled explicitly for constrained environments.
|
|
503
|
+
# mmap. Use the Docker cgroup or the per-invocation sandbox limits
|
|
504
|
+
# instead. It can be enabled explicitly for constrained environments.
|
|
486
505
|
if os.environ.get("VLAMBDA_HARD_MEMORY_LIMIT", "0") == "1":
|
|
487
506
|
limit_bytes = args.max_memory_mb * 1024 * 1024
|
|
488
507
|
try:
|
|
@@ -23,11 +23,17 @@ def _b64decode(s: str) -> bytes:
|
|
|
23
23
|
return base64.urlsafe_b64decode(s)
|
|
24
24
|
|
|
25
25
|
|
|
26
|
-
def
|
|
26
|
+
def new_auth_epoch() -> str:
|
|
27
|
+
"""Random per-user value that invalidates old tokens after a DB reset."""
|
|
28
|
+
return os.urandom(16).hex()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def create_token(user_id: int, username: str, auth_epoch: str = "", expires_in: int = 3600) -> str:
|
|
27
32
|
header = _b64encode(json.dumps({"alg": "HS256", "typ": "JWT"}).encode())
|
|
28
33
|
payload = _b64encode(json.dumps({
|
|
29
34
|
"sub": str(user_id),
|
|
30
35
|
"username": username,
|
|
36
|
+
"epoch": auth_epoch,
|
|
31
37
|
"exp": int(time.time()) + expires_in,
|
|
32
38
|
}).encode())
|
|
33
39
|
sig_input = f"{header}.{payload}".encode()
|
|
@@ -406,9 +406,135 @@ class ProcessPool:
|
|
|
406
406
|
worker.stop()
|
|
407
407
|
|
|
408
408
|
|
|
409
|
+
def _landlock_read_paths() -> list[str]:
|
|
410
|
+
"""Paths the runner needs for Python and its own code."""
|
|
411
|
+
candidates = ["/opt", "/usr", "/lib", "/lib64", "/bin", "/sbin", "/etc"]
|
|
412
|
+
candidates.extend([sys.prefix, sys.base_prefix])
|
|
413
|
+
candidates.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
414
|
+
candidates.extend(sys.path)
|
|
415
|
+
paths: list[str] = []
|
|
416
|
+
for path in candidates:
|
|
417
|
+
if not path or path in (".", "/") or not os.path.isdir(path):
|
|
418
|
+
continue
|
|
419
|
+
normalized = os.path.abspath(path)
|
|
420
|
+
if normalized == "/":
|
|
421
|
+
continue
|
|
422
|
+
if normalized == "/data" or normalized.startswith("/data/"):
|
|
423
|
+
continue
|
|
424
|
+
if normalized not in paths:
|
|
425
|
+
paths.append(normalized)
|
|
426
|
+
return paths
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
class LandlockWorker:
|
|
430
|
+
"""Run one invocation in a fresh Landlock + seccomp sandbox."""
|
|
431
|
+
|
|
432
|
+
def submit(self, code, method, path, query, body, timeout=0, memory_mb=0, vendor_dir="", request_id="", slug=""):
|
|
433
|
+
vendor = vendor_dir or ""
|
|
434
|
+
if vendor and not os.path.isdir(vendor):
|
|
435
|
+
vendor = ""
|
|
436
|
+
payload = {
|
|
437
|
+
"kind": "code",
|
|
438
|
+
"code": code,
|
|
439
|
+
"method": method,
|
|
440
|
+
"path": path,
|
|
441
|
+
"query_string": query,
|
|
442
|
+
"body_b64": base64.b64encode(body or b"").decode("ascii"),
|
|
443
|
+
"vendor_dir": vendor,
|
|
444
|
+
"request_id": request_id or "",
|
|
445
|
+
"slug": slug or "",
|
|
446
|
+
}
|
|
447
|
+
return self._run(payload, timeout, vendor_dir=vendor)
|
|
448
|
+
|
|
449
|
+
def submit_project(self, project_dir, entrypoint, method, path, query, body, timeout=0, request_id="", slug=""):
|
|
450
|
+
payload = {
|
|
451
|
+
"kind": "project",
|
|
452
|
+
"project_dir": project_dir,
|
|
453
|
+
"entrypoint": entrypoint,
|
|
454
|
+
"method": method,
|
|
455
|
+
"path": path,
|
|
456
|
+
"query_string": query,
|
|
457
|
+
"body_b64": base64.b64encode(body or b"").decode("ascii"),
|
|
458
|
+
"request_id": request_id or "",
|
|
459
|
+
"slug": slug or "",
|
|
460
|
+
}
|
|
461
|
+
return self._run(payload, timeout, project_dir=project_dir)
|
|
462
|
+
|
|
463
|
+
def _run(self, payload: dict, timeout: int = 0, project_dir: str = "", vendor_dir: str = ""):
|
|
464
|
+
timeout = timeout if timeout and timeout > 0 else int(os.environ.get("VLAMBDA_INVOKE_TIMEOUT", "30"))
|
|
465
|
+
tmp_dir = tempfile.mkdtemp(prefix="vlambda-run-", dir="/tmp")
|
|
466
|
+
try:
|
|
467
|
+
read_paths = _landlock_read_paths()
|
|
468
|
+
if project_dir:
|
|
469
|
+
read_paths.append(project_dir)
|
|
470
|
+
if vendor_dir:
|
|
471
|
+
read_paths.append(vendor_dir)
|
|
472
|
+
cmd = [sys.executable, "-m", "vlambda.runner", "--sandbox", "landlock"]
|
|
473
|
+
for path in dict.fromkeys(read_paths):
|
|
474
|
+
cmd.extend(["--allow-read", path])
|
|
475
|
+
cmd.extend(["--allow-rw", tmp_dir, "--cpu", str(max(1, int(timeout)))])
|
|
476
|
+
env = _runner_env()
|
|
477
|
+
env["HOME"] = tmp_dir
|
|
478
|
+
env["TMPDIR"] = tmp_dir
|
|
479
|
+
proc = subprocess.Popen(
|
|
480
|
+
cmd,
|
|
481
|
+
stdin=subprocess.PIPE,
|
|
482
|
+
stdout=subprocess.PIPE,
|
|
483
|
+
stderr=subprocess.PIPE,
|
|
484
|
+
text=True,
|
|
485
|
+
cwd=tmp_dir,
|
|
486
|
+
env=env,
|
|
487
|
+
)
|
|
488
|
+
try:
|
|
489
|
+
out, err = proc.communicate(json.dumps(payload) + "\n", timeout=timeout + 2)
|
|
490
|
+
except subprocess.TimeoutExpired:
|
|
491
|
+
proc.kill()
|
|
492
|
+
proc.communicate()
|
|
493
|
+
return {"error": "invocation timeout"}
|
|
494
|
+
except Exception as e:
|
|
495
|
+
print(f"landlock setup failed: {e}", file=sys.stderr, flush=True)
|
|
496
|
+
return {"error": "sandbox failed"}
|
|
497
|
+
finally:
|
|
498
|
+
shutil.rmtree(tmp_dir, ignore_errors=True)
|
|
499
|
+
lines = [line for line in out.splitlines() if line.strip()]
|
|
500
|
+
if not lines:
|
|
501
|
+
if err.strip():
|
|
502
|
+
print(f"landlock error: {err.strip()[-2000:]}", file=sys.stderr, flush=True)
|
|
503
|
+
return {"error": "sandbox exited"}
|
|
504
|
+
try:
|
|
505
|
+
envelope = json.loads(lines[-1])
|
|
506
|
+
except json.JSONDecodeError:
|
|
507
|
+
return {"error": "invalid runner response"}
|
|
508
|
+
if envelope.get("ok"):
|
|
509
|
+
return envelope.get("payload")
|
|
510
|
+
return {"error": envelope.get("error", "execution failed")}
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
class LandlockPool:
|
|
514
|
+
def __init__(self, size: int):
|
|
515
|
+
self._sem = threading.BoundedSemaphore(max(1, size))
|
|
516
|
+
self._max_workers = max(1, size)
|
|
517
|
+
|
|
518
|
+
def execute(self, code, method, path, query, body, timeout=0, memory_mb=0, vendor_dir="", request_id="", slug=""):
|
|
519
|
+
with self._sem:
|
|
520
|
+
return LandlockWorker().submit(code, method, path, query, body, timeout, memory_mb, vendor_dir, request_id, slug)
|
|
521
|
+
|
|
522
|
+
def execute_project(self, project_dir, entrypoint, method, path, query, body, timeout=0, request_id="", slug=""):
|
|
523
|
+
with self._sem:
|
|
524
|
+
return LandlockWorker().submit_project(project_dir, entrypoint, method, path, query, body, timeout, request_id, slug)
|
|
525
|
+
|
|
526
|
+
def _queue_depth(self) -> int:
|
|
527
|
+
return 0
|
|
528
|
+
|
|
529
|
+
def stats(self):
|
|
530
|
+
return {"workers": self._max_workers, "max_workers": self._max_workers, "queue_depth": 0, "mode": "landlock"}
|
|
531
|
+
|
|
532
|
+
def stop(self):
|
|
533
|
+
pass
|
|
534
|
+
|
|
535
|
+
|
|
409
536
|
class NsjailWorker:
|
|
410
537
|
"""Run one invocation in a fresh nsjail sandbox."""
|
|
411
|
-
|
|
412
538
|
def submit(self, code, method, path, query, body, timeout=0, memory_mb=0, vendor_dir="", request_id="", slug=""):
|
|
413
539
|
vendor = vendor_dir or ""
|
|
414
540
|
if vendor and not os.path.isdir(vendor):
|
|
@@ -510,7 +636,10 @@ class NsjailPool:
|
|
|
510
636
|
pass
|
|
511
637
|
|
|
512
638
|
|
|
513
|
-
|
|
639
|
+
_sandbox_mode = os.environ.get("VLAMBDA_SANDBOX", "").lower()
|
|
640
|
+
if _sandbox_mode == "landlock":
|
|
641
|
+
Pool = LandlockPool
|
|
642
|
+
elif _sandbox_mode == "nsjail" or os.environ.get("VLAMBDA_NSJAIL", "0") == "1":
|
|
514
643
|
Pool = NsjailPool
|
|
515
644
|
elif os.environ.get("VLAMBDA_ISOLATE", "0") == "1":
|
|
516
645
|
Pool = ProcessPool
|
|
@@ -37,7 +37,43 @@ def _execute_project(project_dir: str, entrypoint: str, method: str, path: str,
|
|
|
37
37
|
return execute_project(project_dir, entrypoint, req)
|
|
38
38
|
|
|
39
39
|
|
|
40
|
+
def _sandbox_args(argv: list[str]) -> tuple[bool, list[str], list[str], int]:
|
|
41
|
+
enabled = False
|
|
42
|
+
read_paths: list[str] = []
|
|
43
|
+
rw_paths: list[str] = []
|
|
44
|
+
cpu_sec = 5
|
|
45
|
+
index = 0
|
|
46
|
+
while index < len(argv):
|
|
47
|
+
arg = argv[index]
|
|
48
|
+
if arg == "--sandbox" and index + 1 < len(argv):
|
|
49
|
+
enabled = argv[index + 1] == "landlock"
|
|
50
|
+
index += 2
|
|
51
|
+
elif arg == "--allow-read" and index + 1 < len(argv):
|
|
52
|
+
read_paths.append(argv[index + 1])
|
|
53
|
+
index += 2
|
|
54
|
+
elif arg == "--allow-rw" and index + 1 < len(argv):
|
|
55
|
+
rw_paths.append(argv[index + 1])
|
|
56
|
+
index += 2
|
|
57
|
+
elif arg == "--cpu" and index + 1 < len(argv):
|
|
58
|
+
try:
|
|
59
|
+
cpu_sec = max(1, int(argv[index + 1]))
|
|
60
|
+
except ValueError:
|
|
61
|
+
pass
|
|
62
|
+
index += 2
|
|
63
|
+
else:
|
|
64
|
+
index += 1
|
|
65
|
+
return enabled, read_paths, rw_paths, cpu_sec
|
|
66
|
+
|
|
67
|
+
|
|
40
68
|
def main() -> None:
|
|
69
|
+
sandboxed, read_paths, rw_paths, cpu_sec = _sandbox_args(sys.argv[1:])
|
|
70
|
+
if sandboxed:
|
|
71
|
+
try:
|
|
72
|
+
from vlambda.sandbox_os import apply_sandbox
|
|
73
|
+
apply_sandbox(read_paths, rw_paths, cpu_sec)
|
|
74
|
+
except Exception as e:
|
|
75
|
+
print(json.dumps({"ok": False, "error": f"sandbox: {type(e).__name__}: {e}"}), flush=True)
|
|
76
|
+
return
|
|
41
77
|
# Keep stdout clean: only protocol JSON goes there.
|
|
42
78
|
for line in sys.stdin:
|
|
43
79
|
line = line.strip()
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
"""Landlock + seccomp self-confinement for runner processes.
|
|
2
|
+
|
|
3
|
+
The runner runs under the same container as the server, so this module builds
|
|
4
|
+
an unprivileged OS-level sandbox before any user code is executed:
|
|
5
|
+
|
|
6
|
+
* Landlock limits filesystem access to an explicit allow-list (read-only
|
|
7
|
+
Python/venv/project paths plus one writable temporary directory).
|
|
8
|
+
* seccomp blocks network, signals to other processes, ptrace, mount,
|
|
9
|
+
namespace changes and other dangerous syscalls.
|
|
10
|
+
|
|
11
|
+
No user namespaces, capabilities, compose flags or host sysctl changes are
|
|
12
|
+
required. Kernel >= 5.13 with Landlock is needed.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import ctypes
|
|
18
|
+
import errno
|
|
19
|
+
import os
|
|
20
|
+
import platform
|
|
21
|
+
import resource
|
|
22
|
+
|
|
23
|
+
# Landlock access rights (ABI v1-v5).
|
|
24
|
+
LL_EXECUTE = 1 << 0
|
|
25
|
+
LL_WRITE_FILE = 1 << 1
|
|
26
|
+
LL_READ_FILE = 1 << 2
|
|
27
|
+
LL_READ_DIR = 1 << 3
|
|
28
|
+
LL_REMOVE_DIR = 1 << 4
|
|
29
|
+
LL_REMOVE_FILE = 1 << 5
|
|
30
|
+
LL_MAKE_CHAR = 1 << 6
|
|
31
|
+
LL_MAKE_DIR = 1 << 7
|
|
32
|
+
LL_MAKE_REG = 1 << 8
|
|
33
|
+
LL_MAKE_SOCK = 1 << 9
|
|
34
|
+
LL_MAKE_FIFO = 1 << 10
|
|
35
|
+
LL_MAKE_BLOCK = 1 << 11
|
|
36
|
+
LL_MAKE_SYM = 1 << 12
|
|
37
|
+
LL_REFER = 1 << 13
|
|
38
|
+
LL_TRUNCATE = 1 << 14
|
|
39
|
+
LL_IOCTL_DEV = 1 << 15
|
|
40
|
+
|
|
41
|
+
_LL_ABI1 = (1 << 13) - 1
|
|
42
|
+
_LL_ABI2 = _LL_ABI1 | LL_REFER
|
|
43
|
+
_LL_ABI3 = _LL_ABI2 | LL_TRUNCATE
|
|
44
|
+
_LL_ABI5 = _LL_ABI3 | LL_IOCTL_DEV
|
|
45
|
+
|
|
46
|
+
_READ_FILE_ACCESS = LL_READ_FILE | LL_EXECUTE
|
|
47
|
+
_READ_DIR_ACCESS = _READ_FILE_ACCESS | LL_READ_DIR
|
|
48
|
+
_WRITE_DIR_ACCESS = (
|
|
49
|
+
LL_READ_FILE | LL_WRITE_FILE | LL_READ_DIR | LL_REMOVE_DIR | LL_REMOVE_FILE
|
|
50
|
+
| LL_MAKE_DIR | LL_MAKE_REG | LL_MAKE_SOCK | LL_MAKE_FIFO | LL_MAKE_SYM
|
|
51
|
+
| LL_REFER | LL_TRUNCATE
|
|
52
|
+
)
|
|
53
|
+
_DEVICE_ACCESS = LL_READ_FILE | LL_WRITE_FILE
|
|
54
|
+
|
|
55
|
+
_RULE_PATH_BENEATH = 1
|
|
56
|
+
_CREATE_RULESET_VERSION = 1
|
|
57
|
+
|
|
58
|
+
_SCMP_ACT_ALLOW = 0x7FFF0000
|
|
59
|
+
_SCMP_ACT_ERRNO = 0x00050000
|
|
60
|
+
_SCMP_CMP_MASKED_EQ = 7
|
|
61
|
+
|
|
62
|
+
# Syscalls that must never be reachable from user code. Most are blocked with
|
|
63
|
+
# EPERM/EACCES so Python can report a normal exception instead of dying.
|
|
64
|
+
_DENY_SYSCALLS = (
|
|
65
|
+
# network
|
|
66
|
+
"socket", "socketpair", "connect", "bind", "listen", "accept", "accept4",
|
|
67
|
+
"sendto", "recvfrom", "sendmsg", "recvmsg", "sendmmsg", "recvmmsg",
|
|
68
|
+
"shutdown", "getsockname", "getpeername", "setsockopt", "getsockopt",
|
|
69
|
+
# process creation / execution
|
|
70
|
+
"fork", "vfork", "execve", "execveat",
|
|
71
|
+
# process control / signals
|
|
72
|
+
"kill", "tkill", "tgkill", "rt_sigqueueinfo", "rt_tgsigqueueinfo",
|
|
73
|
+
"pidfd_open", "pidfd_send_signal", "pidfd_getfd", "process_vm_readv",
|
|
74
|
+
"process_vm_writev", "process_madvise", "process_mrelease", "ptrace",
|
|
75
|
+
"kcmp", "prlimit64", "sched_setaffinity", "sched_setattr",
|
|
76
|
+
"sched_setscheduler", "setpriority", "ioprio_set", "migrate_pages",
|
|
77
|
+
"move_pages",
|
|
78
|
+
# filesystem / namespaces / mounts
|
|
79
|
+
"mount", "umount", "umount2", "pivot_root", "chroot", "setns", "unshare",
|
|
80
|
+
"open_tree", "move_mount", "fsopen", "fsconfig", "fsmount", "fspick",
|
|
81
|
+
"mount_setattr", "open_by_handle_at", "name_to_handle_at",
|
|
82
|
+
# kernel attack surface
|
|
83
|
+
"bpf", "perf_event_open", "keyctl", "add_key", "request_key",
|
|
84
|
+
"kexec_load", "kexec_file_load", "reboot", "swapon", "swapoff",
|
|
85
|
+
"init_module", "finit_module", "delete_module", "acct", "quotactl",
|
|
86
|
+
"syslog", "adjtimex", "clock_settime", "settimeofday", "sethostname",
|
|
87
|
+
"setdomainname", "vhangup", "nfsservctl", "userfaultfd",
|
|
88
|
+
"io_uring_setup", "io_uring_enter", "io_uring_register",
|
|
89
|
+
# privilege changes (the runner is already unprivileged)
|
|
90
|
+
"setuid", "setgid", "setreuid", "setregid", "setresuid", "setresgid",
|
|
91
|
+
"setgroups", "capset",
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _libc():
|
|
96
|
+
lib = ctypes.CDLL(None, use_errno=True)
|
|
97
|
+
lib.syscall.restype = ctypes.c_long
|
|
98
|
+
lib.prctl.restype = ctypes.c_int
|
|
99
|
+
lib.prctl.argtypes = [ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong]
|
|
100
|
+
return lib
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class _PathBeneath(ctypes.Structure):
|
|
104
|
+
_pack_ = 1
|
|
105
|
+
_fields_ = [("allowed_access", ctypes.c_uint64), ("parent_fd", ctypes.c_int32)]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class _ScmpArgCmp(ctypes.Structure):
|
|
109
|
+
_fields_ = [
|
|
110
|
+
("arg", ctypes.c_uint),
|
|
111
|
+
("op", ctypes.c_int),
|
|
112
|
+
("datum_a", ctypes.c_uint64),
|
|
113
|
+
("datum_b", ctypes.c_uint64),
|
|
114
|
+
]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _syscalls() -> tuple[int, int, int]:
|
|
118
|
+
machine = platform.machine().lower()
|
|
119
|
+
if machine in ("x86_64", "amd64", "aarch64", "arm64"):
|
|
120
|
+
return 444, 445, 446
|
|
121
|
+
raise RuntimeError(f"Landlock is not supported on {machine}")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _landlock_abi(libc) -> int:
|
|
125
|
+
nr, _, _ = _syscalls()
|
|
126
|
+
ret = libc.syscall(
|
|
127
|
+
ctypes.c_long(nr), ctypes.c_void_p(0), ctypes.c_size_t(0),
|
|
128
|
+
ctypes.c_uint(_CREATE_RULESET_VERSION),
|
|
129
|
+
)
|
|
130
|
+
if ret < 0:
|
|
131
|
+
err = ctypes.get_errno()
|
|
132
|
+
raise OSError(err, f"landlock_create_ruleset: {os.strerror(err)}")
|
|
133
|
+
return int(ret)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _handled_mask(abi: int) -> int:
|
|
137
|
+
if abi >= 5:
|
|
138
|
+
return _LL_ABI5
|
|
139
|
+
if abi >= 3:
|
|
140
|
+
return _LL_ABI3
|
|
141
|
+
if abi >= 2:
|
|
142
|
+
return _LL_ABI2
|
|
143
|
+
return _LL_ABI1
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _add_rule(libc, ruleset_fd: int, path: str, access: int):
|
|
147
|
+
try:
|
|
148
|
+
pfd = os.open(path, os.O_PATH | os.O_CLOEXEC)
|
|
149
|
+
except OSError:
|
|
150
|
+
return
|
|
151
|
+
try:
|
|
152
|
+
attr = _PathBeneath(access, pfd)
|
|
153
|
+
_, add_nr, _ = _syscalls()
|
|
154
|
+
ret = libc.syscall(
|
|
155
|
+
ctypes.c_long(add_nr), ctypes.c_int(ruleset_fd),
|
|
156
|
+
ctypes.c_uint(_RULE_PATH_BENEATH), ctypes.byref(attr), ctypes.c_uint(0),
|
|
157
|
+
)
|
|
158
|
+
if ret != 0:
|
|
159
|
+
err = ctypes.get_errno()
|
|
160
|
+
raise OSError(err, f"landlock_add_rule({path}): {os.strerror(err)}")
|
|
161
|
+
finally:
|
|
162
|
+
os.close(pfd)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _apply_landlock(read_paths: list[str], rw_paths: list[str]):
|
|
166
|
+
libc = _libc()
|
|
167
|
+
abi = _landlock_abi(libc)
|
|
168
|
+
handled = _handled_mask(abi)
|
|
169
|
+
attr = ctypes.c_uint64(handled)
|
|
170
|
+
create_nr, _, restrict_nr = _syscalls()
|
|
171
|
+
ruleset_fd = libc.syscall(
|
|
172
|
+
ctypes.c_long(create_nr), ctypes.byref(attr),
|
|
173
|
+
ctypes.c_size_t(ctypes.sizeof(attr)), ctypes.c_uint(0),
|
|
174
|
+
)
|
|
175
|
+
if ruleset_fd < 0:
|
|
176
|
+
err = ctypes.get_errno()
|
|
177
|
+
raise OSError(err, f"landlock_create_ruleset: {os.strerror(err)}")
|
|
178
|
+
try:
|
|
179
|
+
for path in read_paths:
|
|
180
|
+
if not path or not os.path.exists(path):
|
|
181
|
+
continue
|
|
182
|
+
access = _READ_DIR_ACCESS if os.path.isdir(path) else _READ_FILE_ACCESS
|
|
183
|
+
_add_rule(libc, ruleset_fd, path, access & handled)
|
|
184
|
+
for path in rw_paths:
|
|
185
|
+
if not path or not os.path.exists(path):
|
|
186
|
+
continue
|
|
187
|
+
if os.path.isdir(path):
|
|
188
|
+
access = _WRITE_DIR_ACCESS
|
|
189
|
+
else:
|
|
190
|
+
access = _DEVICE_ACCESS
|
|
191
|
+
_add_rule(libc, ruleset_fd, path, access & handled)
|
|
192
|
+
# Devices Python needs for normal operation.
|
|
193
|
+
for path in ("/dev/null", "/dev/zero", "/dev/urandom", "/dev/random"):
|
|
194
|
+
if os.path.exists(path):
|
|
195
|
+
_add_rule(libc, ruleset_fd, path, _DEVICE_ACCESS & handled)
|
|
196
|
+
# Landlock requires no_new_privs when the caller is not privileged.
|
|
197
|
+
if libc.prctl(38, 1, 0, 0, 0) != 0: # PR_SET_NO_NEW_PRIVS
|
|
198
|
+
err = ctypes.get_errno()
|
|
199
|
+
raise OSError(err, f"prctl(PR_SET_NO_NEW_PRIVS): {os.strerror(err)}")
|
|
200
|
+
ret = libc.syscall(ctypes.c_long(restrict_nr), ctypes.c_int(ruleset_fd), ctypes.c_uint(0))
|
|
201
|
+
if ret != 0:
|
|
202
|
+
err = ctypes.get_errno()
|
|
203
|
+
raise OSError(err, f"landlock_restrict_self: {os.strerror(err)}")
|
|
204
|
+
finally:
|
|
205
|
+
os.close(ruleset_fd)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _load_seccomp():
|
|
209
|
+
last_error = None
|
|
210
|
+
for soname in ("libseccomp.so.2", "libseccomp.so"):
|
|
211
|
+
try:
|
|
212
|
+
lib = ctypes.CDLL(soname)
|
|
213
|
+
break
|
|
214
|
+
except OSError as exc:
|
|
215
|
+
last_error = exc
|
|
216
|
+
else:
|
|
217
|
+
raise RuntimeError(f"libseccomp not available: {last_error}")
|
|
218
|
+
|
|
219
|
+
lib.seccomp_init.restype = ctypes.c_void_p
|
|
220
|
+
lib.seccomp_init.argtypes = [ctypes.c_uint32]
|
|
221
|
+
lib.seccomp_syscall_resolve_name.restype = ctypes.c_int
|
|
222
|
+
lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p]
|
|
223
|
+
lib.seccomp_rule_add_array.restype = ctypes.c_int
|
|
224
|
+
lib.seccomp_rule_add_array.argtypes = [
|
|
225
|
+
ctypes.c_void_p, ctypes.c_uint32, ctypes.c_int, ctypes.c_uint,
|
|
226
|
+
ctypes.POINTER(_ScmpArgCmp),
|
|
227
|
+
]
|
|
228
|
+
lib.seccomp_load.restype = ctypes.c_int
|
|
229
|
+
lib.seccomp_load.argtypes = [ctypes.c_void_p]
|
|
230
|
+
lib.seccomp_release.restype = None
|
|
231
|
+
lib.seccomp_release.argtypes = [ctypes.c_void_p]
|
|
232
|
+
|
|
233
|
+
ctx = lib.seccomp_init(_SCMP_ACT_ALLOW)
|
|
234
|
+
if not ctx:
|
|
235
|
+
raise RuntimeError("seccomp_init failed")
|
|
236
|
+
try:
|
|
237
|
+
action = _SCMP_ACT_ERRNO | errno.EPERM
|
|
238
|
+
for name in _DENY_SYSCALLS:
|
|
239
|
+
nr = lib.seccomp_syscall_resolve_name(name.encode())
|
|
240
|
+
if nr < 0:
|
|
241
|
+
continue
|
|
242
|
+
rc = lib.seccomp_rule_add_array(ctx, action, nr, 0, None)
|
|
243
|
+
if rc != 0:
|
|
244
|
+
raise RuntimeError(f"seccomp rule failed for {name}: {rc}")
|
|
245
|
+
# glibc falls back to clone() when clone3() reports ENOSYS.
|
|
246
|
+
clone3_nr = lib.seccomp_syscall_resolve_name(b"clone3")
|
|
247
|
+
if clone3_nr >= 0:
|
|
248
|
+
rc = lib.seccomp_rule_add_array(
|
|
249
|
+
ctx, _SCMP_ACT_ERRNO | errno.ENOSYS, clone3_nr, 0, None,
|
|
250
|
+
)
|
|
251
|
+
if rc != 0:
|
|
252
|
+
raise RuntimeError(f"seccomp clone3 rule failed: {rc}")
|
|
253
|
+
# Threads are allowed (CLONE_THREAD); fork-like clone calls are denied.
|
|
254
|
+
clone_nr = lib.seccomp_syscall_resolve_name(b"clone")
|
|
255
|
+
if clone_nr >= 0:
|
|
256
|
+
clone_thread = 0x00010000
|
|
257
|
+
cmp = _ScmpArgCmp(0, _SCMP_CMP_MASKED_EQ, clone_thread, 0)
|
|
258
|
+
rc = lib.seccomp_rule_add_array(ctx, action, clone_nr, 1, ctypes.byref(cmp))
|
|
259
|
+
if rc != 0:
|
|
260
|
+
raise RuntimeError(f"seccomp clone rule failed: {rc}")
|
|
261
|
+
rc = lib.seccomp_load(ctx)
|
|
262
|
+
if rc != 0:
|
|
263
|
+
raise RuntimeError(f"seccomp_load failed: {rc}")
|
|
264
|
+
finally:
|
|
265
|
+
lib.seccomp_release(ctx)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _apply_rlimits(cpu_sec: int = 5):
|
|
269
|
+
limits = (
|
|
270
|
+
(resource.RLIMIT_AS, 2048 * 1024 * 1024),
|
|
271
|
+
(resource.RLIMIT_CPU, max(1, cpu_sec)),
|
|
272
|
+
(resource.RLIMIT_NOFILE, 64),
|
|
273
|
+
(resource.RLIMIT_FSIZE, 16 * 1024 * 1024),
|
|
274
|
+
(resource.RLIMIT_CORE, 0),
|
|
275
|
+
)
|
|
276
|
+
for kind, value in limits:
|
|
277
|
+
try:
|
|
278
|
+
resource.setrlimit(kind, (value, value))
|
|
279
|
+
except (OSError, ValueError):
|
|
280
|
+
pass
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def apply_sandbox(read_paths: list[str], rw_paths: list[str], cpu_sec: int = 5):
|
|
284
|
+
"""Confine the current process. Must run before user code."""
|
|
285
|
+
_apply_rlimits(cpu_sec)
|
|
286
|
+
_apply_landlock(read_paths, rw_paths)
|
|
287
|
+
_load_seccomp()
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def sandbox_supported() -> bool:
|
|
291
|
+
try:
|
|
292
|
+
return _landlock_abi(_libc()) >= 1
|
|
293
|
+
except Exception:
|
|
294
|
+
return False
|
|
@@ -98,8 +98,10 @@ fn init_db(db_path string) !sqlite.DB {
|
|
|
98
98
|
db.exec('CREATE TABLE IF NOT EXISTS users (
|
|
99
99
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
100
100
|
username TEXT UNIQUE NOT NULL,
|
|
101
|
-
password_hash TEXT NOT NULL
|
|
101
|
+
password_hash TEXT NOT NULL,
|
|
102
|
+
auth_epoch TEXT NOT NULL DEFAULT ""
|
|
102
103
|
);')!
|
|
104
|
+
db.exec('ALTER TABLE users ADD COLUMN auth_epoch TEXT NOT NULL DEFAULT "";') or {}
|
|
103
105
|
db.exec('CREATE TABLE IF NOT EXISTS lambdas (
|
|
104
106
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
105
107
|
slug TEXT UNIQUE NOT NULL,
|
|
@@ -2345,7 +2347,7 @@ pub fn db_verify_api_token(raw string) string {
|
|
|
2345
2347
|
hash := sha256.sum256(raw.bytes()).hex()
|
|
2346
2348
|
mut db := init_db(vlambda_db_path) or { return '' }
|
|
2347
2349
|
defer { db.close() or {} }
|
|
2348
|
-
rows := db.exec_param('SELECT user_id, scopes FROM api_tokens WHERE token_hash = ? AND revoked = 0;',
|
|
2350
|
+
rows := db.exec_param('SELECT t.user_id, t.scopes FROM api_tokens t JOIN users u ON u.id = t.user_id WHERE t.token_hash = ? AND t.revoked = 0;',
|
|
2349
2351
|
hash) or { return '' }
|
|
2350
2352
|
if rows.len == 0 {
|
|
2351
2353
|
return ''
|
|
@@ -95,6 +95,13 @@ def test_runner_env_strips_secrets(monkeypatch):
|
|
|
95
95
|
assert not any(key.startswith("VLAMBDA_") for key in env)
|
|
96
96
|
|
|
97
97
|
|
|
98
|
+
def test_landlock_read_paths():
|
|
99
|
+
from vlambda.pool import _landlock_read_paths
|
|
100
|
+
paths = _landlock_read_paths()
|
|
101
|
+
assert "/" not in paths
|
|
102
|
+
assert all(not path.startswith("/data") for path in paths)
|
|
103
|
+
|
|
104
|
+
|
|
98
105
|
def test_nsjail_config():
|
|
99
106
|
from vlambda.pool import _nsjail_config
|
|
100
107
|
cfg = _nsjail_config("/data/projects/x", "/data/packages/y")
|
|
@@ -185,11 +192,12 @@ def test_gc_orphans_respects_grace(tmp_path, monkeypatch):
|
|
|
185
192
|
|
|
186
193
|
def test_auth_token_roundtrip():
|
|
187
194
|
from vlambda.auth import create_token, verify_token
|
|
188
|
-
token = create_token(42, "alice")
|
|
195
|
+
token = create_token(42, "alice", "epoch-1")
|
|
189
196
|
data = verify_token(token)
|
|
190
197
|
assert data is not None
|
|
191
198
|
assert data["sub"] == "42"
|
|
192
199
|
assert data["username"] == "alice"
|
|
200
|
+
assert data["epoch"] == "epoch-1"
|
|
193
201
|
|
|
194
202
|
|
|
195
203
|
def test_auth_bad_token():
|
|
@@ -351,6 +351,64 @@ def test_nsjail_sandbox():
|
|
|
351
351
|
stop_server()
|
|
352
352
|
|
|
353
353
|
|
|
354
|
+
def test_landlock_sandbox():
|
|
355
|
+
try:
|
|
356
|
+
from vlambda.sandbox_os import sandbox_supported
|
|
357
|
+
import ctypes.util
|
|
358
|
+
if not sandbox_supported() or not ctypes.util.find_library("seccomp"):
|
|
359
|
+
return
|
|
360
|
+
except Exception:
|
|
361
|
+
return
|
|
362
|
+
stop_server()
|
|
363
|
+
start_server({
|
|
364
|
+
"VLAMBDA_SANDBOX": "landlock",
|
|
365
|
+
"VLAMBDA_SECRET": "test-secret",
|
|
366
|
+
"VLAMBDA_COROUTINES": "2",
|
|
367
|
+
"VLAMBDA_TIMEOUT": "5",
|
|
368
|
+
})
|
|
369
|
+
try:
|
|
370
|
+
token, slug = _upload_project("landlock", {
|
|
371
|
+
"main.py": (
|
|
372
|
+
"import os, socket, threading\n"
|
|
373
|
+
"def handler(request):\n"
|
|
374
|
+
" out = {}\n"
|
|
375
|
+
" def check(name, fn):\n"
|
|
376
|
+
" try:\n"
|
|
377
|
+
" fn(); out[name] = 'ok'\n"
|
|
378
|
+
" except Exception as e:\n"
|
|
379
|
+
" out[name] = type(e).__name__\n"
|
|
380
|
+
" check('data', lambda: os.listdir('/data'))\n"
|
|
381
|
+
" check('db', lambda: open('/data/db/vlambda.db', 'rb').read(1))\n"
|
|
382
|
+
" check('proc', lambda: open('/proc/1/environ', 'rb').read())\n"
|
|
383
|
+
" check('socket', lambda: socket.socket())\n"
|
|
384
|
+
" check('kill', lambda: os.kill(1, 0))\n"
|
|
385
|
+
" check('fork', lambda: os.fork())\n"
|
|
386
|
+
" check('subprocess', lambda: __import__('subprocess').run(['/bin/true']))\n"
|
|
387
|
+
" check('tmp_other', lambda: open('/tmp/not-mine', 'w'))\n"
|
|
388
|
+
" values = []\n"
|
|
389
|
+
" thread = threading.Thread(target=lambda: values.append(1))\n"
|
|
390
|
+
" thread.start(); thread.join()\n"
|
|
391
|
+
" out['thread'] = values\n"
|
|
392
|
+
" out['env'] = [k for k in os.environ if k.startswith('VLAMBDA_')]\n"
|
|
393
|
+
" return out\n"
|
|
394
|
+
),
|
|
395
|
+
})
|
|
396
|
+
status, body = req("GET", f"/f/{slug}")
|
|
397
|
+
assert status == 200, body
|
|
398
|
+
assert body.get("data") in ("PermissionError", "FileNotFoundError"), body
|
|
399
|
+
assert body.get("db") in ("PermissionError", "FileNotFoundError"), body
|
|
400
|
+
assert body.get("proc") == "PermissionError", body
|
|
401
|
+
assert body.get("socket") == "PermissionError", body
|
|
402
|
+
assert body.get("kill") == "PermissionError", body
|
|
403
|
+
assert body.get("fork") == "PermissionError", body
|
|
404
|
+
assert body.get("subprocess") == "PermissionError", body
|
|
405
|
+
assert body.get("tmp_other") == "PermissionError", body
|
|
406
|
+
assert body.get("thread") == [1], body
|
|
407
|
+
assert body.get("env") == [], body
|
|
408
|
+
finally:
|
|
409
|
+
stop_server()
|
|
410
|
+
|
|
411
|
+
|
|
354
412
|
def test_async_task():
|
|
355
413
|
token, slug = test_create_invoke()
|
|
356
414
|
status, body = req("POST", f"/async/{slug}")
|
|
@@ -534,7 +592,17 @@ def test_admin_reset():
|
|
|
534
592
|
assert status == 200
|
|
535
593
|
assert "rows" in body
|
|
536
594
|
status, body = req("GET", "/vlambda", token=token)
|
|
537
|
-
assert
|
|
595
|
+
assert status == 401
|
|
596
|
+
# A newly created user gets a new ID/epoch; the old token must stay invalid.
|
|
597
|
+
u = _unique_user()
|
|
598
|
+
status, body = req("POST", "/register", f"{u}:testpass")
|
|
599
|
+
assert status == 201, body
|
|
600
|
+
status, new_token = req("POST", "/login", f"{u}:testpass")
|
|
601
|
+
assert status == 200 and "token" in new_token
|
|
602
|
+
status, body = req("GET", "/vlambda", token=token)
|
|
603
|
+
assert status == 401
|
|
604
|
+
status, body = req("GET", "/vlambda", token=new_token["token"])
|
|
605
|
+
assert status == 200 and body.get("count") == 0
|
|
538
606
|
# Wrong token must not reset.
|
|
539
607
|
status, body = req("POST", "/admin/reset", extra_headers={"X-Admin-Token": "wrong"})
|
|
540
608
|
assert body.get("error") == "forbidden"
|
|
@@ -682,6 +750,7 @@ if __name__ == "__main__":
|
|
|
682
750
|
test_method_mismatch, test_pagination, test_ownership, test_project_zip,
|
|
683
751
|
test_isolated_projects,
|
|
684
752
|
test_nsjail_sandbox,
|
|
753
|
+
test_landlock_sandbox,
|
|
685
754
|
test_async_task, test_metrics_history, test_alias_version, test_metrics_stats,
|
|
686
755
|
test_sandbox_blocked, test_system_endpoints, test_admin_reset, test_bytes_result, test_request_body_echo, test_packages, test_metrics_aggregate_endpoint, test_lambda_logs, test_delete_metrics_and_logs,
|
|
687
756
|
test_cors_headers, test_json_listing, test_api_tokens, test_project_static_files,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|