-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathplugin.cc
375 lines (341 loc) · 13.1 KB
/
plugin.cc
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#include "extensions/basic_auth/plugin.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_split.h"
#include "extensions/common/wasm/base64.h"
#include "extensions/common/wasm/json_util.h"
using ::nlohmann::json;
using ::Wasm::Common::JsonArrayIterate;
using ::Wasm::Common::JsonGetField;
using ::Wasm::Common::JsonObjectIterate;
using ::Wasm::Common::JsonValueAs;
#ifdef NULL_PLUGIN
namespace proxy_wasm {
namespace null_plugin {
namespace basic_auth {
PROXY_WASM_NULL_PLUGIN_REGISTRY
#endif
static RegisterContextFactory register_BasicAuth(
CONTEXT_FACTORY(PluginContext), ROOT_FACTORY(PluginRootContext));
namespace {
void deniedNoBasicAuthData(const std::string& realm) {
sendLocalResponse(
401,
"Request denied by Basic Auth check. No Basic "
"Authentication information found.",
"", {{"WWW-Authenticate", absl::StrCat("Basic realm=", realm)}});
}
void deniedInvalidCredentials(const std::string& realm) {
sendLocalResponse(
401,
"Request denied by Basic Auth check. Invalid "
"username and/or password",
"", {{"WWW-Authenticate", absl::StrCat("Basic realm=", realm)}});
}
bool extractBasicAuthRule(
const json& configuration,
std::unordered_map<std::string,
std::vector<PluginRootContext::BasicAuthConfigRule>>*
rules) {
std::string prefix;
std::string suffix;
std::string exact;
std::vector<std::string> request_methods;
// Build a basic auth config rule
struct PluginRootContext::BasicAuthConfigRule rule;
// Example expected json object:
// {
// "prefix": "/api",
// "request_methods":[ "GET", "POST" ],
// "credentials":[ "ok:test", "admin:admin", "admin2:admin2" ]
// }
// Extract out request path field: prefix, suffix, and exact.
int32_t count = 0;
auto it = configuration.find("prefix");
if (it != configuration.end()) {
count += 1;
auto parse_result = JsonValueAs<std::string>(it.value());
if (parse_result.second != Wasm::Common::JsonParserResultDetail::OK ||
!parse_result.first.has_value()) {
LOG_WARN("failed to parse 'prefix' field in filter configuration.");
return false;
}
prefix = parse_result.first.value();
}
it = configuration.find("exact");
if (it != configuration.end()) {
count += 1;
auto parse_result = JsonValueAs<std::string>(it.value());
if (parse_result.second != Wasm::Common::JsonParserResultDetail::OK ||
!parse_result.first.has_value()) {
LOG_WARN("failed to parse 'exact' field in filter configuration.");
return false;
}
exact = parse_result.first.value();
}
it = configuration.find("suffix");
if (it != configuration.end()) {
count += 1;
auto parse_result = JsonValueAs<std::string>(it.value());
if (parse_result.second != Wasm::Common::JsonParserResultDetail::OK ||
!parse_result.first.has_value()) {
LOG_WARN("failed to parse 'suffix' field in filter configuration.");
return false;
}
suffix = parse_result.first.value();
}
// Exact one of prefix, suffix, and exact is allowed in basic auth rule
if (count != 1) {
LOG_WARN(
"exactly one of 'prefix', 'suffix', and 'exact' has to present in "
"basic "
"auth filter configuration.");
return false;
}
// Get the host that this rule applies on.
if (!JsonArrayIterate(configuration, "hosts", [&](const json& host) -> bool {
auto parse_result = JsonValueAs<std::string>(host);
if (parse_result.second != Wasm::Common::JsonParserResultDetail::OK ||
!parse_result.first.has_value()) {
LOG_WARN("failed to parse 'host' field in filter configuration.");
return false;
}
auto& host_str = parse_result.first.value();
std::pair<PluginRootContext::MATCH_TYPE, std::string> host_match;
if (absl::StartsWith(host_str, "*")) {
// suffix match
host_match.first = PluginRootContext::MATCH_TYPE::Suffix;
host_match.second = host_str.substr(1);
} else if (absl::EndsWith(host_str, "*")) {
// prefix match
host_match.first = PluginRootContext::MATCH_TYPE::Prefix;
host_match.second = host_str.substr(0, host_str.size() - 1);
} else {
host_match.first = PluginRootContext::MATCH_TYPE::Exact;
host_match.second = host_str;
}
rule.hosts.push_back(host_match);
return true;
})) {
LOG_WARN("failed to parse configuration for request hosts.");
return false;
}
// iterate over methods that rule should be applied on.
if (!JsonArrayIterate(
configuration, "request_methods", [&](const json& method) -> bool {
auto method_string = JsonValueAs<std::string>(method);
if (method_string.second !=
Wasm::Common::JsonParserResultDetail::OK) {
return false;
}
request_methods.push_back(method_string.first.value());
return true;
})) {
LOG_WARN("failed to parse configuration for request methods.");
return false;
}
if (request_methods.size() <= 0) {
LOG_WARN("at least one method has to be configured for a rule.");
return false;
}
if (!JsonArrayIterate(
configuration, "credentials", [&](const json& credentials) -> bool {
auto credential = JsonValueAs<std::string>(credentials);
if (credential.second != Wasm::Common::JsonParserResultDetail::OK) {
return false;
}
// Check if credential has `:` in it. If it has, it needs to be
// base64 encoded.
if (absl::StrContains(credential.first.value(), ":")) {
rule.encoded_credentials.insert(
Base64::encode(credential.first.value().data(),
credential.first.value().size()));
return true;
}
// Otherwise, try base64 decode and insert into credential list if
// it can be decoded.
if (!Base64::decodeWithoutPadding(credential.first.value())
.empty()) {
rule.encoded_credentials.insert(credential.first.value());
return true;
}
return false;
})) {
LOG_WARN("failed to parse configuration for credentials.");
return false;
}
if (rule.encoded_credentials.size() <= 0) {
LOG_WARN("at least one credential has to be configured for a rule.");
return false;
}
if (!prefix.empty()) {
rule.path_pattern = PluginRootContext::Prefix;
rule.request_path = prefix;
} else if (!exact.empty()) {
rule.path_pattern = PluginRootContext::Exact;
rule.request_path = exact;
} else if (!suffix.empty()) {
rule.path_pattern = PluginRootContext::Suffix;
rule.request_path = suffix;
}
for (auto& method : request_methods) {
(*rules)[method].push_back(rule);
}
return true;
}
bool hostMatch(const PluginRootContext::BasicAuthConfigRule& rule,
std::string_view request_host) {
if (rule.hosts.empty()) {
// If no host specified, consider this rule applies to all host.
return true;
}
// Remove port, if there is any. At Istio 1.10, port will be stripped
// by default https://github.com/istio/istio/issues/25350.
// Port removing code is inspired by
// https://github.com/envoyproxy/envoy/blob/v1.17.0/source/common/http/header_utility.cc#L219
const absl::string_view::size_type port_start = request_host.rfind(':');
if (port_start != std::string_view::npos) {
// According to RFC3986 v6 address is always enclosed in "[]".
// section 3.2.2.
const auto v6_end_index = request_host.rfind("]");
if (v6_end_index == absl::string_view::npos || v6_end_index < port_start) {
if ((port_start + 1) <= request_host.size()) {
request_host = request_host.substr(0, port_start);
}
}
}
for (const auto& host_match : rule.hosts) {
switch (host_match.first) {
case PluginRootContext::MATCH_TYPE::Suffix:
if (absl::EndsWith(request_host, host_match.second)) {
return true;
}
break;
case PluginRootContext::MATCH_TYPE::Prefix:
if (absl::StartsWith(request_host, host_match.second)) {
return true;
}
break;
case PluginRootContext::MATCH_TYPE::Exact:
if (request_host == host_match.second) {
return true;
}
break;
default:
LOG_WARN(absl::StrCat("unexpected host match pattern"));
return false;
}
}
return false;
}
} // namespace
FilterHeadersStatus PluginRootContext::credentialsCheck(
const PluginRootContext::BasicAuthConfigRule& rule,
std::string_view authorization_header) {
// Check if the Basic auth header starts with "Basic "
if (!absl::StartsWith(authorization_header, "Basic ")) {
deniedNoBasicAuthData(realm_);
return FilterHeadersStatus::StopIteration;
}
std::string_view authorization_header_strip =
absl::StripPrefix(authorization_header, "Basic ");
auto auth_credential_iter =
rule.encoded_credentials.find(std::string(authorization_header_strip));
// Check if encoded credential is part of the encoded_credentials
// set from our container to grant or deny access.
if (auth_credential_iter == rule.encoded_credentials.end()) {
deniedInvalidCredentials(realm_);
return FilterHeadersStatus::StopIteration;
}
return FilterHeadersStatus::Continue;
}
bool PluginRootContext::onConfigure(size_t size) {
// Parse configuration JSON string.
if (size > 0 && !configure(size)) {
LOG_WARN("configuration has errors initialization will not continue.");
return false;
}
return true;
}
bool PluginRootContext::configure(size_t configuration_size) {
auto configuration_data = getBufferBytes(WasmBufferType::PluginConfiguration,
0, configuration_size);
// Parse configuration JSON string.
auto result = ::Wasm::Common::JsonParse(configuration_data->view());
if (!result.has_value()) {
LOG_WARN(absl::StrCat("cannot parse plugin configuration JSON string: ",
configuration_data->view()));
return false;
}
// j is a JsonObject holds configuration data
auto j = result.value();
if (!JsonArrayIterate(j, "basic_auth_rules",
[&](const json& configuration) -> bool {
return extractBasicAuthRule(
configuration, &basic_auth_configuration_);
})) {
LOG_WARN(absl::StrCat("cannot parse plugin configuration JSON string: ",
configuration_data->view()));
return false;
}
auto it = j.find("realm");
if (it != j.end()) {
auto realm_string = JsonValueAs<std::string>(it.value());
if (realm_string.second != Wasm::Common::JsonParserResultDetail::OK) {
LOG_WARN(absl::StrCat(
"cannot parse realm in plugin configuration JSON string: ",
configuration_data->view()));
return false;
}
realm_ = realm_string.first.value();
}
return true;
}
FilterHeadersStatus PluginRootContext::check() {
auto request_path_header = getRequestHeader(":path");
auto request_path = request_path_header->view();
auto method = getRequestHeader(":method")->toString();
auto method_iter = basic_auth_configuration_.find(method);
// First we check if the request method is present in our container
if (method_iter != basic_auth_configuration_.end()) {
auto request_host_header = getRequestHeader(":authority");
auto request_host = request_host_header->view();
// We iterate through our vector of struct in order to find if the
// request_path according to given match pattern, is part of the plugin's
// configuration data. If that's the case we check the credentials
FilterHeadersStatus header_status = FilterHeadersStatus::Continue;
auto authorization_header = getRequestHeader("authorization");
auto authorization = authorization_header->view();
for (auto& rule : basic_auth_configuration_[method]) {
if (!hostMatch(rule, request_host)) {
continue;
}
if (rule.path_pattern == MATCH_TYPE::Prefix) {
if (absl::StartsWith(request_path, rule.request_path)) {
header_status = credentialsCheck(rule, authorization);
}
} else if (rule.path_pattern == MATCH_TYPE::Exact) {
if (rule.request_path == request_path) {
header_status = credentialsCheck(rule, authorization);
}
} else if (rule.path_pattern == MATCH_TYPE::Suffix) {
if (absl::EndsWith(request_path, rule.request_path)) {
header_status = credentialsCheck(rule, authorization);
}
}
if (header_status == FilterHeadersStatus::StopIteration) {
return FilterHeadersStatus::StopIteration;
}
}
}
// If there's no match against the request method or request path it means
// that they don't have any basic auth restriction.
return FilterHeadersStatus::Continue;
}
FilterHeadersStatus PluginContext::onRequestHeaders(uint32_t, bool) {
return rootContext()->check();
}
#ifdef NULL_PLUGIN
} // namespace basic_auth
} // namespace null_plugin
} // namespace proxy_wasm
#endif