diff --git a/crates/bindings-cpp/include/spacetimedb/router.h b/crates/bindings-cpp/include/spacetimedb/router.h index 00808f8bdfd..fdbd8983434 100644 --- a/crates/bindings-cpp/include/spacetimedb/router.h +++ b/crates/bindings-cpp/include/spacetimedb/router.h @@ -100,8 +100,36 @@ class Router { std::abort(); } + static constexpr char route_wildcard = '*'; + static bool character_is_acceptable_for_route_path(char c) { - return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '~' || c == '/'; + return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '~' || c == '/' || + c == route_wildcard; + } + + // True if `*` appears at most once in `path`, and only as its final character. + static bool wildcard_is_only_trailing(const std::string& path) { + std::string prefix = (!path.empty() && path.back() == route_wildcard) ? path.substr(0, path.size() - 1) : path; + return prefix.find(route_wildcard) == std::string::npos; + } + + // True if two route paths can match the same request path. + static bool route_paths_overlap(const std::string& a, const std::string& b) { + const bool a_is_wildcard = !a.empty() && a.back() == route_wildcard; + const bool b_is_wildcard = !b.empty() && b.back() == route_wildcard; + const std::string a_prefix = a_is_wildcard ? a.substr(0, a.size() - 1) : std::string(); + const std::string b_prefix = b_is_wildcard ? b.substr(0, b.size() - 1) : std::string(); + + if (a_is_wildcard && b_is_wildcard) { + return a_prefix.starts_with(b_prefix) || b_prefix.starts_with(a_prefix); + } + if (a_is_wildcard) { + return b.starts_with(a_prefix); + } + if (b_is_wildcard) { + return a.starts_with(b_prefix); + } + return a == b; } static void assert_valid_path(const std::string& path) { @@ -110,9 +138,14 @@ class Router { } for (char c : path) { if (!character_is_acceptable_for_route_path(c)) { - fail_router_registration("Route paths may contain only ASCII lowercase letters, digits and `-_~/`: " + path); + fail_router_registration( + "Route paths may contain only ASCII lowercase letters, digits and `-_~/*`: " + path + ); } } + if (!wildcard_is_only_trailing(path)) { + fail_router_registration("Route paths may contain `*` only as the final character: " + path); + } } static std::string join_paths(const std::string& prefix, const std::string& suffix) { @@ -134,7 +167,7 @@ class Router { } static bool routes_overlap(const RouteSpec& a, const RouteSpec& b) { - if (a.path != b.path) { + if (!route_paths_overlap(a.path, b.path)) { return false; } if (a.method.is<0>() || b.method.is<0>()) { diff --git a/crates/bindings-csharp/Runtime.Tests/RouterTests.cs b/crates/bindings-csharp/Runtime.Tests/RouterTests.cs index 7f63aadf94d..64a40448799 100644 --- a/crates/bindings-csharp/Runtime.Tests/RouterTests.cs +++ b/crates/bindings-csharp/Runtime.Tests/RouterTests.cs @@ -45,6 +45,43 @@ public void RejectsInvalidPathCharacters() Assert.Contains("Route paths may contain only", ex.Message); } + [Fact] + public void AcceptsTrailingWildcardAndRejectsWildcardElsewhere() + { + Assert.NotNull(Router.New().Get("/webhooks/*", TestHandlers.GetHandler)); + + var ex = Assert.Throws( + () => Router.New().Get("/mid*path", TestHandlers.GetHandler) + ); + + Assert.Contains("`*` only as the final character", ex.Message); + } + + [Fact] + public void RejectsWildcardRouteOverlappingStaticRoute() + { + var ex = Assert.Throws( + () => + Router + .New() + .Get("/webhooks/*", TestHandlers.GetHandler) + .Get("/webhooks/github", TestHandlers.GetHandler) + ); + + Assert.Contains("Route conflict", ex.Message); + } + + [Fact] + public void AllowsWildcardRouteAndCoveredPathWithOtherMethod() + { + var router = Router + .New() + .Get("/webhooks/*", TestHandlers.GetHandler) + .Post("/webhooks/github", TestHandlers.PostHandler); + + Assert.NotNull(router); + } + [Fact] public void NestJoinsPathsWithoutDoubleSlash() { diff --git a/crates/bindings-csharp/Runtime/Router.cs b/crates/bindings-csharp/Runtime/Router.cs index 7377d7b2561..69c9b32dba6 100644 --- a/crates/bindings-csharp/Runtime/Router.cs +++ b/crates/bindings-csharp/Runtime/Router.cs @@ -15,7 +15,38 @@ string HandlerFunction ); private const string AcceptableRoutePathCharsHumanDescription = - "ASCII lowercase letters, digits and `-_~/`"; + "ASCII lowercase letters, digits and `-_~/*`"; + + private const char RouteWildcard = '*'; + + /// True if * appears at most once in , and only as its final character. + private static bool WildcardIsOnlyTrailing(string path) + { + var prefix = path.EndsWith(RouteWildcard) ? path[..^1] : path; + return !prefix.Contains(RouteWildcard); + } + + /// True if two route paths can match the same request path. + private static bool RoutePathsOverlap(string a, string b) + { + var aPrefix = a.EndsWith(RouteWildcard) ? a[..^1] : null; + var bPrefix = b.EndsWith(RouteWildcard) ? b[..^1] : null; + + if (aPrefix is not null && bPrefix is not null) + { + return aPrefix.StartsWith(bPrefix, StringComparison.Ordinal) + || bPrefix.StartsWith(aPrefix, StringComparison.Ordinal); + } + if (aPrefix is not null) + { + return b.StartsWith(aPrefix, StringComparison.Ordinal); + } + if (bPrefix is not null) + { + return a.StartsWith(bPrefix, StringComparison.Ordinal); + } + return string.Equals(a, b, StringComparison.Ordinal); + } private readonly List routes; @@ -130,7 +161,7 @@ private static string JoinPaths(string prefix, string suffix) private static bool RoutesOverlap(RouteSpec a, RouteSpec b) { - if (!string.Equals(a.Path, b.Path, StringComparison.Ordinal)) + if (!RoutePathsOverlap(a.Path, b.Path)) { return false; } @@ -157,8 +188,15 @@ private static void AssertValidPath(string path) ); } } + if (!WildcardIsOnlyTrailing(path)) + { + throw new ArgumentException( + $"Route paths may contain `*` only as the final character: {path}", + nameof(path) + ); + } } private static bool CharacterIsAcceptableForRoutePath(char c) => - c is (>= 'a' and <= 'z') or (>= '0' and <= '9') or '-' or '_' or '~' or '/'; + c is (>= 'a' and <= 'z') or (>= '0' and <= '9') or '-' or '_' or '~' or '/' or RouteWildcard; } diff --git a/crates/bindings-typescript/src/server/http_handlers.ts b/crates/bindings-typescript/src/server/http_handlers.ts index 6f729467284..19b2b3051df 100644 --- a/crates/bindings-typescript/src/server/http_handlers.ts +++ b/crates/bindings-typescript/src/server/http_handlers.ts @@ -55,7 +55,10 @@ type RouteSpec = { }; const ACCEPTABLE_ROUTE_PATH_CHARS_HUMAN_DESCRIPTION = - 'ASCII lowercase letters, digits and `-_~/`'; + 'ASCII lowercase letters, digits and `-_~/*`'; + +/** The character which, as the final character of a route path, matches any remaining path. */ +const ROUTE_WILDCARD = '*'; export const makeRequest = Symbol('makeRequest'); @@ -96,10 +99,33 @@ function characterIsAcceptableForRoutePath(c: string) { c === '-' || c === '_' || c === '~' || - c === '/' + c === '/' || + c === ROUTE_WILDCARD ); } +/** True if `*` appears at most once in `path`, and only as its final character. */ +function wildcardIsOnlyTrailing(path: string) { + const prefix = path.endsWith(ROUTE_WILDCARD) ? path.slice(0, -1) : path; + return !prefix.includes(ROUTE_WILDCARD); +} + +/** True if two route paths can match the same request path. */ +function routePathsOverlap(a: string, b: string) { + const aPrefix = a.endsWith(ROUTE_WILDCARD) ? a.slice(0, -1) : null; + const bPrefix = b.endsWith(ROUTE_WILDCARD) ? b.slice(0, -1) : null; + if (aPrefix !== null && bPrefix !== null) { + return aPrefix.startsWith(bPrefix) || bPrefix.startsWith(aPrefix); + } + if (aPrefix !== null) { + return b.startsWith(aPrefix); + } + if (bPrefix !== null) { + return a.startsWith(bPrefix); + } + return a === b; +} + function assertValidPath(path: string) { if (path !== '' && !path.startsWith('/')) { throw new TypeError(`Route paths must start with \`/\`: ${path}`); @@ -109,6 +135,11 @@ function assertValidPath(path: string) { `Route paths may contain only ${ACCEPTABLE_ROUTE_PATH_CHARS_HUMAN_DESCRIPTION}: ${path}` ); } + if (!wildcardIsOnlyTrailing(path)) { + throw new TypeError( + `Route paths may contain \`*\` only as the final character: ${path}` + ); + } } function routesOverlap(a: RouteSpec, b: RouteSpec) { @@ -123,7 +154,7 @@ function routesOverlap(a: RouteSpec, b: RouteSpec) { }; return ( - a.path === b.path && + routePathsOverlap(a.path, b.path) && (a.method.tag === 'Any' || b.method.tag === 'Any' || (a.method.tag === 'Method' && diff --git a/crates/bindings-typescript/tests/http_handlers.test.ts b/crates/bindings-typescript/tests/http_handlers.test.ts index c77f700a3dc..4b6588cd2c9 100644 --- a/crates/bindings-typescript/tests/http_handlers.test.ts +++ b/crates/bindings-typescript/tests/http_handlers.test.ts @@ -168,10 +168,29 @@ describe('http router', async () => { it('rejects invalid path characters', () => { expect(() => new Router().get('/Hello', handler())).toThrow( - 'Route paths may contain only ASCII lowercase letters, digits and `-_~/`: /Hello' + 'Route paths may contain only ASCII lowercase letters, digits and `-_~/*`: /Hello' ); }); + it('accepts a trailing wildcard and rejects a wildcard elsewhere', () => { + expect(() => new Router().get('/webhooks/*', handler())).not.toThrow(); + expect(() => new Router().get('/mid*path', handler())).toThrow( + 'Route paths may contain `*` only as the final character: /mid*path' + ); + }); + + it('rejects a wildcard route that overlaps a static route', () => { + expect(() => + new Router().get('/webhooks/*', handler()).get('/webhooks/github', handler()) + ).toThrow('Route conflict for `/webhooks/github`'); + }); + + it('allows a wildcard route and a covered path with another method', () => { + expect(() => + new Router().get('/webhooks/*', handler()).post('/webhooks/github', handler()) + ).not.toThrow(); + }); + it('allows distinct methods on the same path', () => { expect(() => new Router().get('/echo', handler()).post('/echo', handler()) diff --git a/crates/bindings/src/http.rs b/crates/bindings/src/http.rs index 3b63b59f73b..02bbd5f6917 100644 --- a/crates/bindings/src/http.rs +++ b/crates/bindings/src/http.rs @@ -24,7 +24,10 @@ use spacetimedb_lib::db::raw_def::v10::MethodOrAny; #[cfg(any(target_arch = "wasm32", feature = "unstable"))] use spacetimedb_lib::http as st_http; #[cfg(feature = "unstable")] -use spacetimedb_lib::http::{character_is_acceptable_for_route_path, ACCEPTABLE_ROUTE_PATH_CHARS_HUMAN_DESCRIPTION}; +use spacetimedb_lib::http::{ + character_is_acceptable_for_route_path, route_paths_overlap, wildcard_is_only_trailing, + ACCEPTABLE_ROUTE_PATH_CHARS_HUMAN_DESCRIPTION, +}; #[cfg(feature = "unstable")] use spacetimedb_lib::Identity; use spacetimedb_lib::TimeDuration; @@ -242,6 +245,9 @@ impl Handler { /// Only characters described by [`spacetimedb_lib::http::ACCEPTABLE_ROUTE_PATH_CHARS_HUMAN_DESCRIPTION`] /// are valid for use in paths. This set may be expanded in the future. /// +/// A path may end with a single `*`, which matches any remaining path, so `/webhooks/*` +/// matches `/webhooks/github` and `/webhooks/` but not `/webhooks`. +/// /// SpacetimeDB uses strict routing, meaning that trailing slashes `/` in paths are significant. /// `/foo` and `/foo/` are distinct paths. /// @@ -441,11 +447,14 @@ fn assert_valid_path(path: &str) { ACCEPTABLE_ROUTE_PATH_CHARS_HUMAN_DESCRIPTION ); } + if !wildcard_is_only_trailing(path) { + panic!("Route paths may contain `*` only as the final character: {path}"); + } } #[cfg(feature = "unstable")] fn routes_overlap(a: &RouteSpec, b: &RouteSpec) -> bool { - if a.path != b.path { + if !route_paths_overlap(&a.path, &b.path) { return false; } matches!(a.method, MethodOrAny::Any) || matches!(b.method, MethodOrAny::Any) || a.method == b.method diff --git a/crates/lib/src/http.rs b/crates/lib/src/http.rs index 137c3a9c306..3dda8cc1739 100644 --- a/crates/lib/src/http.rs +++ b/crates/lib/src/http.rs @@ -168,16 +168,112 @@ impl Response { /// True if `c` is a valid character to appear in the path of a user-defined HTTP route. /// -/// We permit only lowercase ASCII letters, ASCII digits, and `-_~/`. +/// We permit only lowercase ASCII letters, ASCII digits, and `-_~/*`. /// `/` is allowed specifically because it's the segment separator character. /// `-_~` seem harmless enough. +/// `*` is the wildcard character; it is valid only as the final character of a path, +/// where it matches any remaining path. [`wildcard_is_only_trailing`] checks that position. /// /// We've chosen an intentionally very restrictive set so that we can assign meaning to other characters in the future, -/// e.g. we may want to use `*` as a wildcard, `:` or `{}` to introduce path parameters, &c. +/// e.g. we may want to use `:` or `{}` to introduce path parameters. pub fn character_is_acceptable_for_route_path(c: char) -> bool { - c.is_ascii_lowercase() || c.is_ascii_digit() || "-_~/".contains(c) + c.is_ascii_lowercase() || c.is_ascii_digit() || "-_~/*".contains(c) } /// A human-readable description of the characters accepted by [`character_is_acceptable_for_route_path`], /// for use in error reporting. -pub const ACCEPTABLE_ROUTE_PATH_CHARS_HUMAN_DESCRIPTION: &str = "ASCII lowercase letters, digits and `-_~/`"; +pub const ACCEPTABLE_ROUTE_PATH_CHARS_HUMAN_DESCRIPTION: &str = "ASCII lowercase letters, digits and `-_~/*`"; + +/// The character which, as the final character of a route path, matches any remaining path. +pub const ROUTE_WILDCARD: char = '*'; + +/// True if `*` appears at most once in `path`, and only as its final character. +pub fn wildcard_is_only_trailing(path: &str) -> bool { + match path.strip_suffix(ROUTE_WILDCARD) { + Some(prefix) => !prefix.contains(ROUTE_WILDCARD), + None => !path.contains(ROUTE_WILDCARD), + } +} + +/// True if the route path `route_path` matches the request path `request_path`. +/// +/// A wildcard route matches any request path starting with the prefix before its `*`, +/// so `/webhooks/*` matches `/webhooks/github` and `/webhooks/` but not `/webhooks`. +/// A static route matches only itself. +pub fn route_path_matches(route_path: &str, request_path: &str) -> bool { + match route_path.strip_suffix(ROUTE_WILDCARD) { + Some(prefix) => request_path.starts_with(prefix), + None => route_path == request_path, + } +} + +/// True if two route paths can match the same request path. +/// +/// Static paths overlap only when they are equal; a wildcard path overlaps any path +/// which starts with the prefix before its `*`, including another wildcard. +pub fn route_paths_overlap(a: &str, b: &str) -> bool { + match (a.strip_suffix(ROUTE_WILDCARD), b.strip_suffix(ROUTE_WILDCARD)) { + (Some(a_prefix), Some(b_prefix)) => a_prefix.starts_with(b_prefix) || b_prefix.starts_with(a_prefix), + (Some(prefix), None) => b.starts_with(prefix), + (None, Some(prefix)) => a.starts_with(prefix), + (None, None) => a == b, + } +} + +#[cfg(test)] +mod route_path_tests { + use super::*; + + #[test] + fn wildcard_must_be_trailing() { + assert!(wildcard_is_only_trailing("/webhooks/*")); + assert!(wildcard_is_only_trailing("/webhooks")); + assert!(wildcard_is_only_trailing("")); + + // A lone `*` is correctly placed; it is rejected by the leading-slash rule, not here. + assert!(wildcard_is_only_trailing("*")); + assert!(!wildcard_is_only_trailing("/mid*path")); + assert!(!wildcard_is_only_trailing("/double**")); + assert!(!wildcard_is_only_trailing("/a/*/b")); + } + + #[test] + fn static_route_matches_only_itself() { + assert!(route_path_matches("/webhooks/github", "/webhooks/github")); + assert!(!route_path_matches("/webhooks/github", "/webhooks/github/")); + assert!(!route_path_matches("/webhooks", "/webhooks/github")); + } + + #[test] + fn wildcard_route_matches_the_remainder() { + assert!(route_path_matches("/webhooks/*", "/webhooks/github")); + assert!(route_path_matches("/webhooks/*", "/webhooks/")); + assert!(route_path_matches("/webhooks/*", "/webhooks/a/b")); + + // The prefix itself, without its trailing slash, is not matched. + assert!(!route_path_matches("/webhooks/*", "/webhooks")); + assert!(!route_path_matches("/webhooks/*", "/other/github")); + } + + #[test] + fn static_paths_overlap_only_when_equal() { + assert!(route_paths_overlap("/a", "/a")); + assert!(!route_paths_overlap("/a", "/b")); + assert!(!route_paths_overlap("/a", "/a/b")); + } + + #[test] + fn wildcard_overlaps_its_prefix_and_everything_below() { + assert!(route_paths_overlap("/a/*", "/a/b")); + assert!(route_paths_overlap("/a/b", "/a/*")); + assert!(!route_paths_overlap("/a/*", "/b/c")); + assert!(!route_paths_overlap("/a/*", "/a")); + } + + #[test] + fn wildcards_overlap_when_either_prefix_contains_the_other() { + assert!(route_paths_overlap("/a/*", "/a/b/*")); + assert!(route_paths_overlap("/a/*", "/a/*")); + assert!(!route_paths_overlap("/a/*", "/b/*")); + } +} diff --git a/crates/schema/src/def.rs b/crates/schema/src/def.rs index 0758a1b3083..d1ed1668f03 100644 --- a/crates/schema/src/def.rs +++ b/crates/schema/src/def.rs @@ -46,6 +46,7 @@ use spacetimedb_lib::db::raw_def::v9::{ }; use spacetimedb_lib::db::view::{extract_view_return_product_type_ref, ViewKind}; use spacetimedb_lib::environment::EnvironmentSchema; +use spacetimedb_lib::http::route_path_matches; use spacetimedb_lib::{hash_bytes, Hash as SpacetimeHash, ProductType, RawModuleDef}; use spacetimedb_primitives::{ ColId, ColList, ColOrCols, ColSet, HttpHandlerId, ProcedureId, ReducerId, TableId, ViewFnPtr, @@ -551,8 +552,9 @@ impl ModuleDef { path: &str, ) -> Option<(HttpHandlerId, &HttpHandlerDef, &HttpRouteDef)> { // TODO(perf): Replace this linear scan with a trie or other indexed routing structure. + // Validation rejects routes which could match the same request, so at most one does. for route in &self.http_routes { - if route.path.as_ref() != path { + if !route_path_matches(route.path.as_ref(), path) { continue; } let method_matches = matches!(route.method, MethodOrAny::Any) diff --git a/crates/schema/src/def/validate/v10.rs b/crates/schema/src/def/validate/v10.rs index f472165c74e..a66825a4889 100644 --- a/crates/schema/src/def/validate/v10.rs +++ b/crates/schema/src/def/validate/v10.rs @@ -5,7 +5,7 @@ use spacetimedb_lib::db::raw_def::v10::*; use spacetimedb_lib::db::raw_def::v9::Lifecycle; use spacetimedb_lib::db::view::{extract_view_return_product_type_ref, ViewKind}; use spacetimedb_lib::de::DeserializeSeed as _; -use spacetimedb_lib::http::character_is_acceptable_for_route_path; +use spacetimedb_lib::http::{character_is_acceptable_for_route_path, route_paths_overlap, wildcard_is_only_trailing}; use spacetimedb_primitives::ReducerId; use spacetimedb_sats::{AlgebraicType, Typespace, WithTypespace}; @@ -587,14 +587,17 @@ fn validate_http_route_path(path: &RawIdentifier) -> Result<()> { let path_str = path.as_ref(); if (!path_str.is_empty() && !path_str.starts_with('/')) || !path_str.chars().all(character_is_acceptable_for_route_path) + || !wildcard_is_only_trailing(path_str) { return Err(ValidationError::InvalidHttpRoutePath { path: path.clone() }.into()); } Ok(()) } +/// Two routes overlap when their paths can match the same request path and their methods +/// can match the same request method, so one of them would be unreachable. fn routes_overlap(a: &HttpRouteDef, b: &HttpRouteDef) -> bool { - if a.path != b.path { + if !route_paths_overlap(&a.path, &b.path) { return false; } matches!(a.method, MethodOrAny::Any) || matches!(b.method, MethodOrAny::Any) || a.method == b.method @@ -3033,6 +3036,10 @@ mod tests { "/backslash\\", "/caret^", "/percent%", + "*", + "/mid*path", + "/double**", + "/star*tail*", ] { builder.add_http_route("handle", MethodOrAny::Any, path); } @@ -3074,6 +3081,10 @@ mod tests { "/backslash\\", "/caret^", "/percent%", + "*", + "/mid*path", + "/double**", + "/star*tail*", ]; expected.sort_unstable(); @@ -3083,6 +3094,106 @@ mod tests { } } + #[test] + fn http_routes_wildcard_overlaps_static_path() { + let mut builder = RawModuleDefV10Builder::new(); + + builder.add_http_handler("handle"); + builder.add_http_route("handle", MethodOrAny::Any, "/webhooks/*"); + builder.add_http_route("handle", MethodOrAny::Any, "/webhooks/github"); + + let result: Result = builder.finish().try_into(); + + expect_error_matching!(result, ValidationError::DuplicateHttpRoute { path, .. } => { + path.as_ref() == "/webhooks/github" + }); + } + + #[test] + fn http_routes_wildcards_overlap_each_other() { + let mut builder = RawModuleDefV10Builder::new(); + + builder.add_http_handler("handle"); + builder.add_http_route("handle", MethodOrAny::Any, "/webhooks/*"); + builder.add_http_route("handle", MethodOrAny::Any, "/webhooks/github/*"); + + let result: Result = builder.finish().try_into(); + + expect_error_matching!(result, ValidationError::DuplicateHttpRoute { path, .. } => { + path.as_ref() == "/webhooks/github/*" + }); + } + + #[test] + fn http_routes_wildcard_does_not_overlap_sibling_path() { + let mut builder = RawModuleDefV10Builder::new(); + + builder.add_http_handler("handle"); + builder.add_http_route("handle", MethodOrAny::Any, "/webhooks/*"); + builder.add_http_route("handle", MethodOrAny::Any, "/other/github"); + + let result: Result = builder.finish().try_into(); + + assert!(result.is_ok(), "{result:?}"); + } + + #[test] + fn http_routes_wildcard_matching() { + let mut builder = RawModuleDefV10Builder::new(); + + builder.add_http_handler("handle"); + builder.add_http_route("handle", MethodOrAny::Method(HttpMethod::Get), "/webhooks/*"); + + let module_def: ModuleDef = builder.finish().try_into().unwrap(); + + for path in ["/webhooks/github", "/webhooks/", "/webhooks/a/b"] { + let (_, _, route) = module_def + .match_http_route(&HttpMethod::Get, path) + .unwrap_or_else(|| panic!("expected /webhooks/* to match {path}")); + assert_eq!(route.path.as_ref(), "/webhooks/*"); + } + + // The prefix itself, a sibling path and another method do not match. + for (method, path) in [ + (HttpMethod::Get, "/webhooks"), + (HttpMethod::Get, "/other/github"), + (HttpMethod::Post, "/webhooks/github"), + ] { + assert!( + module_def.match_http_route(&method, path).is_none(), + "{method:?} {path}" + ); + } + } + + #[test] + fn http_routes_wildcard_and_covered_path_with_other_method_are_allowed() { + let mut builder = RawModuleDefV10Builder::new(); + + builder.add_http_handler("handle"); + builder.add_http_route("handle", MethodOrAny::Method(HttpMethod::Get), "/webhooks/*"); + builder.add_http_route("handle", MethodOrAny::Method(HttpMethod::Post), "/webhooks/github"); + + let result: Result = builder.finish().try_into(); + + assert!(result.is_ok(), "{result:?}"); + } + + #[test] + fn http_routes_any_wildcard_overlaps_covered_path_with_any_method() { + let mut builder = RawModuleDefV10Builder::new(); + + builder.add_http_handler("handle"); + builder.add_http_route("handle", MethodOrAny::Any, "/webhooks/*"); + builder.add_http_route("handle", MethodOrAny::Method(HttpMethod::Post), "/webhooks/github"); + + let result: Result = builder.finish().try_into(); + + expect_error_matching!(result, ValidationError::DuplicateHttpRoute { path, .. } => { + path.as_ref() == "/webhooks/github" + }); + } + #[test] fn http_routes_missing_handler() { let mut builder = RawModuleDefV10Builder::new(); diff --git a/crates/schema/src/error.rs b/crates/schema/src/error.rs index 4f774305118..fc342cf3b1d 100644 --- a/crates/schema/src/error.rs +++ b/crates/schema/src/error.rs @@ -201,7 +201,7 @@ pub enum ValidationError { #[error("HTTP route duplicates method {method:?} for path {path}")] DuplicateHttpRoute { path: RawIdentifier, method: MethodOrAny }, #[error( - "HTTP route path `{path}` is invalid; allowed characters are {allowed}", + "HTTP route path `{path}` is invalid; allowed characters are {allowed}, and `*` is allowed only as the final character", allowed = ACCEPTABLE_ROUTE_PATH_CHARS_HUMAN_DESCRIPTION )] InvalidHttpRoutePath { path: RawIdentifier }, diff --git a/docs/docs/00200-core-concepts/00200-functions/00600-HTTP-handlers.md b/docs/docs/00200-core-concepts/00200-functions/00600-HTTP-handlers.md index ba478020b94..f17bf73151e 100644 --- a/docs/docs/00200-core-concepts/00200-functions/00600-HTTP-handlers.md +++ b/docs/docs/00200-core-concepts/00200-functions/00600-HTTP-handlers.md @@ -229,6 +229,10 @@ Combine routers with `router.Merge(otherRouter)`, which combines both routers. SpacetimeDB uses strict routing, meaning that a request must match a path exactly in order to be routed to that handler. Trailing slashes are significant. +A path may end with a single `*`, which matches any remaining path: the route `/webhooks/*` handles `/webhooks/github`, `/webhooks/` and `/webhooks/a/b`, but not `/webhooks`, because the separator in front of the wildcard is part of its prefix. A wildcard route cannot be published together with a route it would match *for the same HTTP method* — `GET /webhooks/*` and `POST /webhooks/github` are fine, `GET /webhooks/*` and `GET /webhooks/github` are rejected — so a handler is never chosen between two routes that could both serve the request. + +The wildcard does not hide what it matched: the `uri` of the request the handler receives is the full request URI, including the `/v1/database/:name_or_identity/route` prefix described below, so a handler that needs the matched part strips that prefix. + ## Sending Requests Routes defined by a SpacetimeDB database are exposed under the prefix `/v1/database/:name_or_identity/route`. To access the `say-hello` route above, send a request to `$SPACETIMEDB_URI/v1/database/$DATABASE/route/say-hello`, where `$SPACETIMEDB_URI` is the SpacetimeDB host (usually `https://maincloud.spacetimedb.com`), and `$DATABASE` is the name or identity of the database.