diff options
Diffstat (limited to 'server/src/http/handler.cpp')
| -rw-r--r-- | server/src/http/handler.cpp | 348 |
1 files changed, 348 insertions, 0 deletions
diff --git a/server/src/http/handler.cpp b/server/src/http/handler.cpp new file mode 100644 index 0000000..d755c16 --- /dev/null +++ b/server/src/http/handler.cpp | |||
| @@ -0,0 +1,348 @@ | |||
| 1 | module; | ||
| 2 | |||
| 3 | #include <boost/asio/awaitable.hpp> | ||
| 4 | #include <boost/beast/core.hpp> | ||
| 5 | #include <boost/beast/http.hpp> | ||
| 6 | #include <boost/config.hpp> | ||
| 7 | #include <boost/json.hpp> | ||
| 8 | |||
| 9 | #include <openssl/crypto.h> | ||
| 10 | |||
| 11 | module routemon:http.handler$impl; | ||
| 12 | |||
| 13 | import std; | ||
| 14 | import :gpx; | ||
| 15 | import :http.server; | ||
| 16 | import :http.ext.gpx; | ||
| 17 | import :http.ext.hmac_openssl; | ||
| 18 | import :http.ext.json; | ||
| 19 | import :http.ext.raw_deflate; | ||
| 20 | |||
| 21 | namespace beast = boost::beast; | ||
| 22 | namespace json = boost::json; | ||
| 23 | namespace net = boost::asio; | ||
| 24 | |||
| 25 | namespace routemon::http { | ||
| 26 | |||
| 27 | auto parse_timestamp_mins(std::string_view in) | ||
| 28 | -> std::optional<time::timestamp<std::chrono::minutes>> | ||
| 29 | { | ||
| 30 | auto res = time::timestamp<std::chrono::minutes>{}; | ||
| 31 | auto is = std::istringstream{in}; | ||
| 32 | is >> std::chrono::parse("%Y-%m-%dT%H:%MZ", res); | ||
| 33 | return is.fail() ? std::nullopt : std::make_optional(res); | ||
| 34 | } | ||
| 35 | |||
| 36 | auto parse_timestamp_secs(std::string_view in) | ||
| 37 | -> std::optional<time::timestamp<std::chrono::seconds>> | ||
| 38 | { | ||
| 39 | auto res = time::timestamp<std::chrono::seconds>{}; | ||
| 40 | auto is = std::istringstream{in}; | ||
| 41 | is >> std::chrono::parse("%FT%TZ", res); | ||
| 42 | return is.fail() ? std::nullopt : std::make_optional(res); | ||
| 43 | } | ||
| 44 | |||
| 45 | auto handler::handle_process_gpx(l0_ctx ctx, core::readable_request r) | ||
| 46 | -> net::awaitable<core::presponse> | ||
| 47 | { | ||
| 48 | auto l = | ||
| 49 | l_.sub("handle_process_gpx").with("trace_id", ctx.trace_id.as_string()); | ||
| 50 | |||
| 51 | auto cp_begin = time::timestamp<std::chrono::minutes>{}; | ||
| 52 | auto cp_end = time::timestamp<std::chrono::minutes>{}; | ||
| 53 | |||
| 54 | auto const params = ctx.target.params(); | ||
| 55 | if (auto it = params.find("cpbegin"); it != params.end()) | ||
| 56 | { | ||
| 57 | auto mts = parse_timestamp_mins((*it).value); | ||
| 58 | if (!mts) | ||
| 59 | { | ||
| 60 | auto tpl = problem::tpl{ | ||
| 61 | .status = bhttp::status::bad_request, | ||
| 62 | .title = translate("Query parameter has bad value"), | ||
| 63 | .type_uri = | ||
| 64 | "https://routemon.fautchen.eu/problems/query-param-bad-value", | ||
| 65 | }; | ||
| 66 | co_return core::problem_rsp( | ||
| 67 | ctx, tpl.instantiate(), core::keep_alive{false}); | ||
| 68 | } | ||
| 69 | cp_begin = *mts; | ||
| 70 | |||
| 71 | ++it; | ||
| 72 | if (it != params.end() && (*it).key == "cpbegin") | ||
| 73 | { | ||
| 74 | auto tpl = problem::tpl{ | ||
| 75 | .status = bhttp::status::bad_request, | ||
| 76 | .title = translate("Query parameter provided too many times"), | ||
| 77 | .type_uri = "https://routemon.fautchen.eu/problems/" | ||
| 78 | "query-param-too-many-occurrences", | ||
| 79 | }; | ||
| 80 | co_return core::problem_rsp( | ||
| 81 | ctx, tpl.instantiate(), core::keep_alive{false}); | ||
| 82 | } | ||
| 83 | } | ||
| 84 | else | ||
| 85 | { | ||
| 86 | auto tpl = problem::tpl{ | ||
| 87 | .status = bhttp::status::bad_request, | ||
| 88 | .title = translate("Required query parameter not provided"), | ||
| 89 | .type_uri = "https://routemon.fautchen.eu/problems/" | ||
| 90 | "required-query-param-not-provided", | ||
| 91 | }; | ||
| 92 | co_return core::problem_rsp( | ||
| 93 | ctx, tpl.instantiate(), core::keep_alive{false}); | ||
| 94 | } | ||
| 95 | if (auto it = params.find("cpend"); it != params.end()) | ||
| 96 | { | ||
| 97 | auto mts = parse_timestamp_mins((*it).value); | ||
| 98 | if (!mts) | ||
| 99 | { | ||
| 100 | auto tpl = problem::tpl{ | ||
| 101 | .status = bhttp::status::bad_request, | ||
| 102 | .title = translate("Query parameter has bad value"), | ||
| 103 | .type_uri = | ||
| 104 | "https://routemon.fautchen.eu/problems/query-param-bad-value", | ||
| 105 | }; | ||
| 106 | co_return core::problem_rsp( | ||
| 107 | ctx, tpl.instantiate(), core::keep_alive{false}); | ||
| 108 | } | ||
| 109 | cp_end = *mts; | ||
| 110 | |||
| 111 | ++it; | ||
| 112 | if (it != params.end() && (*it).key == "cpend") | ||
| 113 | { | ||
| 114 | auto tpl = problem::tpl{ | ||
| 115 | .status = bhttp::status::bad_request, | ||
| 116 | .title = translate("Query parameter provided too many times"), | ||
| 117 | .type_uri = "https://routemon.fautchen.eu/problems/" | ||
| 118 | "query-param-too-many-occurrences", | ||
| 119 | }; | ||
| 120 | co_return core::problem_rsp( | ||
| 121 | ctx, tpl.instantiate(), core::keep_alive{false}); | ||
| 122 | } | ||
| 123 | } | ||
| 124 | else | ||
| 125 | { | ||
| 126 | auto tpl = problem::tpl{ | ||
| 127 | .status = bhttp::status::bad_request, | ||
| 128 | .title = translate("Required query parameter not provided"), | ||
| 129 | .type_uri = "https://routemon.fautchen.eu/problems/" | ||
| 130 | "required-query-param-not-provided", | ||
| 131 | }; | ||
| 132 | co_return core::problem_rsp( | ||
| 133 | ctx, tpl.instantiate(), core::keep_alive{false}); | ||
| 134 | } | ||
| 135 | |||
| 136 | if (cp_begin >= cp_end) | ||
| 137 | { | ||
| 138 | auto tpl = problem::tpl{ | ||
| 139 | .status = bhttp::status::bad_request, | ||
| 140 | .title = translate("Invalid check period provided"), | ||
| 141 | .type_uri = "https://routemon.fautchen.eu/problems/invalid-check-period", | ||
| 142 | }; | ||
| 143 | co_return core::problem_rsp( | ||
| 144 | ctx, | ||
| 145 | tpl.instantiate().set_detail(translate( | ||
| 146 | "Begin of check period must be before end of check period")), | ||
| 147 | core::keep_alive{false}); | ||
| 148 | } | ||
| 149 | auto cp = time::period<std::chrono::minutes>{cp_begin, cp_end}; | ||
| 150 | |||
| 151 | auto gpx_file = gpx::file{}; | ||
| 152 | try | ||
| 153 | { | ||
| 154 | l.debug("Reading GPX request body"); | ||
| 155 | auto const before_read_gpx = chrono::steady_clock::now(); | ||
| 156 | auto parse_res = | ||
| 157 | r.p->get()[bhttp::field::content_encoding] == "x-deflate-raw" | ||
| 158 | ? std::move((co_await core::read_request< | ||
| 159 | ext::raw_deflate::body<ext::gpx::body> | ||
| 160 | >(ctx, std::move(r))) | ||
| 161 | .body()) | ||
| 162 | : std::move((co_await core::read_request<ext::gpx::body>( | ||
| 163 | ctx, std::move(r))) | ||
| 164 | .body()); | ||
| 165 | l.debug( | ||
| 166 | "Read GPX request body in {}; init took {}, actual parsing {}, " | ||
| 167 | "finishing {}", | ||
| 168 | chrono::duration<double, std::milli>{ | ||
| 169 | chrono::steady_clock::now() - before_read_gpx | ||
| 170 | }, | ||
| 171 | chrono::duration<double, std::milli>{parse_res.init_parse_duration()}, | ||
| 172 | chrono::duration<double, std::milli>{parse_res.put_parse_duration()}, | ||
| 173 | chrono::duration<double, std::milli>{ | ||
| 174 | parse_res.finish_parse_duration() | ||
| 175 | }); | ||
| 176 | gpx_file = std::move(parse_res.unwrap()); | ||
| 177 | } | ||
| 178 | catch (std::exception& ex) | ||
| 179 | { | ||
| 180 | l_.warn("Failed to parse GPX file: {}", ex.what()); | ||
| 181 | // TODO: more detailed problem reporting | ||
| 182 | auto tpl = problem::tpl{ | ||
| 183 | .status = bhttp::status::bad_request, | ||
| 184 | .title = translate("Failed to parse GPX file"), | ||
| 185 | .type_uri = "https://routemon.fautchen.eu/problems/gpx-parse-failed", | ||
| 186 | }; | ||
| 187 | co_return core::problem_rsp( | ||
| 188 | ctx, tpl.instantiate(), core::keep_alive{false}); | ||
| 189 | } | ||
| 190 | |||
| 191 | // TODO: catch handler exceptions and return 500 when raised? | ||
| 192 | // (keep-alive depends on whether whole request was read) | ||
| 193 | auto mres = inner_.process_gpx( | ||
| 194 | ctx.trace_id, std::move(gpx_file), | ||
| 195 | time::period_seq<std::chrono::minutes>{cp}); | ||
| 196 | if (!mres) | ||
| 197 | { | ||
| 198 | auto tpl = problem::tpl{ | ||
| 199 | .status = bhttp::status::internal_server_error, | ||
| 200 | .title = translate("Internal server error"), | ||
| 201 | .type_uri = "https://routemon.fautchen.eu/problems/" | ||
| 202 | "internal-server-error", | ||
| 203 | }; | ||
| 204 | co_return core::problem_rsp(ctx, tpl.instantiate(), core::keep_alive{true}); | ||
| 205 | } | ||
| 206 | |||
| 207 | auto rsp = core::make_rsp<bhttp::string_body>( | ||
| 208 | bhttp::status::ok, core::keep_alive{true}); | ||
| 209 | rsp.set(bhttp::field::content_type, "application/json"); | ||
| 210 | rsp.body() = json::serialize(json::value_from(*mres)); | ||
| 211 | rsp.prepare_payload(); | ||
| 212 | co_return rsp; | ||
| 213 | } | ||
| 214 | |||
| 215 | auto handler::handle_sysinfo(l0_ctx ctx, core::readable_request r) | ||
| 216 | -> net::awaitable<core::presponse> | ||
| 217 | { | ||
| 218 | auto req = co_await core::read_empty_request(ctx, std::move(r)); | ||
| 219 | auto info = inner_.sysinfo(); | ||
| 220 | |||
| 221 | auto rsp = core::make_rsp<bhttp::string_body>( | ||
| 222 | bhttp::status::ok, core::keep_alive{true}); | ||
| 223 | rsp.set(bhttp::field::content_type, "application/json"); | ||
| 224 | rsp.body() = json::serialize(json::value_from(info)); | ||
| 225 | rsp.prepare_payload(); | ||
| 226 | co_return rsp; | ||
| 227 | } | ||
| 228 | |||
| 229 | auto decode_hexnib(char c) -> std::optional<std::uint8_t> | ||
| 230 | { | ||
| 231 | if ('a' <= c && c <= 'f') | ||
| 232 | return c - 'a' + 10; | ||
| 233 | if ('A' <= c && c <= 'F') | ||
| 234 | return c - 'A' + 10; | ||
| 235 | if ('0' <= c && c <= '9') | ||
| 236 | return c - '0'; | ||
| 237 | return std::nullopt; | ||
| 238 | } | ||
| 239 | |||
| 240 | auto handler::handle_rwgps_webhook(l0_ctx ctx, core::readable_request r) | ||
| 241 | -> net::awaitable<core::presponse> | ||
| 242 | { | ||
| 243 | if (r.p->get()[bhttp::field::content_type] != "application/json") | ||
| 244 | { | ||
| 245 | // TODO: 415 Unsupported Media Type | ||
| 246 | // (respond Accept-Post: application/json) | ||
| 247 | throw std::runtime_error{"unhandled: unsupported media type provided"}; | ||
| 248 | } | ||
| 249 | |||
| 250 | auto mrwgps_ts = parse_timestamp_secs(r.p->get()["x-rwgps-datetime"]); | ||
| 251 | if (!mrwgps_ts) | ||
| 252 | { | ||
| 253 | // TODO: 400 Bad Request | ||
| 254 | throw std::runtime_error{ | ||
| 255 | "failed to parse ISO 8601 date/time in x-rwgps-datetime header" | ||
| 256 | }; | ||
| 257 | } | ||
| 258 | |||
| 259 | // TODO: better to instead copy the expected API key to a buffer of | ||
| 260 | // (at least) the size of the input API key and to compare those two | ||
| 261 | // buffers? Then this operation should be Ω/Θ(API key provided in | ||
| 262 | // request) | ||
| 263 | auto req_api_key = r.p->get()["x-rwgps-api-key"]; | ||
| 264 | auto req_api_key_copy = std::string(rwgps_creds_->api_key().size(), 'X'); | ||
| 265 | std::memcpy( | ||
| 266 | req_api_key_copy.data(), req_api_key.data(), | ||
| 267 | std::min(req_api_key.size(), rwgps_creds_->api_key().size())); | ||
| 268 | |||
| 269 | if (CRYPTO_memcmp( | ||
| 270 | req_api_key_copy.data(), rwgps_creds_->api_key().data(), | ||
| 271 | rwgps_creds_->api_key().size())) | ||
| 272 | { | ||
| 273 | // TODO: Unauthorized | ||
| 274 | // TODO: constant-time comparison | ||
| 275 | throw std::runtime_error{"unhandled: mismatching API key provided"}; | ||
| 276 | } | ||
| 277 | |||
| 278 | auto rwgps_sig = r.p->get()["x-rwgps-signature"]; | ||
| 279 | auto rwgps_sig_decoded = std::array<std::uint8_t, 32>{}; | ||
| 280 | |||
| 281 | if (rwgps_sig.length() != 2 * rwgps_sig_decoded.size()) | ||
| 282 | { | ||
| 283 | // TODO: Bad request | ||
| 284 | throw std::runtime_error{"unhandled: bad signature provided"}; | ||
| 285 | } | ||
| 286 | |||
| 287 | for (auto [i, b] : rwgps_sig_decoded | std::views::enumerate) | ||
| 288 | { | ||
| 289 | auto mhi = decode_hexnib(rwgps_sig[static_cast<std::size_t>(i) * 2]); | ||
| 290 | auto mlo = decode_hexnib(rwgps_sig[static_cast<std::size_t>(i) * 2 + 1]); | ||
| 291 | if (!mhi || !mlo) | ||
| 292 | { | ||
| 293 | throw std::runtime_error{"TODO: INVALID SIGNATURE"}; | ||
| 294 | } | ||
| 295 | static_assert(std::same_as<decltype(b), std::uint8_t&>); | ||
| 296 | b = static_cast<std::uint8_t>((*mhi << 4) | *mlo); | ||
| 297 | } | ||
| 298 | |||
| 299 | auto req = co_await core:: | ||
| 300 | read_request<http::ext::hmac_openssl::body<http::ext::json::body>>( | ||
| 301 | ctx, std::move(r), rwgps_creds_->api_secret()); | ||
| 302 | |||
| 303 | if (req.body().mac() != rwgps_sig_decoded) | ||
| 304 | { | ||
| 305 | throw std::runtime_error{"unhandled: incorrect signature provided"}; | ||
| 306 | } | ||
| 307 | |||
| 308 | // TODO: handle conversion failure gracefully | ||
| 309 | inner_.rwgps_webhook( | ||
| 310 | *mrwgps_ts, json::value_to<rwgps::webhook_request>(req.body().get())); | ||
| 311 | |||
| 312 | auto rsp = core::make_rsp<bhttp::empty_body>( | ||
| 313 | bhttp::status::ok, core::keep_alive{true}); | ||
| 314 | rsp.prepare_payload(); | ||
| 315 | co_return rsp; | ||
| 316 | } | ||
| 317 | |||
| 318 | handler::handler( | ||
| 319 | log::logger const& l, api::handler&& inner, | ||
| 320 | std::shared_ptr<rwgps::credentials> rwgps_creds) | ||
| 321 | : l_{l.sub("handler")}, inner_{std::move(inner)}, | ||
| 322 | rwgps_creds_{std::move(rwgps_creds)} | ||
| 323 | { | ||
| 324 | } | ||
| 325 | |||
| 326 | auto handler::make_routes() -> core::route_tree<core::routed_ctx<outer_ctx>> | ||
| 327 | { | ||
| 328 | auto handler = [this]<class MemFn>(MemFn member) | ||
| 329 | { return std::bind_front(member, this); }; | ||
| 330 | |||
| 331 | return core::dtree<core::routed_ctx<outer_ctx>>{}.named_subtrees({ | ||
| 332 | {"gpx", core::dtree<l0_ctx>{{ | ||
| 333 | .post = handler(&handler::handle_process_gpx), | ||
| 334 | }} | ||
| 335 | .no_subtrees()}, | ||
| 336 | {"sysinfo", core::dtree<l0_ctx>{{ | ||
| 337 | .get = handler(&handler::handle_sysinfo), | ||
| 338 | }} | ||
| 339 | .no_subtrees()}, | ||
| 340 | {"webhook", core::dtree<l0_ctx>{}.named_subtrees({ | ||
| 341 | {"rwgps", core::dtree<l0_ctx>{ | ||
| 342 | {.post = handler(&handler::handle_rwgps_webhook)} | ||
| 343 | }.no_subtrees()}, | ||
| 344 | })}, | ||
| 345 | }); | ||
| 346 | } | ||
| 347 | |||
| 348 | } // namespace routemon::http | ||