module; #include #include #include #include #include #include module routemon:http.handler$impl; import std; import :gpx; import :http.server; import :http.ext.gpx; import :http.ext.hmac_openssl; import :http.ext.json; import :http.ext.raw_deflate; namespace beast = boost::beast; namespace json = boost::json; namespace net = boost::asio; namespace routemon::http { auto parse_timestamp_mins(std::string_view in) -> std::optional> { auto res = time::timestamp{}; auto is = std::istringstream{in}; is >> std::chrono::parse("%Y-%m-%dT%H:%MZ", res); return is.fail() ? std::nullopt : std::make_optional(res); } auto parse_timestamp_secs(std::string_view in) -> std::optional> { auto res = time::timestamp{}; auto is = std::istringstream{in}; is >> std::chrono::parse("%FT%TZ", res); return is.fail() ? std::nullopt : std::make_optional(res); } auto handler::handle_process_gpx(l0_ctx ctx, core::readable_request r) -> net::awaitable { auto l = l_.sub("handle_process_gpx").with("trace_id", ctx.trace_id.as_string()); auto cp_begin = time::timestamp{}; auto cp_end = time::timestamp{}; auto const params = ctx.target.params(); if (auto it = params.find("cpbegin"); it != params.end()) { auto mts = parse_timestamp_mins((*it).value); if (!mts) { auto tpl = problem::tpl{ .status = bhttp::status::bad_request, .title = translate("Query parameter has bad value"), .type_uri = "https://routemon.fautchen.eu/problems/query-param-bad-value", }; co_return core::problem_rsp( ctx, tpl.instantiate(), core::keep_alive{false}); } cp_begin = *mts; ++it; if (it != params.end() && (*it).key == "cpbegin") { auto tpl = problem::tpl{ .status = bhttp::status::bad_request, .title = translate("Query parameter provided too many times"), .type_uri = "https://routemon.fautchen.eu/problems/" "query-param-too-many-occurrences", }; co_return core::problem_rsp( ctx, tpl.instantiate(), core::keep_alive{false}); } } else { auto tpl = problem::tpl{ .status = bhttp::status::bad_request, .title = translate("Required query parameter not provided"), .type_uri = "https://routemon.fautchen.eu/problems/" "required-query-param-not-provided", }; co_return core::problem_rsp( ctx, tpl.instantiate(), core::keep_alive{false}); } if (auto it = params.find("cpend"); it != params.end()) { auto mts = parse_timestamp_mins((*it).value); if (!mts) { auto tpl = problem::tpl{ .status = bhttp::status::bad_request, .title = translate("Query parameter has bad value"), .type_uri = "https://routemon.fautchen.eu/problems/query-param-bad-value", }; co_return core::problem_rsp( ctx, tpl.instantiate(), core::keep_alive{false}); } cp_end = *mts; ++it; if (it != params.end() && (*it).key == "cpend") { auto tpl = problem::tpl{ .status = bhttp::status::bad_request, .title = translate("Query parameter provided too many times"), .type_uri = "https://routemon.fautchen.eu/problems/" "query-param-too-many-occurrences", }; co_return core::problem_rsp( ctx, tpl.instantiate(), core::keep_alive{false}); } } else { auto tpl = problem::tpl{ .status = bhttp::status::bad_request, .title = translate("Required query parameter not provided"), .type_uri = "https://routemon.fautchen.eu/problems/" "required-query-param-not-provided", }; co_return core::problem_rsp( ctx, tpl.instantiate(), core::keep_alive{false}); } if (cp_begin >= cp_end) { auto tpl = problem::tpl{ .status = bhttp::status::bad_request, .title = translate("Invalid check period provided"), .type_uri = "https://routemon.fautchen.eu/problems/invalid-check-period", }; co_return core::problem_rsp( ctx, tpl.instantiate().set_detail(translate( "Begin of check period must be before end of check period")), core::keep_alive{false}); } auto cp = time::period{cp_begin, cp_end}; auto gpx_file = gpx::file{}; try { l.debug("Reading GPX request body"); auto const before_read_gpx = chrono::steady_clock::now(); auto parse_res = r.p->get()[bhttp::field::content_encoding] == "x-deflate-raw" ? std::move((co_await core::read_request< ext::raw_deflate::body >(ctx, std::move(r))) .body()) : std::move((co_await core::read_request( ctx, std::move(r))) .body()); l.debug( "Read GPX request body in {}; init took {}, actual parsing {}, " "finishing {}", chrono::duration{ chrono::steady_clock::now() - before_read_gpx }, chrono::duration{parse_res.init_parse_duration()}, chrono::duration{parse_res.put_parse_duration()}, chrono::duration{ parse_res.finish_parse_duration() }); gpx_file = std::move(parse_res.unwrap()); } catch (std::exception& ex) { l_.warn("Failed to parse GPX file: {}", ex.what()); // TODO: more detailed problem reporting auto tpl = problem::tpl{ .status = bhttp::status::bad_request, .title = translate("Failed to parse GPX file"), .type_uri = "https://routemon.fautchen.eu/problems/gpx-parse-failed", }; co_return core::problem_rsp( ctx, tpl.instantiate(), core::keep_alive{false}); } // TODO: catch handler exceptions and return 500 when raised? // (keep-alive depends on whether whole request was read) auto mres = inner_.process_gpx( ctx.trace_id, std::move(gpx_file), time::period_seq{cp}); if (!mres) { auto tpl = problem::tpl{ .status = bhttp::status::internal_server_error, .title = translate("Internal server error"), .type_uri = "https://routemon.fautchen.eu/problems/" "internal-server-error", }; co_return core::problem_rsp(ctx, tpl.instantiate(), core::keep_alive{true}); } auto rsp = core::make_rsp( bhttp::status::ok, core::keep_alive{true}); rsp.set(bhttp::field::content_type, "application/json"); rsp.body() = json::serialize(json::value_from(*mres)); rsp.prepare_payload(); co_return rsp; } auto handler::handle_sysinfo(l0_ctx ctx, core::readable_request r) -> net::awaitable { auto req = co_await core::read_empty_request(ctx, std::move(r)); auto info = inner_.sysinfo(); auto rsp = core::make_rsp( bhttp::status::ok, core::keep_alive{true}); rsp.set(bhttp::field::content_type, "application/json"); rsp.body() = json::serialize(json::value_from(info)); rsp.prepare_payload(); co_return rsp; } auto decode_hexnib(char c) -> std::optional { if ('a' <= c && c <= 'f') return c - 'a' + 10; if ('A' <= c && c <= 'F') return c - 'A' + 10; if ('0' <= c && c <= '9') return c - '0'; return std::nullopt; } auto handler::handle_rwgps_webhook(l0_ctx ctx, core::readable_request r) -> net::awaitable { if (r.p->get()[bhttp::field::content_type] != "application/json") { // TODO: 415 Unsupported Media Type // (respond Accept-Post: application/json) throw std::runtime_error{"unhandled: unsupported media type provided"}; } auto mrwgps_ts = parse_timestamp_secs(r.p->get()["x-rwgps-datetime"]); if (!mrwgps_ts) { // TODO: 400 Bad Request throw std::runtime_error{ "failed to parse ISO 8601 date/time in x-rwgps-datetime header" }; } // TODO: better to instead copy the expected API key to a buffer of // (at least) the size of the input API key and to compare those two // buffers? Then this operation should be Ω/Θ(API key provided in // request) auto req_api_key = r.p->get()["x-rwgps-api-key"]; auto req_api_key_copy = std::string(rwgps_creds_->api_key().size(), 'X'); std::memcpy( req_api_key_copy.data(), req_api_key.data(), std::min(req_api_key.size(), rwgps_creds_->api_key().size())); if (CRYPTO_memcmp( req_api_key_copy.data(), rwgps_creds_->api_key().data(), rwgps_creds_->api_key().size())) { // TODO: Unauthorized // TODO: constant-time comparison throw std::runtime_error{"unhandled: mismatching API key provided"}; } auto rwgps_sig = r.p->get()["x-rwgps-signature"]; auto rwgps_sig_decoded = std::array{}; if (rwgps_sig.length() != 2 * rwgps_sig_decoded.size()) { // TODO: Bad request throw std::runtime_error{"unhandled: bad signature provided"}; } for (auto [i, b] : rwgps_sig_decoded | std::views::enumerate) { auto mhi = decode_hexnib(rwgps_sig[static_cast(i) * 2]); auto mlo = decode_hexnib(rwgps_sig[static_cast(i) * 2 + 1]); if (!mhi || !mlo) { throw std::runtime_error{"TODO: INVALID SIGNATURE"}; } static_assert(std::same_as); b = static_cast((*mhi << 4) | *mlo); } auto req = co_await core:: read_request>( ctx, std::move(r), rwgps_creds_->api_secret()); if (req.body().mac() != rwgps_sig_decoded) { throw std::runtime_error{"unhandled: incorrect signature provided"}; } // TODO: handle conversion failure gracefully inner_.rwgps_webhook( *mrwgps_ts, json::value_to(req.body().get())); auto rsp = core::make_rsp( bhttp::status::ok, core::keep_alive{true}); rsp.prepare_payload(); co_return rsp; } handler::handler( log::logger const& l, api::handler&& inner, std::shared_ptr rwgps_creds) : l_{l.sub("handler")}, inner_{std::move(inner)}, rwgps_creds_{std::move(rwgps_creds)} { } auto handler::make_routes() -> core::route_tree> { auto handler = [this](MemFn member) { return std::bind_front(member, this); }; return core::dtree>{}.named_subtrees({ {"gpx", core::dtree{{ .post = handler(&handler::handle_process_gpx), }} .no_subtrees()}, {"sysinfo", core::dtree{{ .get = handler(&handler::handle_sysinfo), }} .no_subtrees()}, {"webhook", core::dtree{}.named_subtrees({ {"rwgps", core::dtree{ {.post = handler(&handler::handle_rwgps_webhook)} }.no_subtrees()}, })}, }); } } // namespace routemon::http