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
39 changes: 36 additions & 3 deletions crates/bindings-cpp/include/spacetimedb/router.h
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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) {
Expand All @@ -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>()) {
Expand Down
37 changes: 37 additions & 0 deletions crates/bindings-csharp/Runtime.Tests/RouterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ArgumentException>(
() => Router.New().Get("/mid*path", TestHandlers.GetHandler)
);

Assert.Contains("`*` only as the final character", ex.Message);
}

[Fact]
public void RejectsWildcardRouteOverlappingStaticRoute()
{
var ex = Assert.Throws<ArgumentException>(
() =>
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()
{
Expand Down
44 changes: 41 additions & 3 deletions crates/bindings-csharp/Runtime/Router.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,38 @@ string HandlerFunction
);

private const string AcceptableRoutePathCharsHumanDescription =
"ASCII lowercase letters, digits and `-_~/`";
"ASCII lowercase letters, digits and `-_~/*`";

private const char RouteWildcard = '*';

/// <summary>True if <c>*</c> appears at most once in <paramref name="path"/>, and only as its final character.</summary>
private static bool WildcardIsOnlyTrailing(string path)
{
var prefix = path.EndsWith(RouteWildcard) ? path[..^1] : path;
return !prefix.Contains(RouteWildcard);
}

/// <summary>True if two route paths can match the same request path.</summary>
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<RouteSpec> routes;

Expand Down Expand Up @@ -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;
}
Expand All @@ -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;
}
37 changes: 34 additions & 3 deletions crates/bindings-typescript/src/server/http_handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');

Expand Down Expand Up @@ -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}`);
Expand All @@ -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) {
Expand All @@ -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' &&
Expand Down
21 changes: 20 additions & 1 deletion crates/bindings-typescript/tests/http_handlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
13 changes: 11 additions & 2 deletions crates/bindings/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.
///
Expand Down Expand Up @@ -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
Expand Down
Loading