summaryrefslogtreecommitdiffstats
path: root/server/src/http/handler.cpp
blob: d755c1628fa9d136dafe2f60c7e0c7dc90d207fe (about) (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
module;

#include <boost/asio/awaitable.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/config.hpp>
#include <boost/json.hpp>

#include <openssl/crypto.h>

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<time::timestamp<std::chrono::minutes>>
{
  auto res = time::timestamp<std::chrono::minutes>{};
  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<time::timestamp<std::chrono::seconds>>
{
  auto res = time::timestamp<std::chrono::seconds>{};
  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<core::presponse>
{
  auto l =
      l_.sub("handle_process_gpx").with("trace_id", ctx.trace_id.as_string());

  auto cp_begin = time::timestamp<std::chrono::minutes>{};
  auto cp_end = time::timestamp<std::chrono::minutes>{};

  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<std::chrono::minutes>{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<ext::gpx::body>
                         >(ctx, std::move(r)))
                            .body())
            : std::move((co_await core::read_request<ext::gpx::body>(
                             ctx, std::move(r)))
                            .body());
    l.debug(
        "Read GPX request body in {}; init took {}, actual parsing {}, "
        "finishing {}",
        chrono::duration<double, std::milli>{
          chrono::steady_clock::now() - before_read_gpx
        },
        chrono::duration<double, std::milli>{parse_res.init_parse_duration()},
        chrono::duration<double, std::milli>{parse_res.put_parse_duration()},
        chrono::duration<double, std::milli>{
          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<std::chrono::minutes>{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::string_body>(
      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<core::presponse>
{
  auto req = co_await core::read_empty_request(ctx, std::move(r));
  auto info = inner_.sysinfo();

  auto rsp = core::make_rsp<bhttp::string_body>(
      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<std::uint8_t>
{
  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<core::presponse>
{
  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<std::uint8_t, 32>{};

  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<std::size_t>(i) * 2]);
    auto mlo = decode_hexnib(rwgps_sig[static_cast<std::size_t>(i) * 2 + 1]);
    if (!mhi || !mlo)
    {
      throw std::runtime_error{"TODO: INVALID SIGNATURE"};
    }
    static_assert(std::same_as<decltype(b), std::uint8_t&>);
    b = static_cast<std::uint8_t>((*mhi << 4) | *mlo);
  }

  auto req = co_await core::
      read_request<http::ext::hmac_openssl::body<http::ext::json::body>>(
          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<rwgps::webhook_request>(req.body().get()));

  auto rsp = core::make_rsp<bhttp::empty_body>(
      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::credentials> rwgps_creds)
  : l_{l.sub("handler")}, inner_{std::move(inner)},
    rwgps_creds_{std::move(rwgps_creds)}
{
}

auto handler::make_routes() -> core::route_tree<core::routed_ctx<outer_ctx>>
{
  auto handler = [this]<class MemFn>(MemFn member)
  { return std::bind_front(member, this); };

  return core::dtree<core::routed_ctx<outer_ctx>>{}.named_subtrees({
    {"gpx", core::dtree<l0_ctx>{{
                                  .post = handler(&handler::handle_process_gpx),
                                }}
                .no_subtrees()},
    {"sysinfo", core::dtree<l0_ctx>{{
                                      .get = handler(&handler::handle_sysinfo),
                                    }}
                    .no_subtrees()},
    {"webhook", core::dtree<l0_ctx>{}.named_subtrees({
                  {"rwgps", core::dtree<l0_ctx>{
                              {.post = handler(&handler::handle_rwgps_webhook)}
                            }.no_subtrees()},
                })},
  });
}

} // namespace routemon::http