diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 7d1901d..dd16b64 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -83,7 +83,7 @@ jobs: sandboxes: name: sandboxes - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 timeout-minutes: 45 steps: - uses: actions/checkout@v4 diff --git a/Cargo.lock b/Cargo.lock index 1f8db9a..6803d85 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -222,6 +222,7 @@ dependencies = [ "serde", "serde_json", "spin-sdk", + "url", "wit-bindgen 0.61.1", ] diff --git a/LICENSE b/LICENSE index 9e3e542..da9f8f4 100644 --- a/LICENSE +++ b/LICENSE @@ -186,7 +186,7 @@ APPENDIX: How to apply the Apache License to your work. same "printed page" as the copyright notice for easier identification within third-party archives. -Copyright (c) 2026 Akamai Technologies +Copyright (c) The Spin Framework Contributors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -199,3 +199,19 @@ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +--- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the +Combined Software. diff --git a/README.md b/README.md index c3ae0bd..ec79626 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ POST this envelope to `/ts/...` or `/py/...`: { "code": "print(6 * 7)", "sandboxId": "demo", - "allowedHosts": ["api.example.com"], + "allowedHosts": ["https://api.example.com"], "kvEnabled": true, "input": { "method": "GET", "path": "/" } } @@ -75,7 +75,10 @@ POST this envelope to `/ts/...` or `/py/...`: `code` and `sandboxId` are required; `sandboxId` must be non-empty and at most 256 bytes. `allowedHosts` narrows egress for outbound HTTP; -missing or empty denies it. `kvEnabled` is `false` by default; set it to `true` to +missing or empty denies it. Entries use `scheme://host[:port]`; `*.example.com` +matches subdomains only and `:*` allows any port. CIDR and port ranges are not +supported, wildcard hosts grant nothing, and malformed entries return `400`. +`kvEnabled` is `false` by default; set it to `true` to allow access to the scoped key-value store. `input` creates the request delivered to an HTTP handler. @@ -142,6 +145,8 @@ In production, run sandboxes as private components and reach them through Spin s chaining or the [`@spinframework/sandbox`](sdk) client library. The [AI code executor](examples/ai-code-executor) shows the complete wiring. +Sandbox endpoints do not authenticate callers: any component allowed to reach a private route can choose an ID and policy. Grant access only to trusted callers, or authenticate public routes. The application must map requests to sandbox IDs and set `allowedHosts` and `kvEnabled` itself; never accept these from model output or unchecked users. + ## Testing Run unit tests with: @@ -170,6 +175,8 @@ template updates. built-in caps are on size: code over 5 MB (or an oversized request body) is rejected with `413`, and captured stdout/stderr is truncated at 256 KB. - **Stateless.** Each `run` is single-shot. Only the scoped KV store persists. +- **KV lifetime and quotas.** KV has no per-sandbox quota or automatic cleanup. Once an ID is retired, remove its data with `Interpreter.javascript(...).kv(id).clear()`; coordinate cleanup with writers. +- **Secrets.** Code can read any secrets provided in its code, input, or component environment. Do not configure sensitive environment variables on sandbox components; there is no host-side credential injection for outbound requests. - **Fixed capabilities.** No filesystem, shell, or subprocess, and no `pip`/`npm` install at runtime. The pre-bundled dependency set (plus, for JS, whatever the bundler can package) is the whole toolbox. - **Egress DNS.** Private IP literals and local/internal names are denied by the diff --git a/crates/allowed_hosts.rs b/crates/allowed_hosts.rs new file mode 100644 index 0000000..bf2fc94 --- /dev/null +++ b/crates/allowed_hosts.rs @@ -0,0 +1,76 @@ +use url::Url; + +#[derive(Debug)] +#[allow(dead_code)] +pub struct HostPattern { + pub scheme: String, + pub host: String, + pub subdomains_only: bool, + pub port: Option, +} + +pub fn parse_pattern(value: &str) -> Option { + let value = value.trim(); + let (scheme, authority) = value.split_once("://")?; + if scheme.is_empty() || (scheme != "*" && !scheme.chars().all(char::is_alphabetic)) { + return None; + } + let authority = authority.strip_suffix('/').unwrap_or(authority); + if authority.is_empty() || authority.contains(['/', '?', '#', '@', '%', '\\']) || authority.chars().any(char::is_whitespace) { + return None; + } + let (host, port) = if authority.starts_with('[') { + let end = authority.find(']')?; + let tail = &authority[end + 1..]; + (&authority[..=end], if tail.is_empty() { None } else { Some(tail.strip_prefix(':')?) }) + } else if let Some((host, port)) = authority.rsplit_once(':') { + (host, Some(port)) + } else { + (authority, None) + }; + if !host.starts_with('[') && host.contains(':') { + return None; + } + let port = port.filter(|port| !port.is_empty()); + if let Some(port) = port { + if port != "*" && (!port.bytes().all(|byte| byte.is_ascii_digit()) || port.parse::().is_err()) { + return None; + } + } else if !matches!(scheme, "http" | "https" | "postgres" | "mysql" | "redis" | "mqtt") { + return None; + } + let (subdomains_only, host) = match host.strip_prefix("*.") { + Some(host) => (true, host), + None => (false, host), + }; + if host == "*" && !subdomains_only { + return Some(HostPattern { scheme: scheme.to_string(), host: host.to_string(), subdomains_only, port: port.map(str::to_string) }); + } + if host.contains('*') || (subdomains_only && host.starts_with('[')) { + return None; + } + let url = Url::parse(&format!("http://{host}")).ok()?; + if url.username() != "" || url.password().is_some() || url.port().is_some() || url.path() != "/" { + return None; + } + if subdomains_only && !matches!(url.host(), Some(url::Host::Domain(_))) { + return None; + } + let host = url.host_str()?.to_string(); + Some(HostPattern { scheme: scheme.to_string(), host, subdomains_only, port: port.map(str::to_string) }) +} + +#[cfg(test)] +mod tests { + use super::parse_pattern; + + #[test] + fn validates_patterns() { + for value in ["https://example.com", "https://example.com:", "https://example.com/", "*://*:*", "*://*.example.com:*", "http://[2600::1]:8080", "https://93.184.216.34"] { + assert!(parse_pattern(value).is_some(), "{value}"); + } + for value in ["*", "example.com", "", "https://", "*://example.com", "https://example.com/path", "https://example.com?x", "https://user@example.com", "http://example.com:80:90", "https://example.com:1-10", "https://example.com:65536", "https://example.com/24", "https://*.127.0.0.1", "https://a*b.com", "https://[::1]junk"] { + assert!(parse_pattern(value).is_none(), "{value}"); + } + } +} \ No newline at end of file diff --git a/crates/guard-io/Cargo.toml b/crates/guard-io/Cargo.toml index 3aae19f..8ac1a15 100644 --- a/crates/guard-io/Cargo.toml +++ b/crates/guard-io/Cargo.toml @@ -2,7 +2,7 @@ name = "guard-io" version = "0.1.0" edition = "2021" -license = "Apache-2.0" +license = "Apache-2.0 WITH LLVM-exception" publish = false [lib] diff --git a/crates/guard-io/src/egress.rs b/crates/guard-io/src/egress.rs index 8f271e5..87d6e50 100644 --- a/crates/guard-io/src/egress.rs +++ b/crates/guard-io/src/egress.rs @@ -1,5 +1,6 @@ //! Per-request egress allow-list layered on Spin's host policy, with an SSRF backstop. +use crate::allowed_hosts::parse_pattern; use ip_network::IpNetwork; use std::net::IpAddr; use url::Url; @@ -36,21 +37,6 @@ fn parse_authority(scheme: &str, authority: &str) -> Option<(String, Option Some((url.host_str()?.to_string(), url.port())) } -/// Splits the host part of an allow-list pattern (`host` or `host:port-spec`, -/// with an IPv6 host in brackets) into its host and the raw, not-yet-parsed -/// port spec — unlike `parse_authority`, the port half may also be `*`. -fn split_pattern(pat: &str) -> (&str, Option<&str>) { - if let Some(rest) = pat.strip_prefix('[') { - if let Some((host, tail)) = rest.split_once(']') { - return (host, tail.strip_prefix(':')); - } - } - match pat.rsplit_once(':') { - Some((host, port)) => (host, Some(port)), - None => (pat, None), - } -} - /// The well-known default port for a URL scheme, used when an allow-list /// entry omits a port entirely. fn well_known_port(scheme: &str) -> Option { @@ -77,8 +63,8 @@ fn port_matches(pat_port: Option<&str>, scheme: &str, port: Option) -> bool /// Returns true if `scheme://authority` (the outbound request's scheme and /// `host[:port]`) is allowed by the per-request `allowed` list. An allow-list /// entry with an explicit scheme (`https://example.com`) only matches that -/// scheme; an entry without one, or with a `*` scheme (`*://example.com`), -/// matches any scheme. An entry with no port matches only the request +/// scheme; an entry with a `*` scheme (`*://example.com`) matches any scheme. +/// An entry with no port matches only the request /// scheme's default port (80/http, 443/https); `:*` allows any port and /// `:8080` allows exactly that port. pub fn host_allowed(scheme: &str, authority: &str, allowed: &[String]) -> bool { @@ -93,28 +79,16 @@ pub fn host_allowed(scheme: &str, authority: &str, allowed: &[String]) -> bool { return false; // deny internal targets unconditionally } allowed.iter().any(|raw| { - let raw = raw.trim(); - if raw == "*" { - return false; // a bare "*" from the per-request list must not allow-all + let Some(pattern) = parse_pattern(raw) else { return false }; + if matches!(pattern.host.as_str(), "*" | "self" | "self.alt") || (pattern.scheme != "*" && pattern.scheme != scheme_lower) { + return false; } - let (pat_scheme, rest) = match raw.split_once("://") { - Some((s, rest)) => (Some(s.to_ascii_lowercase()), rest), - None => (None, raw), - }; - if let Some(ps) = &pat_scheme { - if ps != "*" && *ps != scheme_lower { - return false; - } - } - let rest = rest.split('/').next().unwrap_or(rest); - let (pat_host, pat_port) = split_pattern(rest); - let pat_host = pat_host.to_ascii_lowercase(); - let host_matches = if let Some(base) = pat_host.strip_prefix("*.") { - host_lower == base || host_lower.ends_with(&format!(".{base}")) + let host_matches = if pattern.subdomains_only { + host_lower.ends_with(&format!(".{}", pattern.host)) } else { - host_lower == pat_host + host_lower == pattern.host }; - host_matches && port_matches(pat_port, &scheme_lower, port) + host_matches && port_matches(pattern.port.as_deref(), &scheme_lower, port) }) } @@ -131,7 +105,7 @@ mod tests { fn allows_an_exact_host_match() { // No port in the pattern defaults to the request scheme's well-known port, // mirroring Spin's own allowed_outbound_hosts port mechanics. - let allowed = vec!["example.com".to_string()]; + let allowed = vec!["https://example.com".to_string()]; assert!(host_allowed("https", "example.com", &allowed)); assert!(host_allowed("https", "example.com:443", &allowed)); assert!(!host_allowed("https", "example.com:8080", &allowed)); @@ -140,7 +114,7 @@ mod tests { #[test] fn allows_a_host_port_pattern_only_on_that_port() { - let allowed = vec!["example.com:8080".to_string()]; + let allowed = vec!["https://example.com:8080".to_string()]; assert!(host_allowed("https", "example.com:8080", &allowed)); assert!(!host_allowed("https", "example.com:9090", &allowed)); assert!(!host_allowed("https", "example.com", &allowed)); @@ -148,7 +122,7 @@ mod tests { #[test] fn a_wildcard_port_allows_any_port() { - let allowed = vec!["example.com:*".to_string()]; + let allowed = vec!["https://example.com:*".to_string()]; assert!(host_allowed("https", "example.com", &allowed)); assert!(host_allowed("https", "example.com:8080", &allowed)); assert!(host_allowed("https", "example.com:65535", &allowed)); @@ -173,32 +147,38 @@ mod tests { #[test] fn a_star_scheme_pattern_matches_any_scheme() { - let allowed = vec!["*://example.com".to_string()]; + let allowed = vec!["*://example.com:*".to_string()]; assert!(host_allowed("http", "example.com", &allowed)); assert!(host_allowed("https", "example.com", &allowed)); } #[test] - fn a_scheme_less_pattern_matches_any_scheme() { + fn a_scheme_less_pattern_does_not_match() { let allowed = vec!["example.com".to_string()]; - assert!(host_allowed("http", "example.com", &allowed)); - assert!(host_allowed("https", "example.com", &allowed)); + assert!(!host_allowed("http", "example.com", &allowed)); + assert!(!host_allowed("https", "example.com", &allowed)); } #[test] - fn wildcard_subdomain_matches_any_depth_and_the_bare_domain() { - // By design, "*.example.com" also covers the bare "example.com", not just - // strict subdomains. - let allowed = vec!["*.example.com".to_string()]; + fn wildcard_subdomain_matches_any_depth_but_not_the_bare_domain() { + let allowed = vec!["https://*.example.com".to_string()]; assert!(host_allowed("https", "a.example.com", &allowed)); assert!(host_allowed("https", "a.b.example.com", &allowed)); - assert!(host_allowed("https", "example.com", &allowed)); + assert!(!host_allowed("https", "example.com", &allowed)); assert!(!host_allowed("https", "notexample.com", &allowed)); } #[test] fn a_bare_star_does_not_allow_all() { assert!(!host_allowed("https", "example.com", &["*".to_string()])); + assert!(!host_allowed("https", "example.com", &["*://*:*".to_string()])); + } + + #[test] + fn spin_self_patterns_do_not_match_outbound_hosts() { + for host in ["self", "self.alt"] { + assert!(!host_allowed("https", host, &[format!("https://{host}")])); + } } #[test] @@ -216,13 +196,13 @@ mod tests { "[fc00::1]", "[::ffff:169.254.169.254]", // IPv4-mapped IPv6 ] { - assert!(!host_allowed("https", host, &[host.trim_start_matches('[').trim_end_matches(']').to_string()]), "{host}"); + assert!(!host_allowed("https", host, &[format!("https://{host}")]), "{host}"); } } #[test] fn allows_public_ip_literals() { - let allowed = vec!["93.184.216.34".to_string()]; + let allowed = vec!["https://93.184.216.34".to_string()]; assert!(host_allowed("https", "93.184.216.34", &allowed)); } @@ -238,7 +218,7 @@ mod tests { #[test] fn matching_is_case_insensitive() { - let allowed = vec!["Example.COM".to_string()]; + let allowed = vec!["https://Example.COM".to_string()]; assert!(host_allowed("https", "example.com", &allowed)); assert!(host_allowed("HTTPS", "EXAMPLE.com", &allowed)); } diff --git a/crates/guard-io/src/lib.rs b/crates/guard-io/src/lib.rs index 3f651b8..0a1b007 100644 --- a/crates/guard-io/src/lib.rs +++ b/crates/guard-io/src/lib.rs @@ -2,6 +2,8 @@ //! This stays separate from `guard` to avoid a component-instantiation cycle. mod bindings; +#[path = "../../allowed_hosts.rs"] +mod allowed_hosts; mod capabilities; mod context; mod egress; diff --git a/crates/guard/Cargo.toml b/crates/guard/Cargo.toml index 96d1bd5..6837edf 100644 --- a/crates/guard/Cargo.toml +++ b/crates/guard/Cargo.toml @@ -2,7 +2,7 @@ name = "guard" version = "0.1.0" edition = "2021" -license = "Apache-2.0" +license = "Apache-2.0 WITH LLVM-exception" publish = false [lib] @@ -15,3 +15,4 @@ anyhow = "1" serde = { version = "1", features = ["derive"] } serde_json = "1" futures = "0.3" +url = "2" diff --git a/crates/guard/src/envelope.rs b/crates/guard/src/envelope.rs index 4228e25..5194b10 100644 --- a/crates/guard/src/envelope.rs +++ b/crates/guard/src/envelope.rs @@ -72,6 +72,11 @@ pub fn validate(body: &[u8]) -> Result { if raw.sandbox_id.len() > MAX_SANDBOX_ID { return Err(EnvelopeError::Invalid(format!("sandboxId must be at most {MAX_SANDBOX_ID} bytes"))); } + if let Some(hosts) = &raw.allowed_hosts { + if hosts.iter().any(|host| crate::allowed_hosts::parse_pattern(host).is_none()) { + return Err(EnvelopeError::Invalid("allowedHosts contains an invalid host pattern".to_string())); + } + } Ok(Envelope { code: raw.code, sandbox_id: raw.sandbox_id, @@ -91,7 +96,7 @@ mod tests { "code": "console.log(1)", "sandboxId": "tenant-a", "input": {"method": "POST", "path": "/x", "body": "hi"}, - "allowedHosts": ["api.example.com"], + "allowedHosts": ["https://api.example.com"], "kvEnabled": true }"#; let env = validate(body).expect("valid envelope"); @@ -100,7 +105,7 @@ mod tests { let input = env.input.expect("input present"); assert_eq!(input.method, Some("POST".to_string())); assert_eq!(input.path, Some("/x".to_string())); - assert_eq!(env.allowed_hosts, Some(vec!["api.example.com".to_string()])); + assert_eq!(env.allowed_hosts, Some(vec!["https://api.example.com".to_string()])); assert!(env.kv_enabled); } @@ -114,6 +119,14 @@ mod tests { assert!(!env.kv_enabled); } + #[test] + fn rejects_invalid_allowed_hosts() { + for host in ["*", "example.com", "https://example.com/path", "https://example.com:1-10"] { + let body = serde_json::json!({"code": "1", "sandboxId": "a", "allowedHosts": [host]}).to_string(); + assert!(matches!(validate(body.as_bytes()), Err(EnvelopeError::Invalid(_))), "{host}"); + } + } + #[test] fn rejects_malformed_json() { match validate(b"not json") { diff --git a/crates/guard/src/lib.rs b/crates/guard/src/lib.rs index f7ab8ff..b31856d 100644 --- a/crates/guard/src/lib.rs +++ b/crates/guard/src/lib.rs @@ -7,6 +7,8 @@ wit_bindgen::generate!({ }); mod envelope; +#[path = "../../allowed_hosts.rs"] +mod allowed_hosts; mod logging; use futures::{SinkExt, TryStreamExt}; diff --git a/examples/ai-code-executor/api/package-lock.json b/examples/ai-code-executor/api/package-lock.json index a3a0a8a..2b12f47 100644 --- a/examples/ai-code-executor/api/package-lock.json +++ b/examples/ai-code-executor/api/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "api", "version": "0.1.0", - "license": "Apache-2.0", + "license": "Apache-2.0 WITH LLVM-exception", "dependencies": { "@anthropic-ai/sdk": "^0.69.0", "@spinframework/sandbox": "file:../../../sdk", diff --git a/examples/ai-code-executor/api/package.json b/examples/ai-code-executor/api/package.json index 83d9f22..3766c94 100644 --- a/examples/ai-code-executor/api/package.json +++ b/examples/ai-code-executor/api/package.json @@ -3,7 +3,7 @@ "private": true, "version": "0.1.0", "description": "AI Code Executor API, an LLM tool-use loop over the Wasm interpreter sandbox", - "license": "Apache-2.0", + "license": "Apache-2.0 WITH LLVM-exception", "main": "index.js", "type": "module", "scripts": { diff --git a/examples/ai-code-executor/ui/package-lock.json b/examples/ai-code-executor/ui/package-lock.json index beb390b..61ed8fa 100644 --- a/examples/ai-code-executor/ui/package-lock.json +++ b/examples/ai-code-executor/ui/package-lock.json @@ -6,7 +6,7 @@ "": { "name": "ui", "hasInstallScript": true, - "license": "Apache-2.0", + "license": "Apache-2.0 WITH LLVM-exception", "dependencies": { "highlight.js": "^11.10.0", "markdown-it": "^14.1.0", diff --git a/examples/ai-code-executor/ui/package.json b/examples/ai-code-executor/ui/package.json index 7318f8c..f1e48b5 100644 --- a/examples/ai-code-executor/ui/package.json +++ b/examples/ai-code-executor/ui/package.json @@ -1,7 +1,7 @@ { "name": "ui", "private": true, - "license": "Apache-2.0", + "license": "Apache-2.0 WITH LLVM-exception", "type": "module", "scripts": { "dev": "nuxt dev", diff --git a/examples/app-builder/api/package-lock.json b/examples/app-builder/api/package-lock.json index a3a0a8a..2b12f47 100644 --- a/examples/app-builder/api/package-lock.json +++ b/examples/app-builder/api/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "api", "version": "0.1.0", - "license": "Apache-2.0", + "license": "Apache-2.0 WITH LLVM-exception", "dependencies": { "@anthropic-ai/sdk": "^0.69.0", "@spinframework/sandbox": "file:../../../sdk", diff --git a/examples/app-builder/api/package.json b/examples/app-builder/api/package.json index 5105243..84697f9 100644 --- a/examples/app-builder/api/package.json +++ b/examples/app-builder/api/package.json @@ -3,7 +3,7 @@ "private": true, "version": "0.1.0", "description": "App Builder API, an LLM generates HTTP-handler apps, stores them, and serves each live", - "license": "Apache-2.0", + "license": "Apache-2.0 WITH LLVM-exception", "main": "index.js", "type": "module", "scripts": { diff --git a/examples/app-builder/ui/package-lock.json b/examples/app-builder/ui/package-lock.json index 928f2ae..5dbd743 100644 --- a/examples/app-builder/ui/package-lock.json +++ b/examples/app-builder/ui/package-lock.json @@ -6,7 +6,7 @@ "": { "name": "ui", "hasInstallScript": true, - "license": "Apache-2.0", + "license": "Apache-2.0 WITH LLVM-exception", "dependencies": { "diff": "^8.0.2", "highlight.js": "^11.10.0", diff --git a/examples/app-builder/ui/package.json b/examples/app-builder/ui/package.json index a32422e..7e1fbd2 100644 --- a/examples/app-builder/ui/package.json +++ b/examples/app-builder/ui/package.json @@ -1,7 +1,7 @@ { "name": "ui", "private": true, - "license": "Apache-2.0", + "license": "Apache-2.0 WITH LLVM-exception", "type": "module", "scripts": { "dev": "nuxt dev", diff --git a/examples/sdk-component/api/package-lock.json b/examples/sdk-component/api/package-lock.json index b39503c..69d8c15 100644 --- a/examples/sdk-component/api/package-lock.json +++ b/examples/sdk-component/api/package-lock.json @@ -5,7 +5,7 @@ "packages": { "": { "name": "sdk-component-api", - "license": "Apache-2.0", + "license": "Apache-2.0 WITH LLVM-exception", "dependencies": { "@spinframework/sandbox": "file:../../../sdk", "@spinframework/wasi-http-proxy": "^2.0.0", diff --git a/examples/sdk-component/api/package.json b/examples/sdk-component/api/package.json index 0dd4fee..e40f27b 100644 --- a/examples/sdk-component/api/package.json +++ b/examples/sdk-component/api/package.json @@ -1,7 +1,7 @@ { "name": "sdk-component-api", "private": true, - "license": "Apache-2.0", + "license": "Apache-2.0 WITH LLVM-exception", "type": "module", "scripts": { "build": "node build.mjs && mkdirp dist && j2w -i build/bundle.js --initLocation http://api.localhost -o dist/api.wasm" diff --git a/packages/typescript/bundler/package-lock.json b/packages/typescript/bundler/package-lock.json index 76091f1..59b0e2e 100644 --- a/packages/typescript/bundler/package-lock.json +++ b/packages/typescript/bundler/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "bundler", "version": "0.1.0", - "license": "Apache-2.0", + "license": "Apache-2.0 WITH LLVM-exception", "dependencies": { "@spinframework/build-tools": "^2.1.0", "@spinframework/spin-variables": "^1.0.1", diff --git a/packages/typescript/bundler/package.json b/packages/typescript/bundler/package.json index be3e10d..61a2a0f 100644 --- a/packages/typescript/bundler/package.json +++ b/packages/typescript/bundler/package.json @@ -3,7 +3,7 @@ "private": true, "version": "0.1.0", "description": "In-Wasm dependency bundler for the TS sandbox; runs in StarlingMonkey (no Node, no esbuild at runtime)", - "license": "Apache-2.0", + "license": "Apache-2.0 WITH LLVM-exception", "scripts": { "build": "node build.mjs && mkdirp dist && j2w -i build/bundle.js --initLocation http://bundler.localhost -o dist/bundler.wasm", "build:debug": "node build.mjs && mkdirp dist && j2w -d -i build/bundle.js --initLocation http://bundler.localhost -o dist/bundler.wasm", diff --git a/packages/typescript/sandbox/package-lock.json b/packages/typescript/sandbox/package-lock.json index fb241ce..56f7662 100644 --- a/packages/typescript/sandbox/package-lock.json +++ b/packages/typescript/sandbox/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "ts-sandbox", "version": "0.1.0", - "license": "Apache-2.0", + "license": "Apache-2.0 WITH LLVM-exception", "dependencies": { "@spinframework/build-tools": "^2.1.0", "@spinframework/spin-kv": "1.0.1", diff --git a/packages/typescript/sandbox/package.json b/packages/typescript/sandbox/package.json index a6ea03b..9c128e5 100644 --- a/packages/typescript/sandbox/package.json +++ b/packages/typescript/sandbox/package.json @@ -3,7 +3,7 @@ "private": true, "version": "0.1.0", "description": "Wasm sandbox that executes dynamic JS/TS code via Spin", - "license": "Apache-2.0", + "license": "Apache-2.0 WITH LLVM-exception", "main": "index.js", "type": "module", "scripts": { diff --git a/sdk/README.md b/sdk/README.md index d6cc111..c9c39ba 100644 --- a/sdk/README.md +++ b/sdk/README.md @@ -58,7 +58,13 @@ await runner.run(args.code, { }); ``` -For reuse across chat turns, store the UUID server-side with its owner and check ownership on every request. IDs select namespaces; they are not authorization. Never accept raw IDs from model output or unchecked client input. Use separate IDs for separate users/conversations, and define quotas and cleanup: abandoning an ID does not delete its KV data. Resumable side tracks and KV cloning are not provided. +For reuse across chat turns, store the UUID server-side with its owner and check ownership on every request. IDs select namespaces; they are not authorization. Never accept raw IDs from model output or unchecked client input. Use separate IDs for separate users/conversations, and define quotas and cleanup: abandoning an ID does not delete its KV data. After stopping all writers, use `await javascript.kv(sessionId).clear()` to remove the namespace's keys. This operation is not transactional; a failure may leave some keys behind and can be retried. Resumable side tracks and KV cloning are not provided. + +`allowedHosts` entries use `scheme://host[:port]`, for example `https://api.example.com` +or `https://*.example.com:*`. Wildcards match subdomains only, wildcard hosts grant no +access, and malformed entries return 400. The Spin manifest allowlist remains authoritative. +Private routes are reachable by any component granted the corresponding service-chaining +permission, so only trusted components should be granted access. ## Backends diff --git a/sdk/package-lock.json b/sdk/package-lock.json index 3fba78d..e6bf0ca 100644 --- a/sdk/package-lock.json +++ b/sdk/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "@spinframework/sandbox", "version": "0.1.0", - "license": "Apache-2.0", + "license": "Apache-2.0 WITH LLVM-exception", "devDependencies": { "typescript": "^5.6.0" } diff --git a/sdk/package.json b/sdk/package.json index f44bbc7..de14164 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -3,7 +3,7 @@ "version": "0.1.0", "description": "An extensible client for sandboxed code execution from a Spin application. Ships a Wasm code-interpreter backend; extensible to other backends.", "type": "module", - "license": "Apache-2.0", + "license": "Apache-2.0 WITH LLVM-exception", "exports": { ".": "./src/index.ts", "./core": "./src/core/index.ts", diff --git a/sdk/src/core/types.ts b/sdk/src/core/types.ts index 4a6652f..6d77e7e 100644 --- a/sdk/src/core/types.ts +++ b/sdk/src/core/types.ts @@ -69,7 +69,7 @@ export interface RunOpts { lang?: Language; /** * Per-run outbound allow-list. Default-deny: an empty/omitted list blocks all - * egress. + * egress. Entries use scheme://host[:port]; *. matches subdomains only. */ allowedHosts?: string[]; /** Enables access to the sandbox's scoped KV store for this run. Default: false. */ diff --git a/sdk/src/interpreter/index.ts b/sdk/src/interpreter/index.ts index d42b1bf..03cc605 100644 --- a/sdk/src/interpreter/index.ts +++ b/sdk/src/interpreter/index.ts @@ -321,6 +321,10 @@ export class InterpreterKV { return this.eval(`out({ v: s.getKeys() });`, "").then((r) => r.v); } + async clear(): Promise { + await this.eval(`for (const key of s.getKeys()) s.delete(key); out({ ok: true });`, ""); + } + // Runs a KV snippet against this namespace and parses the JSON it prints. private async eval(bodyExpr: string, key: string): Promise<{ v: T }> { const code = diff --git a/sdk/test/components.test.ts b/sdk/test/components.test.ts index 6813329..ff6e42a 100644 --- a/sdk/test/components.test.ts +++ b/sdk/test/components.test.ts @@ -38,8 +38,14 @@ if (!baseUrl) { const kv = Interpreter.javascript({ baseUrl }).kv(namespace); await kv.setJson("answer", 42); + await kv.setJson("other", "value"); assert.equal(await kv.getJson("answer"), 42); - await kv.delete("answer"); + const other = Interpreter.javascript({ baseUrl }).kv(`${namespace}-other`); + await other.setJson("answer", 99); + await kv.clear(); assert.equal(await kv.getJson("answer"), null); + assert.deepEqual(await kv.keys(), []); + assert.equal(await other.getJson("answer"), 99); + await other.clear(); }); } \ No newline at end of file diff --git a/sdk/test/interpreter.test.ts b/sdk/test/interpreter.test.ts index a374787..7f652f0 100644 --- a/sdk/test/interpreter.test.ts +++ b/sdk/test/interpreter.test.ts @@ -25,7 +25,7 @@ test("run() maps the main-program shape and selects the route + envelope", async const mock = mockFetch(() => ({ body: JSON.stringify({ stdout: "42\n", stderr: "", error: null }) })); const itp = new Interpreter({ baseUrl: "http://wasm.spin.internal/", fetch: mock.fn }); - const res = await itp.run("print(6*7)", { lang: "python", identity: "job-1", allowedHosts: ["api.x.com"], kvEnabled: true }); + const res = await itp.run("print(6*7)", { lang: "python", identity: "job-1", allowedHosts: ["https://api.x.com"], kvEnabled: true }); assert.equal(res.stdout, "42\n"); assert.equal(res.error, undefined); @@ -36,7 +36,7 @@ test("run() maps the main-program shape and selects the route + envelope", async const env = JSON.parse(mock.calls[0].init.body); assert.equal(env.code, "print(6*7)"); assert.equal(env.sandboxId, "job-1"); - assert.deepEqual(env.allowedHosts, ["api.x.com"]); + assert.deepEqual(env.allowedHosts, ["https://api.x.com"]); assert.equal(env.kvEnabled, true); }); @@ -119,6 +119,19 @@ test("an unbound client retains access to both language routes and JavaScript KV assert.equal(itp.capabilities().arbitraryImage, true); }); +test("KV clear runs in the selected namespace and propagates errors", async () => { + const mock = mockFetch(() => ({ body: JSON.stringify({ stdout: '{"ok":true}\n', stderr: "", error: null }) })); + const itp = Interpreter.javascript({ baseUrl: "http://ts", fetch: mock.fn }); + await itp.kv("tenant-a").clear(); + const envelope = JSON.parse(mock.calls[0].init.body); + assert.equal(envelope.sandboxId, "tenant-a"); + assert.equal(envelope.kvEnabled, true); + assert.match(envelope.code, /s\.getKeys\(\).*s\.delete\(key\)/); + + const failing = mockFetch(() => ({ body: JSON.stringify({ stdout: "", stderr: "", error: "denied" }) })); + await assert.rejects(() => Interpreter.javascript({ baseUrl: "http://ts", fetch: failing.fn }).kv("tenant-a").clear(), /denied/); +}); + test("run() surfaces a runtime error string as Result.error (data, not throw)", async () => { const mock = mockFetch(() => ({ body: JSON.stringify({ stdout: "", stderr: "", error: "Traceback...\nNameError: x" }), diff --git a/tests/bodies/py-egress-allow.json b/tests/bodies/py-egress-allow.json index 97335f2..d081781 100644 --- a/tests/bodies/py-egress-allow.json +++ b/tests/bodies/py-egress-allow.json @@ -2,6 +2,6 @@ "code": "from spin_sdk.http import send, Request\ntry:\n r = send(Request(\"GET\", \"https://example.com/\", {}, None))\n print(\"ALLOWED status=\" + str(r.status))\nexcept Exception as e:\n print(\"DENIED: \" + type(e).__name__ + \": \" + str(e))", "sandboxId": "egress-test", "allowedHosts": [ - "example.com" + "https://example.com" ] } diff --git a/tests/bodies/py-egress-internal.json b/tests/bodies/py-egress-internal.json index 1cfcb6c..32abdb2 100644 --- a/tests/bodies/py-egress-internal.json +++ b/tests/bodies/py-egress-internal.json @@ -2,6 +2,6 @@ "code": "from spin_sdk.http import send, Request\ntry:\n r = send(Request(\"GET\", \"http://169.254.169.254/latest/meta-data/\", {}, None))\n print(\"ALLOWED status=\" + str(r.status))\nexcept Exception as e:\n print(\"DENIED: \" + type(e).__name__ + \": \" + str(e))", "sandboxId": "egress-test", "allowedHosts": [ - "169.254.169.254" + "http://169.254.169.254" ] } diff --git a/tests/bodies/py-egress-star.json b/tests/bodies/py-egress-star.json index b5dde5e..a87739d 100644 --- a/tests/bodies/py-egress-star.json +++ b/tests/bodies/py-egress-star.json @@ -2,6 +2,6 @@ "code": "from spin_sdk.http import send, Request\ntry:\n r = send(Request(\"GET\", \"https://example.com/\", {}, None))\n print(\"ALLOWED status=\" + str(r.status))\nexcept Exception as e:\n print(\"DENIED: \" + type(e).__name__ + \": \" + str(e))", "sandboxId": "egress-test", "allowedHosts": [ - "*" + "*://*:*" ] } diff --git a/tests/bodies/ts-egress-allow.json b/tests/bodies/ts-egress-allow.json index e40652d..4cc15fb 100644 --- a/tests/bodies/ts-egress-allow.json +++ b/tests/bodies/ts-egress-allow.json @@ -1,5 +1,5 @@ { "code": "try {\n const r = await fetch(\"https://example.com/\");\n console.log(\"ALLOWED status=\" + r.status);\n} catch (e) {\n console.log(\"DENIED: \" + (e && e.message ? e.message : e));\n}", "sandboxId": "egress-test", - "allowedHosts": ["example.com"] + "allowedHosts": ["https://example.com"] } diff --git a/tests/bodies/ts-egress-internal.json b/tests/bodies/ts-egress-internal.json index d876382..f8814fa 100644 --- a/tests/bodies/ts-egress-internal.json +++ b/tests/bodies/ts-egress-internal.json @@ -1,5 +1,5 @@ { "code": "try {\n await fetch(\"http://169.254.169.254/latest/meta-data/\");\n console.log(\"ALLOWED\");\n} catch (e) {\n console.log(\"DENIED: \" + (e && e.message ? e.message : e));\n}", "sandboxId": "egress-test", - "allowedHosts": ["169.254.169.254"] + "allowedHosts": ["http://169.254.169.254"] } diff --git a/tests/bodies/ts-egress-star.json b/tests/bodies/ts-egress-star.json index e10c5e0..4bcf387 100644 --- a/tests/bodies/ts-egress-star.json +++ b/tests/bodies/ts-egress-star.json @@ -1,5 +1,5 @@ { "code": "try {\n await fetch(\"https://example.com/\");\n console.log(\"ALLOWED\");\n} catch (e) {\n console.log(\"DENIED: \" + (e && e.message ? e.message : e));\n}", "sandboxId": "egress-test", - "allowedHosts": ["*"] + "allowedHosts": ["*://*:*"] } diff --git a/tests/smoke.hurl b/tests/smoke.hurl index f318b2a..5820a8e 100644 --- a/tests/smoke.hurl +++ b/tests/smoke.hurl @@ -133,6 +133,20 @@ jsonpath "$.stdout" contains "leaked=null" jsonpath "$.stdout" contains "keys=[]" # --- Egress (TypeScript): default-deny with no allowedHosts --- +POST {{base_url}}/ts/run +content-type: application/json +{"code":"console.log('should not run')","sandboxId":"egress-test","allowedHosts":["example.com"]} +HTTP 400 +[Asserts] +jsonpath "$.message" contains "allowedHosts" + +POST {{base_url}}/py/run +content-type: application/json +{"code":"print('should not run')","sandboxId":"egress-test","allowedHosts":["https://example.com/path"]} +HTTP 400 +[Asserts] +jsonpath "$.message" contains "allowedHosts" + POST {{base_url}}/ts/run content-type: application/json file,bodies/ts-egress-deny.json; @@ -141,7 +155,7 @@ HTTP 200 jsonpath "$.stdout" contains "DENIED" jsonpath "$.stdout" not contains "ALLOWED" -# --- Egress: a bare "*" in the per-request allow-list must NOT grant all --- +# --- Egress: a wildcard host in the per-request allow-list must NOT grant all --- POST {{base_url}}/ts/run content-type: application/json file,bodies/ts-egress-star.json;