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
3 changes: 3 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ 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`).

## [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
Expand Down
13 changes: 13 additions & 0 deletions docs/HTTP_ASSETS.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,19 @@ 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.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
Expand Down
42 changes: 41 additions & 1 deletion include/webfront/http/HTTPServer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -325,13 +329,17 @@ struct Response : Headers {
mutable std::string httpStatus;

[[nodiscard]] static std::string toString(StatusCode code) {
static constexpr std::array<std::pair<StatusCode, std::string_view>, 19> names{
static constexpr std::array<std::pair<StatusCode, std::string_view>, 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"},
Expand Down Expand Up @@ -544,6 +552,38 @@ using MountResolver = std::function<MountAnswer(std::string_view segment)>;
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<unsigned char>(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<char>) {
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,
Expand Down
70 changes: 70 additions & 0 deletions test/unit/HTTPRoutesTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1102,6 +1102,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<RouteNet>())
written.append(reinterpret_cast<const char*>(buffer.data()), buffer.size());
auto scope = info("status ", static_cast<int>(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<std::invalid_argument>([] {
(void)redirectReply(Response::ok, "/there/");
});
requireThrows<std::invalid_argument>([] {
(void)redirectReply(Response::seeOther, "");
});
requireThrows<std::invalid_argument>([] {
(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");
Expand Down
Loading