1 /*
2   Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
3 
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU General Public License, version 2.0,
6   as published by the Free Software Foundation.
7 
8   This program is also distributed with certain software (including
9   but not limited to OpenSSL) that is licensed under separate terms,
10   as designated in a particular file or component or in included license
11   documentation.  The authors of MySQL hereby grant you an additional
12   permission to link the program and your derivative works with the
13   separately licensed software that they have included with MySQL.
14 
15   This program is distributed in the hope that it will be useful,
16   but WITHOUT ANY WARRANTY; without even the implied warranty of
17   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18   GNU General Public License for more details.
19 
20   You should have received a copy of the GNU General Public License
21   along with this program; if not, write to the Free Software
22   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
23 */
24 
25 #include "mysqlrouter/rest_api_utils.h"
26 
27 #ifdef RAPIDJSON_NO_SIZETYPEDEFINE
28 // if we build within the server, it will set RAPIDJSON_NO_SIZETYPEDEFINE
29 // globally and require to include my_rapidjson_size_t.h
30 #include "my_rapidjson_size_t.h"
31 #endif
32 
33 #include <rapidjson/document.h>
34 #include <rapidjson/writer.h>
35 
36 #include "mysql/harness/utility/string.h"  // join
37 #include "mysqlrouter/http_auth_realm_component.h"
38 #include "mysqlrouter/http_server_component.h"  // HttpAuth::require_auth()
39 
send_json_document(HttpRequest & req,HttpStatusCode::key_type status_code,const rapidjson::Document & json_doc)40 void send_json_document(HttpRequest &req, HttpStatusCode::key_type status_code,
41                         const rapidjson::Document &json_doc) {
42   // serialize json-document into a string
43   auto chunk = req.get_output_buffer();
44 
45   {
46     rapidjson::StringBuffer json_buf;
47     {
48       rapidjson::Writer<rapidjson::StringBuffer> json_writer(json_buf);
49 
50       json_doc.Accept(json_writer);
51 
52     }  // free json_doc and json_writer early
53 
54     // perhaps we could use evbuffer_add_reference() and a unique-ptr on
55     // json_buf here. needs to be benchmarked
56     chunk.add(json_buf.GetString(), json_buf.GetSize());
57   }  // free json_buf early
58   req.send_reply(status_code,
59                  HttpStatusCode::get_default_status_text(status_code), chunk);
60 }
61 
send_rfc7807_error(HttpRequest & req,HttpStatusCode::key_type status_code,const std::map<std::string,std::string> & fields)62 void send_rfc7807_error(HttpRequest &req, HttpStatusCode::key_type status_code,
63                         const std::map<std::string, std::string> &fields) {
64   auto out_hdrs = req.get_output_headers();
65   out_hdrs.add("Content-Type", "application/problem+json");
66 
67   rapidjson::Document json_doc;
68 
69   auto &allocator = json_doc.GetAllocator();
70 
71   json_doc.SetObject();
72   for (const auto &field : fields) {
73     json_doc.AddMember(
74         rapidjson::Value(field.first.c_str(), field.first.size(), allocator),
75         rapidjson::Value(field.second.c_str(), field.second.size(), allocator),
76         allocator);
77   }
78 
79   json_doc.AddMember("status", status_code, allocator);
80 
81   send_json_document(req, status_code, json_doc);
82 }
83 
send_rfc7807_not_found_error(HttpRequest & req)84 void send_rfc7807_not_found_error(HttpRequest &req) {
85   send_rfc7807_error(req, HttpStatusCode::NotFound,
86                      {
87                          {"title", "URI not found"},
88                          {"instance", req.get_uri().get_path()},
89                      });
90 }
91 
ensure_http_method(HttpRequest & req,HttpMethod::Bitset allowed_methods)92 bool ensure_http_method(HttpRequest &req, HttpMethod::Bitset allowed_methods) {
93   if ((HttpMethod::Bitset(req.get_method()) & allowed_methods).any())
94     return true;
95 
96   std::vector<std::string> allowed_method_names;
97   if ((allowed_methods & HttpMethod::Bitset(HttpMethod::Put)).any())
98     allowed_method_names.push_back("PUT");
99   if ((allowed_methods & HttpMethod::Bitset(HttpMethod::Get)).any())
100     allowed_method_names.push_back("GET");
101   if ((allowed_methods & HttpMethod::Bitset(HttpMethod::Head)).any())
102     allowed_method_names.push_back("HEAD");
103   if ((allowed_methods & HttpMethod::Bitset(HttpMethod::Post)).any())
104     allowed_method_names.push_back("POST");
105   if ((allowed_methods & HttpMethod::Bitset(HttpMethod::Trace)).any())
106     allowed_method_names.push_back("TRACE");
107   if ((allowed_methods & HttpMethod::Bitset(HttpMethod::Connect)).any())
108     allowed_method_names.push_back("CONNECT");
109   if ((allowed_methods & HttpMethod::Bitset(HttpMethod::Patch)).any())
110     allowed_method_names.push_back("PATCH");
111   if ((allowed_methods & HttpMethod::Bitset(HttpMethod::Options)).any())
112     allowed_method_names.push_back("OPTIONS");
113   if ((allowed_methods & HttpMethod::Bitset(HttpMethod::Delete)).any())
114     allowed_method_names.push_back("DELETE");
115 
116   auto out_hdrs = req.get_output_headers();
117   out_hdrs.add("Allow", mysql_harness::join(allowed_method_names, ",").c_str());
118 
119   send_rfc7807_error(
120       req, HttpStatusCode::MethodNotAllowed,
121       {
122           {"title", "HTTP Method not allowed"},
123           {"detail", "only HTTP Methods " +
124                          mysql_harness::join(allowed_method_names, ",") +
125                          " are supported"},
126       });
127 
128   return false;
129 }
130 
ensure_auth(HttpRequest & req,const std::string require_realm)131 bool ensure_auth(HttpRequest &req, const std::string require_realm) {
132   if (!require_realm.empty()) {
133     if (auto realm =
134             HttpAuthRealmComponent::get_instance().get(require_realm)) {
135       if (HttpAuth::require_auth(req, realm)) {
136         // auth wasn't successful, response already sent
137         return false;
138       }
139 
140       // access granted, fall through
141     }
142   }
143 
144   return true;
145 }
146 
ensure_no_params(HttpRequest & req)147 bool ensure_no_params(HttpRequest &req) {
148   if (!req.get_uri().get_query().empty()) {
149     send_rfc7807_error(req, HttpStatusCode::BadRequest,
150                        {
151                            {"title", "validation error"},
152                            {"detail", "parameters not allowed"},
153                        });
154     return false;
155   }
156 
157   return true;
158 }
159 
ensure_modified_since(HttpRequest & req,time_t last_modified)160 bool ensure_modified_since(HttpRequest &req, time_t last_modified) {
161   if (!req.is_modified_since(last_modified)) {
162     req.send_reply(HttpStatusCode::NotModified);
163     return false;
164   }
165 
166   req.add_last_modified(last_modified);
167 
168   return true;
169 }
170