Spaces:
Sleeping
Sleeping
Commit Β·
d2a4863
1
Parent(s): 98d1f5d
Auto-commit: README.md updated
Browse files121245634891056121314781617189101121222312242513141529301617333435183637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826919202122232425262722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165172728293031323352052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556634353637385685695705715725733940575576577578579580581582583584585586587588589590591592593414243595596597598444546600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638474849640641505152643644645646647648649650651652653654655656535465855565758596606616626636646656061667668669670671626364656667686736746756766776970679717273747576777868168268368479806866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677688182837718477385868788775899091------------
ο»Ώ---title: Landrun Sandbox + Browser Automation
emoji: πtitle: Landrun Sandbox + Browser Automation
emoji: πcolorFrom: purple
colorTo: blueemoji: πtitle: Landrun Sandbox + Browser Automationtitle: Docker Sandbox
colorTo: bluesdk: docker
app_file: app.pycolorFrom: purple
app_file: app.pypinned: false
license: mitcolorTo: blueemoji: ππemoji: π³
license: mit---
sdk: docker
# π Landrun Sandbox + Browser Automation# Landrun Sandbox + Browser Automation
app_file: app.pycolorFrom: purplecolorFrom: blue
**Kernel-Level Code Execution Sandbox with Automated UI Testing**
pinned: false
Execute code with maximum security using **Landrun** (Linux Landlock kernel security) and automatically test UIs with **Playwright** browser automation.
license: mitcolorTo: bluecolorTo: purple
## β¨ Features## Features
---
### π Landrun Security
sdk: dockersdk: docker
- **Kernel-level isolation** using Linux Landlock LSM
- **Zero-trust execution** with restricted filesystem access# π Landrun Sandbox + Browser Automation
- **Read-only system files** - only `/tmp/sandbox` is writable
- **Network restrictions** - only HTTP/HTTPS allowedpinned: truepinned: false
- **10-second timeout** protection
**Kernel-Level Code Execution Sandbox with Automated UI Testing**
### π Browser Automation
license: mitlicense: mit
- **Playwright Chromium** for automated UI testing
- **Screenshot capture** before/after actionsExecute code with maximum security using **Landrun** (Linux Landlock kernel security) and automatically test UIs with **Playwright** browser automation.
- **Element interaction** - click, type, wait, get text
- **One-shot API** - execute code β test UI β get results------
### π Supported Languages## β¨ Features
- **Python 3.11** - with stdlib + compilers (gcc, g++)
- **JavaScript (Node.js)** - server-side execution
- **React (JSX)** - client-side components with live preview### π Landrun Security
- **HTML + CSS** - static pages with full styling
- **Kernel-level isolation** using Linux Landlock LSM# π Landrun Sandbox + Browser Automation# π³ Docker Sandbox Executor
## π‘ API Endpoints
- **Zero-trust execution** with restricted filesystem access
### 1. Execute Code
- **Read-only system files** - only `/tmp/sandbox` is writable
```bash
POST /execute- **Network restrictions** - only HTTP/HTTPS allowed
Content-Type: application/json
- **10-second timeout** protection**Kernel-Level Code Execution Sandbox + Automated UI Testing****Secure code execution in isolated Docker containers**
{
"language": "react",
"code": "export default function App() { return <h1>Hello!</h1>; }"
}### π Browser Automation
```
- **Playwright Chromium** for automated UI testing
### 2. Get Live Preview
- **Screenshot capture** before/after actionsExecute code with maximum security using **Landrun** (Linux Landlock kernel security) and automatically test UIs with **Playwright** browser automation.## Features
```bash
GET /preview/{uuid}- **Element interaction** - click, type, wait, get text
```
- **One-shot API** - execute code β test UI β get results
### 3. Test UI with Browser
```bash
POST /browser/test### π Supported Languages## β¨ Featuresβ
**Isolated execution** - Each code run in separate container
Content-Type: application/json
- **Python 3.11** - with stdlib + compilers (gcc, g++)
{
"preview_url": "/preview/uuid",- **JavaScript (Node.js)** - server-side executionβ
**Resource limits** - 256MB RAM, 50% CPU per execution
"actions": [
{"type": "click", "selector": "button"},- **React (JSX)** - client-side components with live preview
{"type": "screenshot"}
]- **HTML + CSS** - static pages with full styling### π Landrun Securityβ
**Network disabled** - Maximum security
}
```
### 4. Execute + Test (One-Shot)## π‘ API Endpoints- **Kernel-level isolation** using Linux Landlock LSMβ
**Auto-cleanup** - Containers destroyed after execution
```bash
POST /browser/execute_and_test
Content-Type: application/json### 1. Execute Code- **Zero-trust execution** with restricted filesystem accessβ
**Multiple languages** - Python, JavaScript, React, HTML
{```bash
"language": "react",
"code": "export default function App() { return <button>Click</button>; }",POST /execute- **Read-only system files** - only `/tmp/sandbox` is writable
"actions": [
{"type": "click", "selector": "button"},Content-Type: application/json
{"type": "screenshot"}
]- **Network restrictions** - only HTTP/HTTPS allowed## Architecture
}
```{
## π― Quick Start "language": "react",- **10-second timeout** protection
### Python Example "code": "export default function App() { return <h1>Hello!</h1>; }"
```python}```
import requests
```
response = requests.post(
"https://speedofmastery-hmm.hf.space/browser/execute_and_test",### π Browser Automationβββββββββββββββββββββββββββββββββββββββββββββββββββββββ
json={
"language": "react",### 2. Get Live Preview
"code": """
export default function App() {```bash- **Playwright Chromium** for automated UI testingβ Hugging Face Space (Docker SDK) β
const [count, setCount] = React.useState(0);
return (GET /preview/{uuid}
<div>
<h1>Count: {count}</h1>```- **Screenshot capture** before/after actionsβ β
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}### 3. Test UI with Browser- **Element interaction** - click, type, waitβ ββββββββββββββββββββββββββββββββββββββββββββββββ β
""",
"actions": [```bash
{"type": "click", "selector": "button"},
{"type": "screenshot"}POST /browser/test- **Text extraction** from elementsβ β FastAPI Server (app_docker.py) β β
]
}Content-Type: application/json
)
- **One-shot API** - execute code β test UI β get resultsβ β β β
result = response.json()
print(result['status']) # 'success'{
```
"preview_url": "/preview/uuid",β β ββββββββββββββββββββββββββββββββββββββββββ β β
## π Security
"actions": [
- **Landrun Sandbox:** Kernel-level isolation using Linux Landlock
- **Read-only:** `/usr`, `/lib`, `/etc` are read-only {"type": "click", "selector": "button"},### π Supported Languagesβ β β Docker Engine (in Space) β β β
- **Writable:** Only `/tmp/sandbox` is writable
- **Network:** TCP ports 80, 443 only {"type": "screenshot"}
- **Timeout:** 10 seconds max execution
- **Browser:** Headless Chromium with 5s action timeout ]- **Python 3.11** - with stdlib + compilersβ β β β β β
## π οΈ Technology Stack}
### Landrun Security- Kernel-level isolation using Linux Landlock LSM- Zero-trust execution with restricted filesystem access- Read-only system files - only /tmp/sandbox is writable- Network restrictions - only HTTP/HTTPS allowed- 10-second timeout protection
- **Landrun**: Go-based Linux Landlock sandbox```- **JavaScript (Node.js)** - server-side executionβ β β ββββββββββββββββ ββββββββββββββββ β β β
- **FastAPI**: Modern async Python web framework
- **Playwright**: Browser automation framework
- **Chromium**: Headless browser engine
- **Docker**: Multi-stage container build### 4. Execute + Test (One-Shot)- **React (JSX)** - client-side components with live previewβ β β β Python:3.11 β β Node:18 β β β β
- **Python 3.11**: Runtime environment with compilers
- **Node.js**: JavaScript execution```bash
## π Browser ActionsPOST /browser/execute_and_test- **HTML + CSS** - static pages with full stylingβ β β β Container β β Container β β β β
| Action | Description |Content-Type: application/json
|--------|-------------|
| `click` | Click element by selector |β β β β β β β β β β
| `type` | Type text into input field |
| `get_text` | Extract text from element |{
| `wait` | Wait for element to appear |
| `screenshot` | Capture screenshot (base64) | "language": "react",## π‘ API Endpointsβ β β β β’ 256MB RAM β β β’ 256MB RAM β β β β
## π License "code": "export default function App() { return <button>Click</button>; }",
MIT License - Free to use and modify "actions": [β β β β β’ 50% CPU β β β’ 50% CPU β β β β
## π Links {"type": "click", "selector": "button"},
- **Live Demo:** [speedofmastery-hmm.hf.space](https://speedofmastery-hmm.hf.space) {"type": "screenshot"}### POST /execute - Execute Code with Landrunβ β β β β’ No Network β β β’ No Network β β β β
- **Landrun GitHub:** [github.com/zouuup/landrun](https://github.com/zouuup/landrun)
- **Playwright Docs:** [playwright.dev](https://playwright.dev) ]
}### GET /preview/{uuid} - Get Live Preview β β β ββββββββββββββββ ββββββββββββββββ β β β
```
### POST /browser/test - Test UI with Browserβ β βββββββββββββββββββββββββββββββοΏ½οΏ½ββββββββββ β β
## π― Quick Start
### POST /browser/execute_and_test - One-Shot Execute + Testβ ββββββββββββββββββββββββββββββββββββββββββββββββ β
### Python Example
```pythonβββββββββββββββββββββββββββββββββββββββββββββββββββββββ
import requests
Full API documentation available at the Space URL.```
response = requests.post(
"https://speedofmastery-hmm.hf.space/browser/execute_and_test",
json={
"language": "react",## π Quick Start## Security Features
"code": """
export default function App() {
const [count, setCount] = React.useState(0);
return (Visit: **https://speedofmastery-hmm.hf.space**### π‘οΈ Container Isolation
<div>
<h1>Count: {count}</h1>- Each execution runs in a **separate Docker container**
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>## π License- Containers are **destroyed after execution**
);
}- **No persistent storage** between executions
""",
"actions": [MIT License
{"type": "click", "selector": "button"},
{"type": "screenshot"}### π« Resource Limits
]- **Memory**: 256MB per container
}- **CPU**: 50% of one core
)- **Timeout**: 30 seconds default
- **Network**: Disabled (network_mode="none")
result = response.json()
print(result['status']) # 'success'### π Security Constraints
```- **No root access** in containers
- **No file system persistence**
## π Security- **No network access**
- **Automatic cleanup** after execution
- **Landrun Sandbox:** Kernel-level isolation using Linux Landlock
- **Read-only:** `/usr`, `/lib`, `/etc` are read-only## Hugging Face Space Configuration
- **Writable:** Only `/tmp/sandbox` is writable
- **Network:** TCP ports 80, 443 only### Required Space Settings
- **Timeout:** 10 seconds max execution
- **Browser:** Headless Chromium with 5s action timeout#### 1. SDK
```yaml
## π οΈ Technology Stacksdk: docker
```
- **Landrun**: Go-based Linux Landlock sandbox
- **FastAPI**: Modern async Python web framework#### 2. Dockerfile.sandbox
- **Playwright**: Browser automation frameworkUse the provided `Dockerfile.sandbox` which includes:
- **Chromium**: Headless browser engine- Python 3.11 base
- **Docker**: Multi-stage container build- Node.js for React/JavaScript
- **Python 3.11**: Runtime environment with compilers- Docker-in-Docker (DinD) support
- **Node.js**: JavaScript execution- Non-root user execution
## π Browser Actions#### 3. Requirements
```txt
| Action | Description |fastapi
|--------|-------------|uvicorn[standard]
| `click` | Click element by selector |docker
| `type` | Type text into input field |pydantic
| `get_text` | Extract text from element |```
| `wait` | Wait for element to appear |
| `screenshot` | Capture screenshot (base64) |## Deployment Steps
## π License### Step 1: Create Hugging Face Space
```bash
MIT License - Free to use and modify# Create new space with Docker SDK
# Name: your-docker-sandbox
## π Links# SDK: Docker
```
- **Live Demo:** [speedofmastery-hmm.hf.space](https://speedofmastery-hmm.hf.space)
- **Landrun GitHub:** [github.com/zouuup/landrun](https://github.com/zouuup/landrun)### Step 2: Upload Files
- **Playwright Docs:** [playwright.dev](https://playwright.dev)```bash
python deploy_docker_space.py```
Or manually:```bash# Clone your spacegit clone https://huggingface.co/spaces/YOUR_USERNAME/your-docker-sandboxcd your-docker-sandbox
# Copy filescp Dockerfile.sandbox Dockerfilecp app_docker.py app.pycp requirements.txt .
# Add READMEcp README_DOCKER.md README.md
# Commit and pushgit add .git commit -m "Deploy Docker sandbox"git push```
### Step 3: Enable Docker in Space Settings1. Go to Space Settings2. Under "Advanced", enable **"Docker SDK"**3. Set **"Timeout"** to 60+ seconds4. Save settings
## API Usage
### Endpoint```POST https://YOUR_USERNAME-your-docker-sandbox.hf.space/execute```
### Request Format```json{ "language": "python", "code": "print('Hello from Docker!')", "timeout": 30}```### Browser Automation- Playwright Chromium for automated UI testing- Screenshot capture before/after actions- Element interaction - click, type, wait, get text- One-shot API - execute code and test UI in single call
### Supported Languages- `python` - Python 3.11 in Alpine container- `javascript` - Node.js 18 in Alpine container- `react` - Client-side React (no container needed)- `html` - Pure HTML (no container needed)
### Response Format```json{ "status": "success", "preview_url": "data:text/html;base64,...", "terminal_view_url": "data:text/html;base64,...", "execution_time": 0.234, "docker_enabled": true}```
## Example: Python Code Execution
### PowerShell```powershell$apiUrl = "https://YOUR_USERNAME-your-docker-sandbox.hf.space/execute"
$code = @"import sysprint(f'Python {sys.version}')print('Running in Docker container!')for i in range(5): print(f'Count: {i}')"@
$body = @{ language = "python" code = $code timeout = 30} | ConvertTo-Json
$response = Invoke-RestMethod -Uri $apiUrl -Method Post -Body $body -ContentType "application/json"
# Display terminal output$terminalHtml = "<html><body><iframe src='$($response.terminal_view_url)' style='width:100%;height:100vh;border:none;'></iframe></body></html>"$terminalHtml | Out-File -FilePath "docker_terminal.html"Start-Process "docker_terminal.html"```
### JavaScript (Node.js)```javascriptconst apiUrl = "https://YOUR_USERNAME-your-docker-sandbox.hf.space/execute";- Python 3.11 with stdlib + compilers- JavaScript Node.js server-side execution- React JSX client-side components with live preview- HTML + CSS static pages with full styling
const code = `console.log('Node.js in Docker!');console.log('Environment:', process.version);const data = [1, 2, 3, 4, 5];console.log('Sum:', data.reduce((a, b) => a + b, 0));`;## API Endpoints
fetch(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ language: 'javascript', code: code, timeout: 30 })}).then(res => res.json()).then(data => { console.log('Execution time:', data.execution_time); // Open terminal view const iframe = document.createElement('iframe'); iframe.src = data.terminal_view_url; iframe.style = 'width:100%;height:100vh;border:none;'; document.body.appendChild(iframe);});```### POST /executeExecute code in sandbox and get preview URL
### React Example```javascriptconst reactCode = `const { useState } = React;### GET /preview/{uuid}Get live HTML preview of executed code
function Counter() { const [count, setCount] = useState(0); return ( <div style={{ padding: '40px', textAlign: 'center', fontFamily: 'Arial' }}> <h1 style={{ fontSize: '48px', color: '#667eea' }}>Counter: {count}</h1> <button onClick={() => setCount(count + 1)} style={{ padding: '15px 30px', fontSize: '20px', background: '#667eea', color: 'white', border: 'none', borderRadius: '10px', cursor: 'pointer', margin: '10px' }} > Increment </button> <button onClick={() => setCount(count - 1)} style={{ padding: '15px 30px', fontSize: '20px', background: '#764ba2', color: 'white', border: 'none', borderRadius: '10px', cursor: 'pointer', margin: '10px' }} > Decrement </button> </div> );}### POST /browser/testTest existing preview with browser automation
ReactDOM.render(<Counter />, document.getElementById('root'));`;### POST /browser/execute_and_testExecute code and test UI in single call (one-shot)
fetch(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ language: 'react', code: reactCode })}).then(res => res.json()).then(data => { // React runs client-side, so preview_url contains the full app window.open(data.preview_url, '_blank');});```## Quick Start
## Advantages of Docker SandboxPython example:- Execute React code with browser automation- Click buttons and capture screenshots- Get test results with base64 screenshots
### β
vs Regular Hugging Face Spaces1. **Complete Isolation** - Each execution is fully isolated2. **Resource Control** - Strict memory and CPU limits3. **No Contamination** - Containers destroyed after use4. **Multiple Runtimes** - Python, Node, Ruby, etc. in separate containers5. **Security** - No network, no persistence, no escape## Security
### β
vs Local Sandboxie1. **Cloud-Native** - No local installation needed2. **Always Available** - 24/7 API access3. **Scalable** - Handles multiple concurrent requests4. **Platform Independent** - Works from any device- Landrun Sandbox: Kernel-level isolation using Linux Landlock- Read-only: /usr, /lib, /etc are read-only- Writable: Only /tmp/sandbox is writable- Network: TCP ports 80, 443 only- Timeout: 10 seconds max execution- Browser: Headless Chromium with 5s action timeout
### β
vs Process-Based Execution1. **Better Isolation** - Container vs process boundaries2. **Cleaner Cleanup** - No orphaned processes3. **Reproducible** - Same environment every time4. **Safer** - Can't access host filesystem## Technology Stack
## Monitoring- Landrun: Go-based Linux Landlock sandbox- FastAPI: Modern async Python web framework- Playwright: Browser automation framework- Chromium: Headless browser engine- Docker: Multi-stage container build- Python 3.11: Runtime environment with compilers- Node.js: JavaScript execution
### Health Check```bashcurl https://YOUR_USERNAME-your-docker-sandbox.hf.space/health```## Browser Actions
Response:```json{ "status": "healthy", "docker_available": true}```
### Container StatsThe Docker executor automatically:- Removes containers after execution- Logs container lifecycle events- Tracks resource usage- Enforces timeouts
## Troubleshooting
### "Docker not available"**Solution**: Ensure Space is using Docker SDK:1. Space Settings β SDK β Select "Docker"2. Wait for rebuild3. Check `/health` endpoint
### Execution Timeout**Solution**: Increase timeout in request:```json{ "language": "python", "code": "...", "timeout": 60}```
### Container Memory Error**Solution**: Optimize code or contact HF support for higher limits
### Network Errors in Container**Expected**: Containers have `network_mode="none"` for security- React/HTML work because they run **client-side**- Python/JavaScript run **server-side** without network
## Performance
### Typical Execution Times- **Python simple**: ~0.5-1s (container startup + execution)- **JavaScript simple**: ~0.6-1.2s- **React**: ~0.1s (client-side, no container)- **HTML**: ~0.05s (client-side, no container)
### Cold StartFirst execution may take 2-5 seconds to pull Docker images.
## Best Practices
### 1. Choose Right Language- Use **React/HTML** for UI apps (faster, client-side)- Use **Python/JavaScript** for computation (secure, isolated)
### 2. Optimize Code- Keep execution time under 10 seconds- Avoid heavy computations in containers- Use React for interactive UIs
### 3. Handle Errors```javascripttry { const response = await fetch(apiUrl, { ... }); const data = await response.json(); if (data.status === 'error') { console.error('Execution failed'); }} catch (error) { console.error('API error:', error);}```
## Future Enhancements
- [ ] Multi-language containers (Go, Rust, Ruby)- [ ] Custom Docker images- [ ] Volume mounting for data- [ ] WebSocket for real-time output- [ ] GPU support for ML workloadsAvailable actions: click, type, get_text, wait, screenshot
## LicenseMIT License - Feel free to use and modify!
---MIT License
## Links
**Questions?** Open an issue or discussion on the Space!- Live Demo: https://speedofmastery-hmm.hf.space- Landrun GitHub: https://github.com/zouuup/landrun- Playwright Docs: https://playwright.devREADME.md+59-743