A secure Python sandbox with a rich scientific stack for WebAssembly.
Project details
wasi-python provides a statically linked CPython 3.15 compiled for WebAssembly, encapsulating a comprehensive scientific stack that includes numpy, pandas, and more. Designed for executing untrusted code in secure environments, it ensures isolation from the host system while delivering full Python functionality, all within an easily deployable single binary.
wasi-python provides a secure, statically linked implementation of CPython (version 3.15) compiled to WebAssembly, designed specifically for hosting untrusted agent-generated code server-side within web applications. This unique solution seamlessly integrates popular scientific libraries such as numpy, pandas, scipy, and scikit-learn, enabling developers to run complex data processing tasks without risking the integrity of the host system.
Experience the full power of the scientific stack within a safe environment. The following code snippet showcases how to analyze noisy signals, perform curve fitting, and cluster data:
from wasi_python import run
code = """
import numpy as np
import pandas as pd
from scipy import optimize
from sklearn.cluster import KMeans
rng = np.random.default_rng(7)
t = np.linspace(0, 5, 200)
signal = np.sin(2 * np.pi * 3 * t) + rng.normal(0, 0.3, t.size)
freqs = np.fft.rfftfreq(t.size, d=t[1] - t[0])
print(f"dominant frequency: {freqs[np.abs(np.fft.rfft(signal)).argmax()]:.1f} Hz")
(a, k), _ = optimize.curve_fit(lambda t, a, k: a * np.exp(-k * t), t, 3 * np.exp(-0.7 * t) + rng.normal(0, 0.1, t.size))
print(f"decay fit: a={a:.2f} k={k:.2f}")
points = np.vstack([c + rng.normal(0, 0.5, (100, 2)) for c in ([1, 1], [5, 5], [1, 5])])
labels = KMeans(n_clusters=3, n_init=10, random_state=0).fit_predict(points)
print(pd.DataFrame(points, columns=["x", "y"]).groupby(labels).mean().round(1))
"""
done = run(["-c", code])
print(done.stdout.decode())
Designed to execute potentially harmful code safely, wasi-python enforces strict isolation. By default, the sandbox cannot access the host filesystem or network. Here’s how to handle permissions within the sandbox:
import shutil
from pathlib import Path
from wasi_python import Grant, run
for name in ("wasi_python_shared", "wasi_python_private"):
Path(name).mkdir(exist_ok=True)
(Path(name) / "hello.txt").write_text(f"hello from {name}\n")
code = """
for path in ("/shared/hello.txt", "/private/hello.txt", "/shared/../private/hello.txt"):
try:
print(path, "->", open(path).read().strip())
except OSError as e:
print(path, "->", type(e).__name__)
try:
open("/shared/notes.txt", "w")
except OSError as e:
print("write to /shared ->", type(e).__name__)
"""
done = run(["-c", code], grants=[Grant("wasi_python_shared", "/shared")])
print(done.stdout.decode())
Incorporate specialized functions directly into the guest environment via tools. Here’s an example of exposing a price lookup function:
from wasi_python import run
from wasi_python.tools import tool
PRICES = {"apple": 0.5, "pear": 0.8}
@tool(read_only=True)
def price(item: str) -> float:
return PRICES[item]
code = """
from host import tools
basket = {"apple": 6, "pear": 3}
print("total", sum(tools.price(name) * n for name, n in basket.items()))
try:
tools.price("plum")
except Exception as e:
print("plum ->", e)
"""
done = run(["-c", code], tools=[price])
print(done.stdout.decode())
Sessions allow persistent context across multiple interactions:
from wasi_python import Session
with Session() as session:
session.run("import numpy as np; x = np.random.default_rng(1).normal(size=10_000)")
print(session.run("print(round(float(x.mean()), 3), round(float(x.std()), 3))").stdout.decode())
Support for async operations is built-in, enabling multiple guests to run concurrently while retaining responsiveness:
import asyncio
from wasi_python import run_async
async def main():
guests = [run_async(["-c", f"import time; time.sleep(1); print('guest {n} done')"]) for n in range(3)]
results = await asyncio.gather(*guests)
for done in results:
print(done.stdout.decode().strip())
asyncio.run(main())
wasi-python offers a groundbreaking approach to executing Python code securely in a WebAssembly environment, integrating essential scientific libraries while safeguarding the host system. Its focus on security, ease of use, and expandability makes it an invaluable tool for developers looking to integrate Python into web applications.
Comments
0Start the conversation
Share the first comment.