vlambda 0.2.1__tar.gz → 0.2.2__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.
Files changed (30) hide show
  1. {vlambda-0.2.1 → vlambda-0.2.2}/PKG-INFO +15 -15
  2. {vlambda-0.2.1 → vlambda-0.2.2}/README.md +14 -14
  3. {vlambda-0.2.1 → vlambda-0.2.2}/pyproject.toml +1 -1
  4. {vlambda-0.2.1 → vlambda-0.2.2}/python/vlambda/__main__.py +5 -3
  5. {vlambda-0.2.1 → vlambda-0.2.2}/python/vlambda/pool.py +131 -2
  6. {vlambda-0.2.1 → vlambda-0.2.2}/python/vlambda/runner.py +36 -0
  7. vlambda-0.2.2/python/vlambda/sandbox_os.py +294 -0
  8. {vlambda-0.2.1 → vlambda-0.2.2}/tests/test_unit.py +7 -0
  9. {vlambda-0.2.1 → vlambda-0.2.2}/tests/test_vlambda.py +59 -0
  10. {vlambda-0.2.1 → vlambda-0.2.2}/vcraft.toml +1 -1
  11. {vlambda-0.2.1 → vlambda-0.2.2}/LICENSE +0 -0
  12. {vlambda-0.2.1 → vlambda-0.2.2}/python/vlambda/__init__.py +0 -0
  13. {vlambda-0.2.1 → vlambda-0.2.2}/python/vlambda/assets.py +0 -0
  14. {vlambda-0.2.1 → vlambda-0.2.2}/python/vlambda/auth.py +0 -0
  15. {vlambda-0.2.1 → vlambda-0.2.2}/python/vlambda/cache.py +0 -0
  16. {vlambda-0.2.1 → vlambda-0.2.2}/python/vlambda/dbpool.py +0 -0
  17. {vlambda-0.2.1 → vlambda-0.2.2}/python/vlambda/metrics.py +0 -0
  18. {vlambda-0.2.1 → vlambda-0.2.2}/python/vlambda/packages.py +0 -0
  19. {vlambda-0.2.1 → vlambda-0.2.2}/python/vlambda/project.py +0 -0
  20. {vlambda-0.2.1 → vlambda-0.2.2}/python/vlambda/py.typed +0 -0
  21. {vlambda-0.2.1 → vlambda-0.2.2}/python/vlambda/request.py +0 -0
  22. {vlambda-0.2.1 → vlambda-0.2.2}/python/vlambda/reset.py +0 -0
  23. {vlambda-0.2.1 → vlambda-0.2.2}/python/vlambda/sandbox.py +0 -0
  24. {vlambda-0.2.1 → vlambda-0.2.2}/python/vlambda/shared_cache.py +0 -0
  25. {vlambda-0.2.1 → vlambda-0.2.2}/python/vlambda/tasks.py +0 -0
  26. {vlambda-0.2.1 → vlambda-0.2.2}/python/vlambda/transfer.py +0 -0
  27. {vlambda-0.2.1 → vlambda-0.2.2}/src/vlambda_native.v +0 -0
  28. {vlambda-0.2.1 → vlambda-0.2.2}/tests/conftest.py +0 -0
  29. {vlambda-0.2.1 → vlambda-0.2.2}/v.mod +0 -0
  30. {vlambda-0.2.1 → vlambda-0.2.2}/vcraft_build.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: vlambda
3
- Version: 0.2.1
3
+ Version: 0.2.2
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** — lambdas are compiled once and cached in memory
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** — nsjail namespaces in Docker, plus restricted Python builtins and blocked modules
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 nsjail and expose plain
107
- HTTP on port `8080`; Dokploy (or another proxy) handles TLS and the public
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
- nsjail needs unprivileged user namespaces, so the container must run with
111
- `--security-opt seccomp=unconfined` (nsjail applies its own seccomp policy to
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 inside nsjail with a separate user, PID, mount and network
257
- namespace. The sandbox sees only `/opt` and the current project/vendor (read-only),
258
- has no access to `/data`, cannot read the server's `/proc`, and has no network.
259
- Resource limits and a seccomp deny-list are also applied. The server process and
260
- the database stay outside the sandbox.
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
@@ -298,7 +298,7 @@ For a disposable demo, run it from cron every day:
298
298
 
299
299
  | Metric | Value |
300
300
  |--------|-------|
301
- | Cold start | 0ms (persistent process) |
301
+ | Cold start | 0ms in persistent mode; fresh sandbox process in Docker |
302
302
  | Warm invocation | ~0.3ms |
303
303
  | Throughput (concurrent, free-threaded) | ~3,000 req/s |
304
304
  | 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** — lambdas are compiled once and cached in memory
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** — nsjail namespaces in Docker, plus restricted Python builtins and blocked modules
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 nsjail and expose plain
96
- HTTP on port `8080`; Dokploy (or another proxy) handles TLS and the public
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
- nsjail needs unprivileged user namespaces, so the container must run with
100
- `--security-opt seccomp=unconfined` (nsjail applies its own seccomp policy to
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 inside nsjail with a separate user, PID, mount and network
246
- namespace. The sandbox sees only `/opt` and the current project/vendor (read-only),
247
- has no access to `/data`, cannot read the server's `/proc`, and has no network.
248
- Resource limits and a seccomp deny-list are also applied. The server process and
249
- the database stay outside the sandbox.
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
@@ -287,7 +287,7 @@ For a disposable demo, run it from cron every day:
287
287
 
288
288
  | Metric | Value |
289
289
  |--------|-------|
290
- | Cold start | 0ms (persistent process) |
290
+ | Cold start | 0ms in persistent mode; fresh sandbox process in Docker |
291
291
  | Warm invocation | ~0.3ms |
292
292
  | Throughput (concurrent, free-threaded) | ~3,000 req/s |
293
293
  | Throughput (response cache hits) | ~100x faster |
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "vlambda"
3
- version = "0.2.1"
3
+ version = "0.2.2"
4
4
  authors = [{name = "Ricardo Robles Fernández"}]
5
5
  license = {text = "MIT"}
6
6
 
@@ -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
@@ -382,7 +384,7 @@ def main() -> None:
382
384
 
383
385
  def _run_project(project_dir, entrypoint, method, path, query, body):
384
386
  import json
385
- timeout = int(os.environ.get("VLAMBDA_INVOKE_TIMEOUT", "30"))
387
+ timeout = args.invoke_timeout
386
388
  try:
387
389
  result = pool.execute_project(project_dir, entrypoint, method, path, query, body, timeout=timeout)
388
390
  if isinstance(result, str):
@@ -481,8 +483,8 @@ def main() -> None:
481
483
  if args.max_memory_mb > 0:
482
484
  import threading, time, resource
483
485
  # A hard RLIMIT_AS for the whole process starves V/Python threads and
484
- # mmap. Use cgroups or the per-worker nsjail limits instead. It can be
485
- # enabled explicitly for constrained environments.
486
+ # mmap. Use the Docker cgroup or the per-invocation sandbox limits
487
+ # instead. It can be enabled explicitly for constrained environments.
486
488
  if os.environ.get("VLAMBDA_HARD_MEMORY_LIMIT", "0") == "1":
487
489
  limit_bytes = args.max_memory_mb * 1024 * 1024
488
490
  try:
@@ -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
- if os.environ.get("VLAMBDA_NSJAIL", "0") == "1":
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
@@ -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")
@@ -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}")
@@ -682,6 +740,7 @@ if __name__ == "__main__":
682
740
  test_method_mismatch, test_pagination, test_ownership, test_project_zip,
683
741
  test_isolated_projects,
684
742
  test_nsjail_sandbox,
743
+ test_landlock_sandbox,
685
744
  test_async_task, test_metrics_history, test_alias_version, test_metrics_stats,
686
745
  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
746
  test_cors_headers, test_json_listing, test_api_tokens, test_project_static_files,
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "vlambda"
3
- version = "0.2.1"
3
+ version = "0.2.2"
4
4
  module = "vlambda_native"
5
5
  description = "An ASGI-like server for Python lambdas, written in V."
6
6
  license = "MIT"
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