Spaces:
Sleeping
Sleeping
Commit Β·
d2a4863
1
Parent(s): 98d1f5d
Auto-commit: README.md updated
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775------------title: Landrun Sandbox + Browser Automationemoji: πtitle: Landrun Sandbox + Browser AutomationcolorFrom: purplecolorTo: blueemoji: πtitle: Landrun Sandbox + Browser Automationtitle: Docker Sandboxsdk: dockerapp_file: app.pycolorFrom: purplepinned: falselicense: mitcolorTo: blueemoji: ππemoji: π³---sdk: docker# π Landrun Sandbox + Browser Automationapp_file: app.pycolorFrom: purplecolorFrom: blue**Kernel-Level Code Execution Sandbox with Automated UI Testing**pinned: falseExecute code with maximum security using **Landrun** (Linux Landlock kernel security) and automatically test UIs with **Playwright** browser automation.license: mitcolorTo: bluecolorTo: purple## β¨ Features---### π Landrun Securitysdk: 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 Automationlicense: 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```bashPOST /execute- **Network restrictions** - only HTTP/HTTPS allowedContent-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```bashGET /preview/{uuid}- **Element interaction** - click, type, wait, get text```- **One-shot API** - execute code β test UI β get results### 3. Test UI with Browser```bashPOST /browser/test### π Supported Languages## β¨ Featuresβ **Isolated execution** - Each code run in separate containerContent-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```bashPOST /browser/execute_and_testContent-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**: 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 requestsFull 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```bashMIT 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)```bashpython 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}```### 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 = $codetimeout = 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";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));`;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 viewconst iframe = document.createElement('iframe');iframe.src = data.terminal_view_url;iframe.style = 'width:100%;height:100vh;border:none;';document.body.appendChild(iframe);});```### React Example```javascriptconst reactCode = `const { useState } = React;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><buttononClick={() => setCount(count + 1)}style={{padding: '15px 30px',fontSize: '20px',background: '#667eea',color: 'white',border: 'none',borderRadius: '10px',cursor: 'pointer',margin: '10px'}}>Increment</button><buttononClick={() => setCount(count - 1)}style={{padding: '15px 30px',fontSize: '20px',background: '#764ba2',color: 'white',border: 'none',borderRadius: '10px',cursor: 'pointer',margin: '10px'}}>Decrement</button></div>);}ReactDOM.render(<Counter />, document.getElementById('root'));`;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 appwindow.open(data.preview_url, '_blank');});```## Advantages of Docker Sandbox### β 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### β 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### β 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## Monitoring### Health Check```bashcurl https://YOUR_USERNAME-your-docker-sandbox.hf.space/health```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 workloads## LicenseMIT License - Feel free to use and modify!---**Questions?** Open an issue or discussion on the Space!12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091ο»Ώ---title: Landrun Sandbox + Browser Automationemoji: πcolorFrom: purplecolorTo: bluesdk: dockerapp_file: app.pypinned: falselicense: mit---# Landrun Sandbox + Browser Automation**Kernel-Level Code Execution Sandbox with Automated UI Testing**Execute code with maximum security using **Landrun** (Linux Landlock kernel security) and automatically test UIs with **Playwright** browser automation.## Features### 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### 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 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## API Endpoints### POST /executeExecute code in sandbox and get preview URL### GET /preview/{uuid}Get live HTML preview of executed code### POST /browser/testTest existing preview with browser automation### POST /browser/execute_and_testExecute code and test UI in single call (one-shot)## Quick StartPython example:- Execute React code with browser automation- Click buttons and capture screenshots- Get test results with base64 screenshots## Security- 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## Technology Stack- 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## Browser ActionsAvailable actions: click, type, get_text, wait, screenshot## LicenseMIT License## Links- Live Demo: https://speedofmastery-hmm.hf.space- Landrun GitHub: https://github.com/zouuup/landrun- Playwright Docs: https://playwright.dev
README.md+59-743