diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index b9af4e69..e8df8b40 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -10,6 +10,10 @@ these entries stays in the GitHub releases and the Git history. ## Unreleased +### Added +- Redirect from a route with `http::redirectReply(status, location)` and the statuses `found` (302), `seeOther` (303), `temporaryRedirect` (307) and `permanentRedirect` (308), written with their reason phrase (#741, `docs/HTTP_ASSETS.md`). +- Answer the root path `/` from the application with `app.addRootRoute(handler)`, before the document root's `index.html`, while `/s//` of a family of spaces keeps serving it: a session lobby redirects `/` to a new session in one step (#740, `docs/SPACES.md`). + ## [1.3.0] - 2026-11-28 WebFront 1.3 ships with developer environment 1.3.0. The developer environment gains inspectors of the running application diff --git a/docs/HTTP_ASSETS.md b/docs/HTTP_ASSETS.md index 9061f163..8c012dc7 100644 --- a/docs/HTTP_ASSETS.md +++ b/docs/HTTP_ASSETS.md @@ -48,6 +48,26 @@ header that could split the response or that the server owns (`Content-Length`, 500. The registration handle removes the route when destroyed; a request already running keeps its handler. The binding of a request to a connection (#469) is not part of this mechanism yet. +A route redirects with `http::redirectReply(status, location)` (#741): `Response::movedPermanently` (301), +`found` (302), `seeOther` (303), `temporaryRedirect` (307) or `permanentRedirect` (308), each written with its reason phrase +(`HTTP/1.1 303 See Other`). The reply carries `Location` and an empty body, and the temporary ones (302, 303, 307) also +`Cache-Control: no-store`, so that a browser asks again on its next visit: a route that hands out a new session answers +`303`, since a `301` would be cached and send every later visit to the same session. Another status, an empty location or +one with a control character throws `std::invalid_argument`. + +```cpp +auto lobby = app.addRoute("/new/", [&](const http::RouteRequest&) { + return http::redirectReply(http::Response::seeOther, "/s/" + sessions.create() + "/"); +}); +``` + +`app.addRootRoute(handler)` (#740) answers the root path `/` itself, any query included, for `GET` and `HEAD`, before the +file providers that would serve `index.html` of the document root. It covers `/` alone (the forms the server reads as `/`, +such as `//`, included): `/index.html`, `/other/` and every other path keep their routes and files, and under a family of +spaces `/s//` still serves `index.html`, since the root route belongs to the application, not to the spaces. A prefix +route cannot be `/`, and there is one root route at a time (`std::invalid_argument`). Without one, nothing changes. The +lobby of a multi-session application, which redirects `/` to a new session, is described in `docs/SPACES.md`. + `app.addRoute(prefix, handler, http::RouteOptions{.postBodyLimit = n})` also answers `POST` (#619), for a small request such as a JSON-RPC call: the body, announced by `Content-Length` and at most `n` bytes, is read whole before the handler runs and reaches it as `RouteRequest::body`. `Expect: 100-continue` gets `100 Continue` first. The server refuses, without diff --git a/docs/SPACES.md b/docs/SPACES.md index 9e4aed5b..7d36e0a6 100644 --- a/docs/SPACES.md +++ b/docs/SPACES.md @@ -62,6 +62,24 @@ and a target that is not a safe path are answered 404 without calling the resolv segment is cut before it is decoded, so `/s/alpha%2Fdata/` names no space and never reaches `alpha`. Creating a space applies the same rule, so every space that can be created is reachable. +## A session lobby + +A multi-session application often hands out sessions at its root: `GET /` creates one and redirects to it. The root path +belongs to the application, not to the spaces, so `app.addRootRoute(handler)` answers `/` (and only it, any query +included) before the file providers would serve `index.html`, while `/s//` keeps serving that same `index.html` for +each space. A `303 See Other` sends the browser to the new session without being cached, so that each visit of `/` gets +its own (a `301` would send every later visit to the first session): + +```cpp +auto lobby = app.addRootRoute([&](const webfront::http::RouteRequest&) { + return webfront::http::redirectReply(webfront::http::Response::seeOther, "/s/" + newSessionId() + "/"); +}); +``` + +The handler runs on a worker thread of the server, not on its context: guard what it shares with the resolver. `GET` and +`HEAD` reach it, other methods get 405 (or `POST` with `RouteOptions::postBodyLimit`). `/index.html` and every other path +keep their routing, and a single root route can exist at a time. Without one, `/` serves `index.html` as before. + ## What a space offers A space has the members of the application that concern its pages, with the same signatures, and its `UI` type is the diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 2fb53df1..1785d02d 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -939,6 +939,17 @@ class BasicWF { return httpServer.addRoute(std::move(prefix), std::move(handler), std::move(options)); } + /** @brief Answers the root path `/` itself (with any query), for `GET` and `HEAD`, before the file providers that would + * serve the document root's `index.html`: a lobby that hands out a session and redirects to it with + * `http::redirectReply`, for instance. Only `/`: `/index.html` and every other path keep their routes and files, and + * the root of a space (spaces(), `/s/abc/`) still serves its `index.html`. One root route at a time; lasts as long as + * the returned registration. `options` as for addRoute (`secretPath` is refused). Throws std::invalid_argument for an + * empty handler or a second root route. Thread-safe. See docs/SPACES.md (a session lobby). + */ + [[nodiscard]] http::RouteTable::Registration addRootRoute(http::RouteHandler handler, http::RouteOptions options = {}) { + return httpServer.addRootRoute(std::move(handler), std::move(options)); + } + /** @brief Declares that the segment following `prefix` (absolute, ending with '/', such as "/s/") is a secret, a capability * such as a session's identifier: WebFront never writes it to its logs, for files, routes, WebSocket upgrades and their * failures alike ("/s//index.html" is logged with a star in place of ``), nor the message of an error raised diff --git a/include/webfront/http/HTTPServer.hpp b/include/webfront/http/HTTPServer.hpp index a4919654..def8c63a 100644 --- a/include/webfront/http/HTTPServer.hpp +++ b/include/webfront/http/HTTPServer.hpp @@ -267,6 +267,10 @@ struct Response : Headers { accepted = 202, partialContent = 206, movedPermanently = 301, + found = 302, + seeOther = 303, + temporaryRedirect = 307, + permanentRedirect = 308, badRequest = 400, unauthorized = 401, forbidden = 403, @@ -325,13 +329,17 @@ struct Response : Headers { mutable std::string httpStatus; [[nodiscard]] static std::string toString(StatusCode code) { - static constexpr std::array, 19> names{ + static constexpr std::array, 23> names{ {{continue_, "Continue"}, {switchingProtocols, "Switching Protocols"}, {ok, "OK"}, {accepted, "Accepted"}, {partialContent, "Partial Content"}, {movedPermanently, "Moved Permanently"}, + {found, "Found"}, + {seeOther, "See Other"}, + {temporaryRedirect, "Temporary Redirect"}, + {permanentRedirect, "Permanent Redirect"}, {badRequest, "Bad Request"}, {unauthorized, "Unauthorized"}, {forbidden, "Forbidden"}, @@ -393,7 +401,8 @@ struct RouteOptions { std::optional postBodyLimit{}; }; -/// The dynamic routes of a server. Prefixes never overlap, so at most one route matches a path. +/// The dynamic routes of a server. Prefixes never overlap, so at most one route matches a path. The root route +/// (addRoot) answers the path "/" alone, not the paths under it. class RouteTable { public: struct Entry { @@ -405,6 +414,8 @@ class RouteTable { std::function harden; /// See RouteOptions::postBodyLimit: unset, the route refuses `POST` with 405. std::optional postBodyLimit; + /// The route answers its prefix alone ("/" for the root route), not the paths under it. + bool exact = false; }; private: @@ -470,26 +481,34 @@ class RouteTable { // The log redaction recognizes the services space only: a secret route elsewhere could not be masked reliably. if (options.secretPath && !prefix.starts_with("/webfront/services/")) throw std::invalid_argument("A secret route must live under /webfront/services/, not '" + prefix + "'"); - auto entry = std::make_shared( - Entry{std::move(prefix), std::move(handler), options.secretPath, std::move(options.harden), options.postBodyLimit}); - std::lock_guard lock(state->mutex); - for (const auto& other : state->entries) - if (other->prefix.starts_with(entry->prefix) || entry->prefix.starts_with(other->prefix)) - throw std::invalid_argument("Route prefix '" + entry->prefix + "' collides with '" + other->prefix + "'"); - state->entries.push_back(entry); - return {state, std::move(entry)}; + return insert( + std::make_shared(Entry{std::move(prefix), std::move(handler), options.secretPath, std::move(options.harden), options.postBodyLimit, false})); } - /// @return the route whose prefix starts the path, kept alive for as long as the caller holds it. - [[nodiscard]] std::shared_ptr find(std::string_view path) const { + /// Registers the root route: it answers the path "/" alone (with any query), every other path keeps its route or + /// goes to the file providers. Only RouteOptions::secretPath is refused, since a secret route lives under + /// /webfront/services/. + /// @throws std::invalid_argument for an empty handler, a secret path, or a root route already registered. + [[nodiscard]] Registration addRoot(RouteHandler handler, RouteOptions options = {}) { + if (!handler) + throw std::invalid_argument("A route needs a handler"); + if (options.secretPath) + throw std::invalid_argument("A secret route must live under /webfront/services/, not '/'"); + return insert(std::make_shared(Entry{"/", std::move(handler), false, std::move(options.harden), options.postBodyLimit, true})); + } + + /// @return the route whose prefix starts the path, or the root route for "/" (and unless `withRoot` is false), kept + /// alive for as long as the caller holds it. + [[nodiscard]] std::shared_ptr find(std::string_view path, bool withRoot = true) const { std::lock_guard lock(state->mutex); for (const auto& entry : state->entries) - if (path.starts_with(entry->prefix)) + if (entry->exact ? withRoot && path == entry->prefix : path.starts_with(entry->prefix)) return entry; return {}; } - /// True for an absolute path ending with '/', other than "/", without "..", "//", "/./", control or reserved characters. + /// True for an absolute path ending with '/', other than "/" (see addRoot), without "..", "//", "/./", control or + /// reserved characters. [[nodiscard]] static bool validPrefix(std::string_view prefix) { if (prefix.size() < 2 || !prefix.starts_with('/') || !prefix.ends_with('/')) return false; @@ -501,6 +520,20 @@ class RouteTable { } private: + // A prefix route covers the paths that start with its prefix, an exact one only its own: two routes collide when one + // would answer a path of the other. + Registration insert(std::shared_ptr entry) { + const auto covers = [](const Entry& route, const Entry& other) { + return route.exact ? other.exact && other.prefix == route.prefix : other.prefix.starts_with(route.prefix); + }; + std::lock_guard lock(state->mutex); + for (const auto& other : state->entries) + if (covers(*entry, *other) || covers(*other, *entry)) + throw std::invalid_argument("Route prefix '" + entry->prefix + "' collides with '" + other->prefix + "'"); + state->entries.push_back(entry); + return {state, std::move(entry)}; + } + std::shared_ptr state = std::make_shared(); }; @@ -544,6 +577,38 @@ using MountResolver = std::function; return reply; } +/// A redirection to `location`, with an empty body: `301` and `308` are permanent, which browsers may cache; `302`, `303` +/// and `307` are temporary and carry `Cache-Control: no-store`, so that a later visit asks again (a lobby that hands out a +/// new session answers `303 See Other`). `307` and `308` keep the method and body of the request, `303` turns them into a +/// `GET`. Throws std::invalid_argument for a status that is not a redirection, or a location that is empty or holds a +/// control character, which would split the header. +[[nodiscard]] inline RouteReply redirectReply(Response::StatusCode status, std::string location) { + switch (status) { + case Response::movedPermanently: + case Response::found: + case Response::seeOther: + case Response::temporaryRedirect: + case Response::permanentRedirect: + break; + default: + throw std::invalid_argument("redirectReply takes a redirection status (301, 302, 303, 307 or 308), not " + std::to_string(status)); + } + if (location.empty() || std::any_of(location.begin(), location.end(), [](char c) { + return static_cast(c) < 32 || c == 127; + })) + throw std::invalid_argument("redirectReply takes a non-empty location without control characters"); + RouteReply reply; + reply.status = status; + reply.headers.emplace_back("Location", std::move(location)); + if (status != Response::movedPermanently && status != Response::permanentRedirect) + reply.headers.emplace_back("Cache-Control", "no-store"); + reply.contentLength = 0; + reply.body = [](std::span) { + return std::size_t{0}; + }; + return reply; +} + namespace routing { /// True when a request target may carry a read token (it names the services space): its text is then never logged, @@ -1300,6 +1365,13 @@ class Server { return routes.add(std::move(prefix), std::move(handler), std::move(options)); } + /// Answers the root path "/" (any query) before the file providers, which would serve its `index.html`: a lobby that + /// redirects to a new session, for instance. Every other path keeps its routing, and the root of a space under a mount + /// ("/s/abc/") still serves its `index.html`. One root route at a time (std::invalid_argument); see RouteTable::addRoot. + [[nodiscard]] RouteTable::Registration addRootRoute(RouteHandler handler, RouteOptions options = {}) { + return routes.addRoot(std::move(handler), std::move(options)); + } + /// Called, on the context's thread, with the socket of a connection upgraded to a WebSocket. A handler that also takes a /// `const UpgradeSpace&` receives the space of the upgrade, as its mount resolved it (empty outside the mounts), and the /// path of the upgrade request. @@ -1598,8 +1670,9 @@ class Server { // A request, other than a WebSocket upgrade, under a registered prefix. Every method under a prefix // belongs to the route (405 for those it does not serve): its URLs never fall through to the providers. - // The routes of a space (`own`) come before the server's. - std::optional matchRoute(const Request& request, const RouteTable* own = nullptr) const { + // The routes of a space (`own`) come before the server's. Under a mount (`mounted`), the server's root route belongs + // to the application, not to the spaces: "/s/abc/" still serves the space's index.html. + std::optional matchRoute(const Request& request, const RouteTable* own = nullptr, bool mounted = false) const { if (request.isUpgradeRequest("websocket")) return {}; auto split = routing::splitTarget(request.uri); @@ -1607,7 +1680,7 @@ class Server { return {}; auto route = own ? own->find(split->first) : nullptr; if (!route) - route = routes.find(split->first); + route = routes.find(split->first, !mounted); if (!route) return {}; return RouteMatch{std::move(route), std::move(split->first), std::move(split->second)}; @@ -1846,7 +1919,7 @@ class Server { throw BadRequestException(); space.requestPath = std::move(target->first); } - auto match = matchRoute(request, spaceRoutes.get()); + auto match = matchRoute(request, spaceRoutes.get(), !mountPrefix.empty()); // Under a mount, the logs show the whole path as it came, the mount's segment and the secret segments masked; a // secret prefix covers it as the server read it and as the space reads it. The query may quote a URL: never shown. const auto shown = [&](std::string_view path) { diff --git a/test/unit/HTTPRoutesTests.cpp b/test/unit/HTTPRoutesTests.cpp index 782c85de..8de02702 100644 --- a/test/unit/HTTPRoutesTests.cpp +++ b/test/unit/HTTPRoutesTests.cpp @@ -825,6 +825,16 @@ struct ProvidedFS { } }; +/// Serves any path with its own name as content: "file index.html" for "/", "file other/index.html" for "/other/". +struct NamingFS { + explicit NamingFS(std::filesystem::path) { } + std::optional open(std::filesystem::path path) { + ProvidedFile::content = "file " + path.relative_path().generic_string(); + ProvidedFile::native.clear(); + return ProvidedFS{{}}.open({}); + } +}; + } // namespace const Scenario filesProvider{"Files of a provider are announced by size and streamed", [] { @@ -878,6 +888,119 @@ const Scenario filesProvider{"Files of a provider are announced by size and stre }); }}; +const Scenario rootRoute{"The root route answers / alone, and the root of a space keeps its index.html (#740)", [] { + const auto lobby = [](const RouteRequest& request) { + return redirectReply(Response::seeOther, "/s/new/?" + std::string(request.query)); + }; + given("a root route", [&] { + for (const auto* target : {"/", "/?from=link", "//", "/./"}) { + when("GET ", target, " is requested", [&] { + Fixture fixture; + Server server("127.0.0.1", "0"); + auto route = server.addRootRoute(lobby); + const auto response = fixture.answer(get(target)); + then("the route answers instead of index.html", [&] { + require(response.starts_with("HTTP/1.1 303 See Other\r\n")); + require(contains(response, "Location: /s/new/?")); + require(!contains(response, "file index.html")); + }); + }); + } + when("HEAD / is requested", [&] { + Fixture fixture; + Server server("127.0.0.1", "0"); + auto route = server.addRootRoute(lobby); + const auto response = fixture.answer(get("/", "HEAD")); + then("the route answers with its headers", [&] { + require(response.starts_with("HTTP/1.1 303 See Other\r\n")); + require(contains(response, "Location: /s/new/?\r\n")); + }); + }); + when("POST / is requested", [&] { + Fixture fixture; + Server server("127.0.0.1", "0"); + auto route = server.addRootRoute(lobby); + const auto response = fixture.answer(get("/", "POST")); + then("it is refused as by any route that does not accept POST", [&] { + require(response.starts_with("HTTP/1.1 405 Method Not Allowed\r\n")); + }); + }); + for (const auto& [target, file] : { + std::pair{"/index.html", "file index.html"}, + std::pair{ "/other/", "file other/index.html"} + }) { + when("GET ", target, " is requested", [&] { + Fixture fixture; + Server server("127.0.0.1", "0"); + auto route = server.addRootRoute(lobby); + const auto response = fixture.answer(get(target)); + then("the file providers serve it as before", [&] { + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(response.ends_with(file)); + }); + }); + } + when("the root of a space under a mount is requested", [&] { + Fixture fixture; + Server server("127.0.0.1", "0"); + auto route = server.addRootRoute(lobby); + server.mount("/s/", [](std::string_view) { + return MountAnswer{}; + }); + const auto response = fixture.answer(get("/s/abc/")); + then("the space serves the document root's index.html", [&] { + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(response.ends_with("file index.html")); + }); + }); + when("the registration is reset", [&] { + Fixture fixture; + Server server("127.0.0.1", "0"); + auto route = server.addRootRoute(lobby); + route.reset(); + const auto response = fixture.answer(get("/")); + then("/ serves index.html again", [&] { + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(response.ends_with("file index.html")); + }); + }); + }); + given("no root route", [&] { + Fixture fixture; + Server server("127.0.0.1", "0"); + auto other = server.addRoute("/new/", lobby); + const auto response = fixture.answer(get("/")); + then("/ serves index.html as before", [&] { + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(response.ends_with("file index.html")); + }); + }); + given("a route table", [&] { + RouteTable table; + auto root = table.addRoot(lobby); + then("a second root route, an empty handler and a secret root are refused", [&] { + requireThrows([&] { + (void)table.addRoot(lobby); + }); + RouteTable other; + requireThrows([&] { + (void)other.addRoot(nullptr); + }); + requireThrows([&] { + (void)other.addRoot(lobby, RouteOptions{.secretPath = true}); + }); + }); + then("prefix routes coexist with it and keep their paths", [&] { + auto prefix = table.add("/new/", lobby); + require(table.find("/") != nullptr); + require(table.find("/", false) == nullptr); + require(table.find("/new/x") != nullptr && table.find("/new/x") != table.find("/")); + require(table.find("/index.html") == nullptr); + require(table.find("/other/") == nullptr); + }); + }); + }}; + const Scenario nativeFileKnown{"A native file known by its size reports it", [] { webfront::test::TemporaryDirectory directory; const auto path = directory.path() / "known.bin"; @@ -1102,6 +1225,76 @@ const Scenario handlerMay{"A handler may answer 405 with a body of its own", [] }); }}; +const Scenario routeRedirects{"A route redirects with the status line, Location and caching of its status (#741)", [] { + Fixture fixture; + Router server("127.0.0.1", "0"); + given("a route answering 303 See Other", [&] { + auto route = server.addRoute("/new/", [](const RouteRequest&) { + return redirectReply(Response::seeOther, "/s/abc/"); + }); + const auto response = fixture.answer(get("/new/")); + then("the browser gets the status with its reason, the location and no body", [&] { + require(response.starts_with("HTTP/1.1 303 See Other\r\n")); + require(contains(response, "Location: /s/abc/\r\n")); + require(contains(response, "Cache-Control: no-store\r\n")); + require(contains(response, "Content-Length: 0\r\n")); + require(response.ends_with("\r\n\r\n")); + }); + }); + given("a route answering 308 Permanent Redirect to HEAD", [&] { + auto route = server.addRoute("/old/", [](const RouteRequest&) { + return redirectReply(Response::permanentRedirect, "https://example.org/new/"); + }); + const auto response = fixture.answer(get("/old/", "HEAD")); + then("a permanent redirection may be cached", [&] { + require(response.starts_with("HTTP/1.1 308 Permanent Redirect\r\n")); + require(contains(response, "Location: https://example.org/new/\r\n")); + require(!contains(response, "Cache-Control")); + }); + }); + }}; + +const Scenario redirectStatuses{"Each redirection status has its reason phrase and its caching (#741)", [] { + struct Expected { + Response::StatusCode status; + std::string_view line; + bool cached; + }; + for (const auto& [status, line, cached] : { + Expected{ Response::movedPermanently, "301 Moved Permanently", true}, + Expected{ Response::found, "302 Found", false}, + Expected{ Response::seeOther, "303 See Other", false}, + Expected{Response::temporaryRedirect, "307 Temporary Redirect", false}, + Expected{Response::permanentRedirect, "308 Permanent Redirect", true} + }) { + Response response; + response.statusCode = status; + std::string written; + for (const auto& buffer : response.toBuffers()) + written.append(reinterpret_cast(buffer.data()), buffer.size()); + auto scope = info("status ", static_cast(status)); + checkEqual(written.substr(0, written.find("\r\n")), "HTTP/1.1 " + std::string(line)); + const auto reply = redirectReply(status, "/there/"); + checkEqual(reply.status, status); + checkEqual(reply.contentLength.value_or(1), 0u); + bool noStore = false; + for (const auto& [name, value] : reply.headers) + noStore = noStore || (name == "Cache-Control" && value == "no-store"); + checkEqual(noStore, !cached); + } + then("anything else than a redirection, or a location that could split the header, is refused", [] { + requireThrows([] { + (void)redirectReply(Response::ok, "/there/"); + }); + requireThrows([] { + (void)redirectReply(Response::seeOther, ""); + }); + requireThrows([] { + (void)redirectReply(Response::seeOther, "/there/\r\nSet-Cookie: a=b"); + }); + }); + }}; + const Scenario headerNames{"Header names are ASCII tokens whatever the locale", [] { Fixture fixture; Router server("127.0.0.1", "0");