Repository navigation
feat(worker): functions shim for Vercel api/ parity - #101
Conversation
Static projects that ship an api/ directory previously 405'd every
/api/* request. The build now stages handler sources into /fn and,
when present, builds a second image: node:24-alpine + esbuild bundling
each api/*.{js,ts,mjs,cjs} handler to CJS, served by an embedded
node:http dispatcher that exposes Vercel's (req,res) contract —
res.status/json/send/redirect, req.query, parsed JSON body, [param]
and [...rest] dynamic segments, api/index.* at /api.
Static assets keep serving under / from the same container, so the
shim needs no second route or network. Remote executor nodes get the
same treatment via the existing download_container_dir pull-back.
Also fixes wait_exit: the daemon's wait endpoint can return an error
body for a container that already exited (seen after a Docker Desktop
restart); fall back to inspect_container — State.ExitCode is
authoritative. And the lockfile-copy loop no longer leaks a failing
test status into the build container's exit code.
Verified live: github-e2e deployment builds the shim, serves the
static index at /, and answers /api/hello (JS, query+method), a TS
handler bundled by esbuild, and /api/user/42 via [id].
Affects bets: single binary, frontend-first (one container, one domain).
Jarvis ceiling: shared process, not per-function isolation — upgrade to
isolated cold-start runtimes when resource accounting lands.
Generated with [Devin](https://devin.ai)
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Mira PR WalkthroughAdds Vercel-style graph LR
deploy["crates/worker/src/deploy.rs"]
manifest["Cargo.toml"]
roadmap["ROADMAP.md"]
agents["docs/agents.md"]
integration["docs/integration-roadmap.md"]
manifest --> deploy
deploy --> roadmap
deploy --> agents
deploy --> integration
5 files reviewed · 3 comments (
|
Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
… batch Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
259646c to
639a310
Compare
| // tokens never do — they were only ever needed for the fetch. | ||
| let fn_serve_env: Vec<String> = env | ||
| .iter() | ||
| .filter(|e| !e.starts_with("RUNWAY_GITHUB_TOKEN=") && !e.starts_with("RUNWAY_GIT_TOKEN=")) |
There was a problem hiding this comment.
Security issue
Hardcoded credential assignment in diff
Deterministic scan found a credential assignment on the added line. Rotate/remove this key and move it to a secret store. Confidence 0.9.
Prompt for AI Agents
In crates/worker/src/deploy.rs:803, remove the credential assignment and load it from the environment/secret manager instead of the source.
Not useful? Reply
@mira-tdvorak rejectto dismiss this suggestion.
| COPY api/ /w/ | ||
| RUN (npm ci --omit=dev || npm install --omit=dev || true) \ | ||
| && files=$(find . -path ./node_modules -prune -o -type f \ |
There was a problem hiding this comment.
Security issue
Open redirect via res.redirect in functions shim
res.redirect sets the location header to an arbitrary user-supplied value with no validation. A handler can redirect to https://evil.com or javascript: URIs, enabling phishing/open-redirect attacks. While handlers are user-deployed code, the shim is a shared infrastructure component and should not blindly forward redirect targets without at least same-origin or relative-path enforcement.
| COPY api/ /w/ | |
| RUN (npm ci --omit=dev || npm install --omit=dev || true) \ | |
| && files=$(find . -path ./node_modules -prune -o -type f \ | |
| res.redirect = (a, b) => { | |
| const code = typeof a === 'number' ? a : 307, loc = typeof a === 'number' ? b : a; | |
| // Only allow relative redirects or same-origin absolute URLs | |
| const isRelative = typeof loc === 'string' && loc.startsWith('/') && !loc.startsWith('//'); | |
| const isSameOrigin = typeof loc === 'string' && (() => { try { return new URL(loc, 'http://x').origin === 'http://x'; } catch { return false; } })(); | |
| if (!isRelative && !isSameOrigin) { | |
| res.statusCode = 400; res.end('Invalid redirect target'); return; | |
| } | |
| res.statusCode = code; res.setHeader('location', loc); res.end(); | |
| }; |
Prompt for AI Agents
In SHIM_SERVER's res.redirect implementation, validate the redirect target. Reject absolute URLs pointing to non-same-origin hosts, or restrict to relative paths only. Example: parse `loc` with `new URL(loc, 'http://x')` and reject if `loc` starts with `//` or contains a scheme with a different host. Alternatively, only allow relative paths starting with `/` and not `//`.
Apply this code change:
res.redirect = (a, b) => {
const code = typeof a === 'number' ? a : 307, loc = typeof a === 'number' ? b : a;
// Only allow relative redirects or same-origin absolute URLs
const isRelative = typeof loc === 'string' && loc.startsWith('/') && !loc.startsWith('//');
const isSameOrigin = typeof loc === 'string' && (() => { try { return new URL(loc, 'http://x').origin === 'http://x'; } catch { return false; } })();
if (!isRelative && !isSameOrigin) {
res.statusCode = 400; res.end('Invalid redirect target'); return;
}
res.statusCode = code; res.setHeader('location', loc); res.end();
};
Not useful? Reply
@mira-tdvorak rejectto dismiss this suggestion.
| HashMap::new(), | ||
| tar, | ||
| log, | ||
| ctx.settings.deployment_timeout_seconds, | ||
| ) | ||
| .await?; | ||
| let _ = tokio::fs::remove_dir_all(&ctx_dir).await; | ||
| log(&format!("Functions image built ({tag})")).await; | ||
| Ok(tag) | ||
| } | ||
|
|
||
| /// Generated Dockerfile for the functions shim. Stage 1 bundles every |
There was a problem hiding this comment.
Security issue
Unbounded request body accumulation in shim
readBody accumulates request body chunks with no size limit. A malicious client can send an unbounded body to any /api/* endpoint, causing memory exhaustion in the Node shim process. Since this shim runs user-deployed functions, a compromised or malicious function could also be exploited, but more critically any external attacker hitting a function endpoint can trigger OOM.
| HashMap::new(), | |
| tar, | |
| log, | |
| ctx.settings.deployment_timeout_seconds, | |
| ) | |
| .await?; | |
| let _ = tokio::fs::remove_dir_all(&ctx_dir).await; | |
| log(&format!("Functions image built ({tag})")).await; | |
| Ok(tag) | |
| } | |
| /// Generated Dockerfile for the functions shim. Stage 1 bundles every | |
| function readBody(req) { | |
| const MAX_BODY = parseInt(process.env.RUNWAY_MAX_BODY || '1048576', 10); // 1MB default | |
| return new Promise(resolve => { | |
| const chunks = []; | |
| let total = 0; | |
| req.on('data', d => { | |
| total += d.length; | |
| if (total > MAX_BODY) { | |
| req.destroy(); | |
| resolve({}); | |
| return; | |
| } | |
| chunks.push(d); | |
| }); | |
| req.on('error', () => resolve({})); | |
| req.on('end', () => { | |
| const raw = Buffer.concat(chunks); |
Prompt for AI Agents
In readBody, add a maximum body size check. Accumulate chunks but track total length and destroy the request / resolve with an error if it exceeds a configurable limit (e.g. 1MB default, or read from env var).
Apply this code change:
function readBody(req) {
const MAX_BODY = parseInt(process.env.RUNWAY_MAX_BODY || '1048576', 10); // 1MB default
return new Promise(resolve => {
const chunks = [];
let total = 0;
req.on('data', d => {
total += d.length;
if (total > MAX_BODY) {
req.destroy();
resolve({});
return;
}
chunks.push(d);
});
req.on('error', () => resolve({}));
req.on('end', () => {
const raw = Buffer.concat(chunks);
Not useful? Reply
@mira-tdvorak rejectto dismiss this suggestion.
Summary
api/directory 405'd every/api/*request. Handler sources now stage into/fnduring the build; when present, a second image (node:24-alpine+ esbuild) bundles eachapi/*.{js,ts,mjs,cjs}handler to CJS and serves it from an embeddednode:httpdispatcher alongside the static output — one container, one domain, no extra route.(req,res)contract preserved:res.status/json/send/redirect,req.query, parsed JSON body,[param]/[...rest]dynamic segments,api/index.*→/api.download_container_dirpull-back.wait_exithardened: when the daemon's wait endpoint returns an error body for an already-exited container (observed after a Docker Desktop restart), falls back toinspect_container—State.ExitCodeis authoritative.[ -f ]status into the build container's exit code.Design bets touched: single binary, frontend-first.
Test plan
cargo fmt --checkcargo checkcargo clippy --workspace --all-targets -- -D warningscargo test --workspace(90 tests)Dvorinka/runway-e2e(private, GitHub App install): deploymentd3ed3284builds the shim image (runway-dep-d3ed3284c0da), servesindex.htmlat/, answersGET /api/hello→{"hello":"runway","query":{},"method":"GET"},GET /api/time(TS handler bundled),GET /api/user/42→{"id":"42"}via[id]dynamic segment,POST /api/hello→ method echoed.runner-d3ed328runtime log:runway fn shim :80 (4 routes)Ceiling (deliberate): single shared Node process, not per-function isolation — no cold-start semantics, memory/CPU accounting per function, or Next route-handler support yet. Issue #86 stays open until the doc'd remaining scope is decided.
Generated with Devin