Skip to content
Open
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
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,10 @@ For simple projects, `workerd serve wrangler.jsonc` also accepts a Wrangler
config. `main` is bundled with esbuild, as Wrangler does. The supported fields
are `name`, `main`, `compatibility_date`, `compatibility_flags`, `vars`,
`durable_objects`, `exports`, `migrations`, `no_bundle`, `$schema` and, with
`--experimental`, `kv_namespaces`, `triggers.crons`, `queues` and `workflows`;
any other field is an error. Each KV namespace is one Durable Object, so its
throughput is that of one object.
`--experimental`, `kv_namespaces`, `triggers.crons`, `queues`, `workflows` and
`assets`; any other field is an error. With `assets`, `main` may be left out to
serve files only, and then fields that need a Worker are an error. Each KV
namespace is one Durable Object, so its throughput is that of one object.

A simple "Hello World!" config file might look like:

Expand Down
1 change: 1 addition & 0 deletions deps/rust/Cargo.lock

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

2 changes: 2 additions & 0 deletions deps/rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ http-body = "1"
httpdate = "1"
percent-encoding = "2"
url = "2"
# The server's assets service: the `_headers`, `_redirects` and `.assetsignore` rules.
regex = { version = "1", default-features = false, features = ["std", "perf"] }
# The server's CryptoKey bindings: hex key material.
data-encoding = "2"
# `workerd test`: the service and entrypoint filters.
Expand Down
7 changes: 6 additions & 1 deletion deps/rust/cargo-bazel-lock.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"binary_crates": [
"capnpc 0.27.0"
],
"checksum": "825692ad90398af9f1f5eceade32827bcdd59a8cd38054a0cbb4027f3b8a0634",
"checksum": "eb9ab79751c275672f5b39535545a7891464446ef52bbffe2e1e34e60eb284e5",
"conditions": {
"aarch64-apple-darwin": [
"aarch64-apple-darwin"
Expand Down Expand Up @@ -2935,6 +2935,10 @@
"id": "rand 0.9.5",
"target": "rand"
},
{
"id": "regex 1.13.1",
"target": "regex"
},
{
"id": "ring 0.17.14",
"target": "ring"
Expand Down Expand Up @@ -15873,6 +15877,7 @@
"proc-macro2 1.0.107",
"quote 1.0.47",
"rand 0.9.5",
"regex 1.13.1",
"ring 0.17.14",
"ruff_python_ast 0.0.0",
"ruff_python_parser 0.0.0",
Expand Down
2 changes: 1 addition & 1 deletion src/rust/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ _Snapshot — the set drifts as crates come and go; `bazel query //src/rust/...`
- In a crate root that attribute would cover the whole crate, so there the item takes `#[expect(unsafe_code, reason = "...")]` instead: the bridge module (after its `#[cxx::bridge]` line), or the function or `impl`.
- What can fail returns a `Result`; a panic asserts what cannot happen. `unreachable!` says exactly that and is allowed everywhere. Any other deliberate panic takes `#[expect(clippy::<lint>, reason = "...")]` on its function.
- Test code is not held to any of this. A module's `<module>-test.rs` is compiled only into the crate's `<name>_test` target, and test targets get no lint levels from the macros; neither do `testonly` crates (`wd_rust_crate(testonly = True)`: test harnesses, the Rust half of a C++ test). So a test file needs no opt-ins, and the production files are still checked where the library is built.
- `#![forbid(unsafe_code)]` in a crate root (`memory-cache`, `jsg-macros`) is stronger than the default and stays.
- `#![forbid(unsafe_code)]` in a crate root (`memory-cache`, `jsg-macros`, `assets-router`) is stronger than the default and stays.
- The crates derived from upstream cxx (`src/rust/cxx/{src,syntax,gen,macro,tests}`) are outside these defaults; the `kj-rs*` crates beside them are inside.
- **Tests**: a module's unit tests live beside it in `<module>-test.rs` (`dns.rs` → `dns-test.rs`, `lib.rs` → `lib-test.rs`), never in an inline `mod tests { ... }`, so a diff shows production changes and test changes as separate files. See UNIT TEST FILES below. JSG tests use `jsg_test::Harness::run_in_context()`; `Harness::with_flags(|mut f| f.set_<flag>(true))` sets raw compat flags and uses workers' shared `configureJsgIsolate()` helper for isolate-level JSG settings. It starts with all flags false and applies no compatibility date or flag implications; see `jsg/README.md` §Testing with flags. `jsg_test::set_autogates(&["gate-name"])` configures the process's autogates for as long as the returned guard lives. Always run the full `src/rust/...` test suite (`bazel test //src/rust/...`) rather than targeting a single crate — changes in shared crates like `jsg` or `jsg-macros` can break downstream consumers
- **FFI pointers**: functions receiving raw pointers must be `unsafe fn` (see `jsg/README.md`)
Expand Down
12 changes: 12 additions & 0 deletions src/rust/assets-router/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
load("//:build/wd_rust_crate.bzl", "wd_rust_crate")

wd_rust_crate(
name = "assets-router",
test_deps = ["@crates_vendor//serde_json"],
visibility = ["//visibility:public"],
deps = [
"@crates_vendor//regex",
"@crates_vendor//serde",
"@crates_vendor//url",
],
)
121 changes: 121 additions & 0 deletions src/rust/assets-router/base_path-test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
use super::*;

fn normalize(value: &str) -> Result<String, &'static str> {
BasePath::normalize(value).map(|base| base.as_str().to_owned())
}

fn base(value: &str) -> BasePath {
BasePath::normalize(value).unwrap()
}

// Upstream: `utils/testdata/base-path-normalization.json` (contract version 1), the vectors
// the control plane's normalization is held to as well.
#[test]
fn normalize_matches_the_shared_contract() {
for (name, input, canonical) in [
("root", "/", Some("/")),
("absolute", "/docs", Some("/docs/")),
("relative", "./docs", Some("/docs/")),
("duplicate segments", "/a//b", Some("/a/b/")),
("dot segments", "/a/./b/../c", Some("/a/c/")),
("above root", "../../docs", Some("/docs/")),
("unicode", "/café/naïve", Some("/café/naïve/")),
("empty", "", None),
("url", "https://example.com/docs", None),
("protocol relative url", "//example.com/docs", None),
("backslash", "/a\\b", None),
("query", "/docs?lang=en", None),
("fragment", "/docs#intro", None),
("percent encoding", "/docs%2Fapi", None),
("control character", "/docs\u{1}api", None),
] {
assert_eq!(normalize(input).ok().as_deref(), canonical, "{name}");
}
}

// Upstream: utils/tests/base-path.test.ts `normalizeBasePath > valid values`.
#[test]
fn normalize_accepts_pathnames() {
assert_eq!(normalize("/subpath").unwrap(), "/subpath/");
assert_eq!(normalize("/a/b/c").unwrap(), "/a/b/c/");
assert_eq!(normalize("subpath").unwrap(), "/subpath/");
assert_eq!(normalize("../app").unwrap(), "/app/");
assert_eq!(normalize("/subpath/").unwrap(), "/subpath/");
assert_eq!(normalize("/.").unwrap(), "/");

let long = format!("/{}", "😀".repeat(2000));
assert_eq!(normalize(&long).unwrap(), format!("{long}/"));
}

// Upstream: utils/tests/base-path.test.ts `normalizeBasePath > invalid values`.
#[test]
fn normalize_rejects_values_that_are_not_pathnames() {
assert_eq!(normalize(""), Err("The value must not be empty."));
assert_eq!(
normalize("/sub\\path"),
Err("The value must not contain backslashes.")
);
assert_eq!(
normalize("/sub\u{0}path"),
Err("The value must not contain control characters.")
);
assert_eq!(
normalize("/sub\u{7f}path"),
Err("The value must not contain control characters.")
);
assert_eq!(
normalize("/subpath?a=1"),
Err("The value must not contain query strings or fragments.")
);
assert_eq!(
normalize("/subpath#frag"),
Err("The value must not contain query strings or fragments.")
);
assert_eq!(
normalize("/sub%2Fpath"),
Err("The value must not contain percent-encoded sequences.")
);
assert_eq!(
normalize("/sub%20path"),
Err("The value must not contain percent-encoded sequences.")
);
assert_eq!(
normalize("//a"),
Err("The value must be a pathname, not a URL.")
);
assert_eq!(
normalize("https://example.com/subpath"),
Err("The value must be a pathname, not a URL.")
);
assert_eq!(
normalize("data:text/plain,hello"),
Err("The value must be a pathname, not a URL.")
);
}

#[test]
fn normalize_only_treats_a_leading_scheme_as_a_url() {
assert_eq!(normalize("/a:b").unwrap(), "/a:b/");
assert_eq!(normalize("1a:b").unwrap(), "/1a:b/");
}

// Upstream: asset-worker/tests/base-path.test.ts `stripBasePath`.
#[test]
fn strip_maps_public_paths_to_asset_paths() {
assert_eq!(base("/").strip("/foo/bar"), Some("/foo/bar"));
assert_eq!(base("/subpath/").strip("/subpath/foo"), Some("/foo"));
assert_eq!(base("/subpath/").strip("/subpath"), Some("/"));
assert_eq!(base("/subpath/").strip("/subpath/"), Some("/"));
assert_eq!(base("/subpath/").strip("/subpath-other/foo"), None);
assert_eq!(base("/subpath/").strip("/other"), None);
assert_eq!(base("/路径/").strip("/路径/foo"), Some("/foo"));
}

// Upstream: asset-worker/tests/base-path.test.ts `addBasePath`.
#[test]
fn add_maps_asset_paths_to_public_paths() {
assert_eq!(base("/").add("/foo/"), "/foo/");
assert_eq!(base("/subpath/").add("/"), "/subpath/");
assert_eq!(base("/subpath/").add("/foo/"), "/subpath/foo/");
assert_eq!(base("/subpath/").add(""), "/subpath");
}
106 changes: 106 additions & 0 deletions src/rust/assets-router/base_path.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
// Copyright (c) 2026 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
// https://opensource.org/licenses/Apache-2.0

//! The `base_path` under which assets are served.
//!
//! Ported from workers-sdk's workers-shared, `utils/base-path.ts` and
//! `asset-worker/src/utils/base-path.ts`.

/// The root `/`, or a pathname with a leading and a trailing slash, such as `/subpath/`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BasePath(String);

impl Default for BasePath {
fn default() -> Self {
Self("/".to_owned())
}
}

impl BasePath {
/// Mirrors `normalizeBasePath`, and its messages.
pub fn normalize(value: &str) -> Result<Self, &'static str> {
let (scheme, _) = value.split_once(':').unwrap_or_default();
let mut scheme_chars = scheme.chars();
let has_scheme = scheme_chars.next().is_some_and(|c| c.is_ascii_alphabetic())
&& scheme_chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '-'));
for (invalid, message) in [
(value.is_empty(), "The value must not be empty."),
(
value.starts_with("//") || has_scheme,
"The value must be a pathname, not a URL.",
),
(
value.contains('\\'),
"The value must not contain backslashes.",
),
(
value.chars().any(|c| c <= '\u{1f}' || c == '\u{7f}'),
"The value must not contain control characters.",
),
(
value.contains(['?', '#']),
"The value must not contain query strings or fragments.",
),
(
value.contains('%'),
"The value must not contain percent-encoded sequences.",
),
] {
if invalid {
return Err(message);
}
}
let mut segments = Vec::new();
for segment in value.split('/') {
match segment {
"" | "." => {}
".." => _ = segments.pop(),
segment => segments.push(segment),
}
}
if segments.is_empty() {
return Ok(Self::default());
}
Ok(Self(format!("/{}/", segments.join("/"))))
}

pub fn as_str(&self) -> &str {
&self.0
}

pub fn is_root(&self) -> bool {
self.0 == "/"
}

/// The base without its trailing slash, e.g. `/subpath`, unless it is the root.
pub(crate) fn without_trailing_slash(&self) -> Option<&str> {
self.0.strip_suffix('/').filter(|base| !base.is_empty())
}

/// The path under the base of a decoded pathname, matching whole segments. Mirrors
/// `stripBasePath`.
pub fn strip<'a>(&self, path: &'a str) -> Option<&'a str> {
match self.without_trailing_slash() {
None => Some(path),
Some(base) if path == base => Some("/"),
Some(base) => path
.strip_prefix(self.as_str())
.map(|_| &path[base.len()..]),
}
}

/// The public path of a path under the base, where `""` is the base without its trailing
/// slash. Mirrors `addBasePath`.
pub fn add(&self, path: &str) -> String {
match self.without_trailing_slash() {
None => path.to_owned(),
Some(_) if path == "/" => self.0.clone(),
Some(base) => format!("{base}{path}"),
}
}
}

#[cfg(test)]
#[path = "base_path-test.rs"]
mod tests;
Loading
Loading