Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 9 additions & 22 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -118,28 +118,15 @@ updates:
# rationale sits next to the dep in the root Cargo.toml.
- dependency-name: "branches"

# oxc_* is held at 0.117.x, and not for API churn alone. bashkit declares
# these five (`oxc_parser`, `oxc_ast`, `oxc_allocator`, `oxc_span`,
# `oxc_syntax`) for the wasm32-unknown-unknown TypeScript path, where
# `zapcode_browser/parser` walks the oxc AST directly. The versions exist
# to match what upstream `zapcode-core` vendors — see the pin comment next
# to the deps in crates/bashkit/Cargo.toml.
#
# `zapcode-core` 1.5.1 requires `oxc ^0.117`, so it does not move with a
# bump of bashkit's declaration. #2758 bumped to 0.154.0 and resolved a
# *second* copy of all 13 oxc crates, leaving the two sides of the same
# parser pipeline on trees 37 minor versions apart — and 0.154 also needs
# rustc 1.97.0 against the 1.95.0 in rust-toolchain.toml, which is what
# reddened the "WASM web package" job, the same shape as the wasmtime
# 49.x failure in #2708. It also pulled in 19 unvetted crates
# (`compact_str` 0.10, `phf` 0.14, `oxc_index` 5.0 and the oxc stack).
#
# Ignore outright rather than by update-type: every release past 0.117.x
# splits the graph the same way, so no bump helps until `zapcode-core`
# moves upstream. Doing it then means bumping the pinned toolchain and
# porting the vendored parser together — a deliberate change, not an
# aggregated `chore(deps)` PR. Without this entry dependabot reopens the
# same unlandable PR every week.
# oxc_* is held at 0.117.x. bashkit declares these five (`oxc_parser`,
# `oxc_ast`, `oxc_allocator`, `oxc_span`, `oxc_syntax`) for the vendored
# ZapCode 1.5.1 copy (`zapcode_vendor/parser` walks the oxc AST directly),
# used on every target. Any oxc release past 0.117.x changes that AST, and
# #2758 (0.154.0) also needed a newer rustc than rust-toolchain.toml.
# Moving oxc means porting the vendored parser and bumping the toolchain
# together, a deliberate change, not an aggregated `chore(deps)` PR.
# Without this entry dependabot reopens the same unlandable PR every week.
# See knowledge/operations/dependencies.md.
- dependency-name: "oxc_*"

# Fuzz targets are a separate cargo workspace with their own lockfile, so the
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,8 @@ jobs:

- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2

- name: Check browser VM source drift
run: python3 scripts/check_zapcode_browser.py
- name: Check vendored ZapCode source drift
run: python3 scripts/check_zapcode_vendor.py

- name: Check bashkit for wasm32-unknown-unknown
run: cargo check -p bashkit -p bashkit-scripted-tool --target wasm32-unknown-unknown --features bashkit/jq,bashkit/wasm_js,bashkit/terminal
Expand Down
18 changes: 0 additions & 18 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 8 additions & 11 deletions crates/bashkit/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,13 @@ bytes = { version = "1", default-features = false, optional = true }
foldhash = { version = "0.2", default-features = false, optional = true }
hifijson = { version = "0.5.0", default-features = false, features = ["alloc", "std"], optional = true }
indexmap = { version = "2.0", default-features = false, optional = true }
# Vendored ZapCode (src/zapcode_vendor) uses the same parser/codec versions as upstream 1.5.1.
oxc_parser = { version = "0.117.0", optional = true }
oxc_ast = { version = "0.117.0", optional = true }
oxc_allocator = { version = "0.117.0", optional = true }
oxc_span = { version = "0.117.0", optional = true }
oxc_syntax = { version = "0.117.0", optional = true }
postcard = { version = "1.1.3", features = ["alloc"], optional = true }
num-bigint = { version = "0.4.6", default-features = false, optional = true }
ryu = { version = "1.0.20", optional = true }
self_cell = { version = "1.2.0", optional = true }
Expand Down Expand Up @@ -252,7 +259,7 @@ cpython = ["dep:bashkit-cpython-wasm", "dep:wasmtime"]
cpython-native = ["cpython", "bashkit-cpython-wasm/native"]
# Enable ts/node/deno/bun builtins via embedded ZapCode TypeScript interpreter
# Usage: cargo build --features typescript
typescript = ["dep:zapcode-core", "dep:oxc_parser", "dep:oxc_ast", "dep:oxc_allocator", "dep:oxc_span", "dep:oxc_syntax", "dep:postcard", "dep:indexmap", "indexmap/serde", "serde/rc"]
typescript = ["dep:oxc_parser", "dep:oxc_ast", "dep:oxc_allocator", "dep:oxc_span", "dep:oxc_syntax", "dep:postcard", "dep:indexmap", "indexmap/std", "indexmap/serde", "serde/rc"]
# Enable sqlite/sqlite3 builtins backed by Turso (pure-Rust SQLite-compatible
# engine). Phase 1 uses turso's `MemoryIO` with a load/flush against the VFS
# at command boundaries; Phase 2 plugs the bashkit VFS in via a custom `IO`
Expand Down Expand Up @@ -450,14 +457,6 @@ fetchkit = { version = "0.7.1", default-features = false, features = ["docs-pdf"
web-time = { workspace = true, optional = true }

[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies]
# Vendored browser ZapCode uses the same parser/codec versions as upstream.
oxc_parser = { version = "0.117.0", optional = true }
oxc_ast = { version = "0.117.0", optional = true }
oxc_allocator = { version = "0.117.0", optional = true }
oxc_span = { version = "0.117.0", optional = true }
oxc_syntax = { version = "0.117.0", optional = true }
postcard = { version = "1.1.3", features = ["alloc"], optional = true }

gloo-timers = { version = "0.4", features = ["futures"], optional = true }
send_wrapper = { version = "0.6", features = ["futures"], optional = true }
# Task spawner for the host-call execution driver (see host_call.rs). JS-backed
Expand All @@ -479,5 +478,3 @@ unexpected_cfgs = { level = "warn", check-cfg = ['cfg(feature, values("i18n-deci
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
tokio = { workspace = true, features = ["process"] }

[target.'cfg(not(all(target_arch = "wasm32", target_os = "unknown")))'.dependencies]
zapcode-core = { version = "1.5.1", optional = true }
3 changes: 2 additions & 1 deletion crates/bashkit/docs/threat-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -892,9 +892,10 @@ access is bridged through Bashkit's VFS, never the host filesystem.
| Script reads host filesystem (TM-TS-022) | Load a host script | Script file loaded via VFS | MITIGATED |
| Shebang line injection (TM-TS-023) | `#!...` header | Shebang stripped safely | MITIGATED |
| Deeply nested source aborts the host (TM-TS-024) | A few KB of `[[[...` or `1+1+...` overflows ZapCode's recursive parser/compiler | Nesting estimate rejects depth over 1000; ZapCode steps run on a 128 MiB-stack thread | MITIGATED |
| Huge `padStart`/`padEnd` aborts the host (TM-TS-025) | `'a'.padStart(2**40)` asks the allocator for ~1 TiB | Vendored ZapCode caps the target length at 10,000,000, like `repeat`; the run fails cleanly | MITIGATED |
| Bash var expansion injection (TM-TS-020) | Unquoted `$VAR` expanded before TS runs | By design; use single quotes to prevent expansion | MITIGATED |

Per-threat coverage (TM-TS-001 … TM-TS-024), including error-isolation and
Per-threat coverage (TM-TS-001 … TM-TS-025), including error-isolation and
exit-code propagation cases, is also exercised by the `threat_ts_*` tests.

### Request Signing & Snapshot Integrity (TM-CRY-*, TM-SNAP-*)
Expand Down
3 changes: 1 addition & 2 deletions crates/bashkit/src/builtins/typescript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@
//! `node`/`deno`/`bun` aliases.

use crate::time_compat::Instant;
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
use crate::zapcode_browser as zapcode_core;
use crate::zapcode_vendor as zapcode_core;
use async_trait::async_trait;
use std::future::Future;
use std::path::{Path, PathBuf};
Expand Down
20 changes: 8 additions & 12 deletions crates/bashkit/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -610,14 +610,9 @@ pub use builtins::{
TypeScriptConfig, TypeScriptExtension, TypeScriptExternalFnHandler, TypeScriptExternalFns,
TypeScriptLimits,
};
// Re-export zapcode-core types needed by external handler consumers.
#[cfg(all(feature = "typescript", target_arch = "wasm32", target_os = "unknown"))]
pub use zapcode_browser::Value as ZapcodeValue;
#[cfg(all(
feature = "typescript",
not(all(target_arch = "wasm32", target_os = "unknown"))
))]
pub use zapcode_core::Value as ZapcodeValue;
// Re-export ZapCode types needed by external handler consumers.
#[cfg(feature = "typescript")]
pub use zapcode_vendor::Value as ZapcodeValue;

/// Logging utilities module
///
Expand Down Expand Up @@ -8721,9 +8716,10 @@ echo missing fi"#,
}
}

// Browser-only upstream source retains VM limits; native builds keep the
// external crate and its public value types. See runtimes/zapcode-runtime.md.
#[cfg(all(feature = "typescript", target_arch = "wasm32", target_os = "unknown"))]
// Decision: every target runs this in-tree ZapCode 1.5.1 copy instead of the
// registry crate, so Bashkit can carry resource-limit fixes (marked
// `bashkit fork:`) that upstream has not shipped. See runtimes/zapcode-runtime.md.
#[cfg(feature = "typescript")]
#[rustfmt::skip]
#[allow(dead_code, unused_imports, clippy::all, clippy::unwrap_used)]
mod zapcode_browser;
mod zapcode_vendor;
10 changes: 0 additions & 10 deletions crates/bashkit/src/zapcode_browser/README.md

This file was deleted.

12 changes: 12 additions & 0 deletions crates/bashkit/src/zapcode_vendor/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Vendored ZapCode source

Upstream `zapcode-core` 1.5.1, MIT, https://github.com/TheUncharted/zapcode.
Every target (native, WASI, browser) builds this copy; the registry crate is
no longer a dependency. The copy replaces std clocks that panic on
wasm32-unknown-unknown and carries `bashkit fork:` resource-limit fixes
upstream has not shipped (listed in `scripts/check_zapcode_vendor.py`). It adds
no JS eval, imports, network or filesystem access.

`upstream-sha256.json` records every original source file. Mechanical change:
`crate::` becomes `crate::zapcode_vendor::`; `lib.rs` becomes `mod.rs`.
Clock changes in sandbox.rs/trace.rs use Bashkit's platform clock shim.
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ pub mod instruction;

use std::collections::{HashMap, HashSet};

use crate::zapcode_browser::error::{Result, ZapcodeError};
use crate::zapcode_browser::parser::ir::*;
use crate::zapcode_vendor::error::{Result, ZapcodeError};
use crate::zapcode_vendor::parser::ir::*;
use instruction::*;

/// Compiled program ready for VM execution.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use oxc_ast::ast;
use oxc_parser::Parser;
use oxc_span::SourceType;

use crate::zapcode_browser::error::{Result, ZapcodeError};
use crate::zapcode_vendor::error::{Result, ZapcodeError};

pub fn parse(source: &str) -> Result<Program> {
// Auto-wrap trailing object literals: `{ key: value }` → `({ key: value })`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,26 +33,26 @@ impl ResourceTracker {
self.start_time = Some(crate::time::Instant::now());
}

pub fn check_time(&self, limits: &ResourceLimits) -> crate::zapcode_browser::error::Result<()> {
pub fn check_time(&self, limits: &ResourceLimits) -> crate::zapcode_vendor::error::Result<()> {
if let Some(start) = self.start_time {
if start.elapsed().as_millis() as u64 > limits.time_limit_ms {
return Err(crate::zapcode_browser::ZapcodeError::TimeLimitExceeded);
return Err(crate::zapcode_vendor::ZapcodeError::TimeLimitExceeded);
}
}
Ok(())
}

pub fn check_stack(&self, limits: &ResourceLimits) -> crate::zapcode_browser::error::Result<()> {
pub fn check_stack(&self, limits: &ResourceLimits) -> crate::zapcode_vendor::error::Result<()> {
if self.current_stack_depth > limits.max_stack_depth {
return Err(crate::zapcode_browser::ZapcodeError::StackOverflow(self.current_stack_depth));
return Err(crate::zapcode_vendor::ZapcodeError::StackOverflow(self.current_stack_depth));
}
Ok(())
}

pub fn track_allocation(&mut self, limits: &ResourceLimits) -> crate::zapcode_browser::error::Result<()> {
pub fn track_allocation(&mut self, limits: &ResourceLimits) -> crate::zapcode_vendor::error::Result<()> {
self.allocations += 1;
if self.allocations > limits.max_allocations {
return Err(crate::zapcode_browser::ZapcodeError::AllocationLimitExceeded);
return Err(crate::zapcode_vendor::ZapcodeError::AllocationLimitExceeded);
}
Ok(())
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ use std::collections::{HashMap, HashSet};

use serde::{Deserialize, Serialize};

use crate::zapcode_browser::compiler::CompiledProgram;
use crate::zapcode_browser::error::{Result, ZapcodeError};
use crate::zapcode_browser::sandbox::ResourceLimits;
use crate::zapcode_browser::value::Value;
use crate::zapcode_browser::vm::{CallFrame, Continuation, TryInfo, Vm, VmState};
use crate::zapcode_vendor::compiler::CompiledProgram;
use crate::zapcode_vendor::error::{Result, ZapcodeError};
use crate::zapcode_vendor::sandbox::ResourceLimits;
use crate::zapcode_vendor::value::Value;
use crate::zapcode_vendor::vm::{CallFrame, Continuation, TryInfo, Vm, VmState};

/// Internal serializable representation of VM state at a suspension point.
#[derive(Debug, Clone, Serialize, Deserialize)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use std::sync::Arc;

use indexmap::IndexMap;

use crate::zapcode_browser::error::{Result, ZapcodeError};
use crate::zapcode_browser::value::Value;
use crate::zapcode_vendor::error::{Result, ZapcodeError};
use crate::zapcode_vendor::value::Value;

/// Register built-in global objects and functions.
pub fn register_globals(globals: &mut HashMap<String, Value>) {
Expand Down Expand Up @@ -507,6 +507,8 @@ fn call_string_method(s: &Arc<str>, method: &str, args: &[Value]) -> Result<Opti
Value::String(s.clone())
} else {
let pad_len = target_len - current_len;
// bashkit fork: cap like `repeat`; unbounded take() aborted the host.
if target_len > 10_000_000 { return Err(ZapcodeError::AllocationLimitExceeded); }
Comment thread
chaliy marked this conversation as resolved.
Resolved
let padding: String = pad.chars().cycle().take(pad_len).collect();
Value::String(Arc::from(format!("{}{}", padding, s).as_str()))
}
Expand All @@ -523,6 +525,8 @@ fn call_string_method(s: &Arc<str>, method: &str, args: &[Value]) -> Result<Opti
Value::String(s.clone())
} else {
let pad_len = target_len - current_len;
// bashkit fork: cap like `repeat`; unbounded take() aborted the host.
if target_len > 10_000_000 { return Err(ZapcodeError::AllocationLimitExceeded); }
Comment thread
chaliy marked this conversation as resolved.
Resolved
let padding: String = pad.chars().cycle().take(pad_len).collect();
Value::String(Arc::from(format!("{}{}", s, padding).as_str()))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ use std::sync::Arc;

use indexmap::IndexMap;

use crate::zapcode_browser::compiler::instruction::{Constant, Instruction};
use crate::zapcode_browser::compiler::CompiledProgram;
use crate::zapcode_browser::error::{Result, ZapcodeError};
use crate::zapcode_browser::sandbox::{ResourceLimits, ResourceTracker};
use crate::zapcode_browser::snapshot::ZapcodeSnapshot;
use crate::zapcode_browser::trace::{ExecutionTrace, SpanBuilder, TraceStatus};
use crate::zapcode_browser::value::{Closure, FunctionId, GeneratorObject, SuspendedFrame, Value};
use crate::zapcode_vendor::compiler::instruction::{Constant, Instruction};
use crate::zapcode_vendor::compiler::CompiledProgram;
use crate::zapcode_vendor::error::{Result, ZapcodeError};
use crate::zapcode_vendor::sandbox::{ResourceLimits, ResourceTracker};
use crate::zapcode_vendor::snapshot::ZapcodeSnapshot;
use crate::zapcode_vendor::trace::{ExecutionTrace, SpanBuilder, TraceStatus};
use crate::zapcode_vendor::value::{Closure, FunctionId, GeneratorObject, SuspendedFrame, Value};

mod builtins;

Expand Down Expand Up @@ -2402,7 +2402,7 @@ impl Vm {
}

// Re-export for the ParamPattern type used in function calls
use crate::zapcode_browser::parser::ir::ParamPattern;
use crate::zapcode_vendor::parser::ir::ParamPattern;

fn is_array_method(name: &str) -> bool {
matches!(
Expand Down Expand Up @@ -2505,7 +2505,7 @@ impl ZapcodeRun {

// Parse
let parse_span = SpanBuilder::new("parse");
let program = match crate::zapcode_browser::parser::parse(&self.source) {
let program = match crate::zapcode_vendor::parser::parse(&self.source) {
Ok(p) => {
root_span.add_child(parse_span.finish_ok());
p
Expand All @@ -2522,7 +2522,7 @@ impl ZapcodeRun {
// Compile
let compile_span = SpanBuilder::new("compile");
let ext_set: HashSet<String> = self.external_functions.iter().cloned().collect();
let compiled = match crate::zapcode_browser::compiler::compile_with_externals(&program, ext_set.clone()) {
let compiled = match crate::zapcode_vendor::compiler::compile_with_externals(&program, ext_set.clone()) {
Ok(c) => {
root_span.add_child(compile_span.finish_ok());
c
Expand Down
28 changes: 28 additions & 0 deletions crates/bashkit/tests/integration/threat_model_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7614,6 +7614,34 @@ mod typescript_security {
assert_ne!(result.exit_code, 0, "Memory bomb should not succeed");
}

/// TM-TS-025: a huge padStart/padEnd length fails the run instead of
/// asking the allocator for ~1 TiB and aborting the host process.
#[tokio::test]
async fn threat_ts_pad_huge_length_fails_cleanly() {
let mut bash = bash_with_ts();
for method in ["padStart", "padEnd"] {
let result = bash
.exec(&format!(
"ts -c \"console.log('a'.{method}(2 ** 40).length)\""
))
.await
.unwrap();
assert_ne!(result.exit_code, 0, "{method} should fail");
assert!(
result.stdout.is_empty(),
"{method} printed {:?}",
result.stdout
);
}
// Ordinary padding still works, including multi-char pads.
let result = bash
.exec("ts -c \"console.log('7'.padStart(3, '0') + '|' + 'ab'.padEnd(5, 'xy'))\"")
.await
.unwrap();
assert_eq!(result.exit_code, 0, "stderr: {}", result.stderr);
assert_eq!(result.stdout.trim(), "007|abxyx");
}

/// TM-TS-003: TypeScript stack overflow blocked
#[tokio::test]
async fn threat_ts_stack_overflow() {
Expand Down
Loading
Loading