ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

Cloudflare Sandbox 实战指南:在 Workers 上安全跑不可信代码,8 个坑全部避开

Cloudflare Sandbox 实战指南:在 Workers 上安全跑不可信代码,8 个坑全部避开 Cloudflare Sandbox 实战指南在 Workers 上安全跑不可信代码8 个坑全部避开【免费下载链接】skillsSkills Catalog for Codex项目地址: https://gitcode.com/GitHub_Trending/skills4/skills如果你的业务要在 Workers 上执行用户提交的代码或者想给 AI Agent 一个能跑 Python、出图表的环境但又不想自己养一堆虚拟机Cloudflare Sandbox 就是干这个的每个沙箱都是边缘上的一个安全容器文件系统、进程、网络互相隔离相同 ID 的请求永远落在同一个沙箱里。最小可跑版本也就十来行import { getSandbox, proxyToSandbox, type Sandbox } from cloudflare/sandbox; export { Sandbox } from cloudflare/sandbox; // 供 Durable Object 注册用 export default { async fetch(request, env) { // 预览 URL 请求必须先转发这是硬性要求 const proxied await proxyToSandbox(request, env); if (proxied) return proxied; const sandbox getSandbox(env.Sandbox, demo); const result await sandbox.exec(python3 -c print(2 2)); return Response.json({ output: result.stdout }); } };先把沙箱跑起来3 步配好容器绑定沙箱的本质是一对Durable Object 负责身份和状态容器负责干活。所以 wrangler.jsonc 里要配三处——containers 告诉 Workers 用什么镜像、什么规格durable_objects.bindings 声明 Sandbox 命名空间migrations 登记 DO 类。配完之后getSandbox 首次调用就会拉镜像起容器{ name: my-sandbox-worker, main: src/index.ts, compatibility_date: 2025-01-01, // 新项目直接写当天日期 containers: [{ class_name: Sandbox, image: ./Dockerfile, instance_type: lite, // 三档规格lite / standard / heavy max_instances: 5 }], durable_objects: { bindings: [{ class_name: Sandbox, name: Sandbox }] }, migrations: [{ tag: v1, new_sqlite_classes: [Sandbox] }] }规格按内存需求选数据类任务起步建议 standard规格内存vCPUlite默认256MB0.5standard512MB1heavy1GB2镜像基于官方沙箱基镜像构建只装你想预置的依赖即可FROM docker.io/cloudflare/sandbox:latest RUN pip3 install --no-cache-dir pandas numpy matplotlib EXPOSE 8080 3000 # 本地 wrangler dev 调试必须写⚠️ EXPOSE 这一行最容易漏本地跑 wrangler dev 时端口访问依赖它漏了会报connection refused: container port not found。生产环境不用操心所有端口会自动暴露。日常开发和运维就靠这五条命令wrangler dev # 本地开发服务器 wrangler deploy # 部署到生产 wrangler tail # 实时查看日志 wrangler containers list # 检查容器状态 wrangler secret put GITHUB_TOKEN # 存密钥用法见出错时怎么办两个时间数字要提前有心理预期首次部署构建镜像约 2~3 分钟沙箱休眠后再被请求冷启动约 2~3 秒。日志级别和格式可以环境变量控制{ vars: { SANDBOX_LOG_LEVEL: debug, // debug | info | warn | error默认 info SANDBOX_LOG_FORMAT: pretty // json | pretty默认 json } }本地调试建议 debug pretty生产建议 info/warn json排查问题效率差很多。往容器里扔代码先跑通第一条命令exec 是出场率最高的方法用法很直白const result await sandbox.exec(python3 script.py); // 返回{ stdout, stderr, exitCode, success, duration }五个字段分别是标准输出、标准错误、退出码、是否成功退出码为 0、执行耗时。要注意命令跑挂了和API 调用失败是两回事前者不抛异常只给你 success: false后者才会抛带 error.code 的异常后面出错时怎么办一节细讲。最常用的是这三个选项await sandbox.exec(python3 test.py, { cwd: /workspace/project, // 容器内工作目录 env: { API_KEY: secret }, // 注入到这条命令进程的环境变量 stream: true, // 开启流式输出 onOutput: (stream, data) console.log(data) // 边跑边打日志 });cwd 决定命令在容器哪个目录执行构建、测试类任务基本都要指定env 是往沙箱传密钥的推荐通道stream onOutput 适合 npm install 这种耗时命令你能实时看到安装进度而不是干等。exec 默认超时 120 秒长任务怕拖死请求就显式覆盖const result await sandbox.exec(python3 script.py, { timeout: 30000 // 覆盖默认 120 秒 });先写文件再执行防命令注入⚠️ exec 收到的是 shell 字符串把用户输入直接拼进去等于把整个容器交出去// 危险写法userCode 里带个引号就能逃逸执行任意命令 const bad await sandbox.exec(python3 -c ${userCode}); // 安全写法先写文件再执行文件 await sandbox.writeFile(/workspace/user_code.py, userCode); const good await sandbox.exec(python3 /workspace/user_code.py);这条原则对所有【免费下载链接】skillsSkills Catalog for Codex项目地址: https://gitcode.com/GitHub_Trending/skills4/skills创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表