From 02475e05ccd1aa15c6a6163834f28bfebbef796f Mon Sep 17 00:00:00 2001 From: Rutger Broekhoff Date: Mon, 30 Nov 2026 11:47:36 +0100 Subject: RWGPS webhook and such --- server/src/srv.cpp | 145 ++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 128 insertions(+), 17 deletions(-) (limited to 'server/src/srv.cpp') diff --git a/server/src/srv.cpp b/server/src/srv.cpp index 5de0fc5..287f838 100644 --- a/server/src/srv.cpp +++ b/server/src/srv.cpp @@ -13,11 +13,14 @@ module; #include +#include + module routemon:srv$impl; import std; import :gpx; import :srv; +import :rwgps.webhook; namespace beast = boost::beast; namespace chrono = std::chrono; @@ -330,9 +333,10 @@ struct raw_deflate_body }; }; -auto parse_timestamp(std::string_view in) -> std::optional +auto parse_timestamp_mins(std::string_view in) + -> std::optional> { - auto res = time::timestamp{}; + 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); @@ -344,13 +348,13 @@ auto handler::handle_process_gpx(l0_ctx ctx, http::readable_request r) 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 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((*it).value); + auto mts = parse_timestamp_mins((*it).value); if (!mts) { auto tpl = problem::tpl{ @@ -390,7 +394,7 @@ auto handler::handle_process_gpx(l0_ctx ctx, http::readable_request r) } if (auto it = params.find("cpend"); it != params.end()) { - auto mts = parse_timestamp((*it).value); + auto mts = parse_timestamp_mins((*it).value); if (!mts) { auto tpl = problem::tpl{ @@ -442,7 +446,7 @@ auto handler::handle_process_gpx(l0_ctx ctx, http::readable_request r) "Begin of check period must be before end of check period")), http::keep_alive{false}); } - auto cp = time::period{cp_begin, cp_end}; + auto cp = time::period{cp_begin, cp_end}; auto gpx_file = gpx::file{}; try @@ -487,7 +491,8 @@ auto handler::handle_process_gpx(l0_ctx ctx, http::readable_request r) // 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}); + ctx.trace_id, std::move(gpx_file), + time::period_seq{cp}); if (!mres) { auto tpl = problem::tpl{ @@ -521,8 +526,109 @@ auto handler::handle_sysinfo(l0_ctx ctx, http::readable_request r) co_return rsp; } -handler::handler(log::logger const& l, api::handler&& inner) - : l_{l.sub("handler")}, inner_{std::move(inner)} +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 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_rwgps_webhook(l0_ctx ctx, http::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 http:: + 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 = http::make_rsp( + bhttp::status::ok, http::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)} { } @@ -536,11 +642,15 @@ auto handler::make_routes() -> http::route_tree> .post = handler(&handler::handle_process_gpx), }} .no_subtrees()}, - {"sysinfo", http::dtree{ - { - .get = handler(&handler::handle_sysinfo), - } - }.no_subtrees()}, + {"sysinfo", http::dtree{{ + .get = handler(&handler::handle_sysinfo), + }} + .no_subtrees()}, + {"webhook", http::dtree{}.named_subtrees({ + {"rwgps", http::dtree{ + {.post = handler(&handler::handle_rwgps_webhook)} + }.no_subtrees()}, + })}, }); } @@ -557,8 +667,9 @@ auto server::make_global_middleware(config::http_server const& cfg) server::server( log::logger const& l, config::http_server const& cfg, - locale::selector&& lsel, api::handler&& inner) - : handler_{l, std::move(inner)}, + std::shared_ptr rwgps_creds, locale::selector&& lsel, + api::handler&& inner) + : handler_{l, std::move(inner), std::move(rwgps_creds)}, srv_{ l, http::router{ -- cgit v1.3.1