-
Notifications
You must be signed in to change notification settings - Fork 9k
Expand file tree
/
Copy pathHTTPHandlerFactory.cpp
More file actions
740 lines (659 loc) · 36.4 KB
/
Copy pathHTTPHandlerFactory.cpp
File metadata and controls
740 lines (659 loc) · 36.4 KB
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
#include <Server/HTTP/HTTPRequestHandler.h>
#include <Server/HTTPHandler.h>
#include <Server/HTTPHandlerFactory.h>
#include <Server/IServer.h>
#include <Server/IndexRequestHandler.h>
#include <Server/InterserverIOHTTPHandler.h>
#include <Server/PrometheusMetricsWriter.h>
#include <Server/PrometheusRequestHandlerFactory.h>
#include <Server/ReplicasStatusHandler.h>
#include <Server/StaticRequestHandler.h>
#include <Server/WebUIRequestHandler.h>
#include <Server/WebTerminalRequestHandler.h>
#include <Core/Settings.h>
#include <Interpreters/Context.h>
#include <boost/algorithm/string/predicate.hpp>
#if CLICKHOUSE_CLOUD
#include <Server/CloudReadinessHandler.h>
#endif
#if USE_SSL
#include <Server/ACME/RequestHandler.h>
#include <Server/ACME/Client.h>
#endif
#include <Poco/Util/AbstractConfiguration.h>
#include <Common/SQLDefinedHandlers/SQLDefinedHandlersFactory.h>
#include <Common/SQLDefinedHandlers/SQLDefinedHandler.h>
#include <base/find_symbols.h>
namespace DB
{
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
extern const int UNKNOWN_ELEMENT_IN_CONFIG;
extern const int INVALID_CONFIG_PARAMETER;
}
namespace
{
class RedirectRequestHandler : public HTTPRequestHandler
{
private:
std::string url;
std::unordered_map<String, String> http_response_headers_override;
public:
explicit RedirectRequestHandler(std::string url_, std::unordered_map<String, String> http_response_headers_override_ = {})
: url(std::move(url_)), http_response_headers_override(http_response_headers_override_)
{
}
void handleRequest(HTTPServerRequest &, HTTPServerResponse & response, const ProfileEvents::Event &) override
{
applyHTTPResponseHeaders(response, http_response_headers_override);
response.redirect(url);
}
};
/// Matches incoming requests against the registry of SQL-defined handlers (CREATE HANDLER).
/// Consulted after all configuration-defined handlers, so config handlers always take priority.
/// SQL-defined handlers are tried in lexicographic order of their names.
class SQLDefinedHTTPHandlerFactory : public HTTPRequestHandlerFactory
{
public:
SQLDefinedHTTPHandlerFactory(
IServer & server_,
std::string protocol_name_,
std::optional<String> default_session_user_)
: server(server_)
, protocol_name(std::move(protocol_name_))
, default_session_user(std::move(default_session_user_))
{
}
std::unique_ptr<HTTPRequestHandler> createRequestHandler(const HTTPServerRequest & request) override
{
auto handlers = SQLDefinedHandlersFactory::instance().getAll();
if (!handlers || handlers->empty())
return nullptr;
/// Match against the URL path only, without the query string and fragment.
const auto & uri = request.getURI();
const char * path_end = find_first_symbols<'?', '#'>(uri.data(), uri.data() + uri.size());
const String path(uri.data(), path_end);
const String & method = request.getMethod();
/// Mirror the method semantics of config-defined HTTP handlers (see `allowGetAndHeadRequest` /
/// `allowRESTMethods` in HTTPHandlerFactory.h): `HEAD` reuses the handler declared for `GET`, and every
/// path/protocol match answers `OPTIONS` so the generic preflight/CORS branch in `HTTPHandler::handleRequest`
/// can respond. `ParserCreateHandlerQuery` never stores `HEAD`/`OPTIONS`, so these cannot be matched directly.
const bool is_head = method == Poco::Net::HTTPRequest::HTTP_HEAD;
const bool is_options = method == Poco::Net::HTTPRequest::HTTP_OPTIONS;
for (const auto & [name, handler] : *handlers)
{
const bool method_matches = handler->matchesMethod(method)
|| (is_head && handler->matchesMethod(Poco::Net::HTTPRequest::HTTP_GET))
|| is_options;
if (handler->matchesProtocol(protocol_name)
&& method_matches
&& handler->matchesURL(path))
{
HTTPHandlerConnectionConfig connection_config;
connection_config.default_session_user = default_session_user;
return std::make_unique<SQLDefinedQueryHandler>(server, connection_config, *handler);
}
}
return nullptr;
}
private:
IServer & server;
std::string protocol_name;
std::optional<String> default_session_user;
};
HTTPRequestHandlerFactoryPtr createRedirectHandlerFactory(
const Poco::Util::AbstractConfiguration & config,
const std::string & config_prefix,
std::unordered_map<String, String> common_headers)
{
std::string url = config.getString(config_prefix + ".handler.location");
auto headers = parseHTTPResponseHeadersWithCommons(config, config_prefix, common_headers);
auto factory = std::make_shared<HandlingRuleHTTPHandlerFactory<RedirectRequestHandler>>(
[my_url = std::move(url), headers_override = std::move(headers)]()
{
return std::make_unique<RedirectRequestHandler>(my_url, headers_override);
});
factory->addFiltersFromConfig(config, config_prefix);
return factory;
}
}
static void addCommonDefaultHandlersFactory(HTTPRequestHandlerFactoryMain & factory, IServer & server, const Poco::Util::AbstractConfiguration & config);
static void addDefaultHandlersFactory(
HTTPRequestHandlerFactoryMain & factory,
IServer & server,
const Poco::Util::AbstractConfiguration & config,
AsynchronousMetrics & async_metrics,
const std::optional<String> & default_session_user);
static void addCatchAllQueryHandlerFactory(
HTTPRequestHandlerFactoryMain & factory,
IServer & server,
const Poco::Util::AbstractConfiguration & config,
const std::optional<String> & default_session_user);
static auto createPingHandlerFactory(IServer & server)
{
auto creator = [&server]() -> std::unique_ptr<StaticRequestHandler>
{
constexpr auto ping_response_expression = "Ok.\n";
return std::make_unique<StaticRequestHandler>(
server, ping_response_expression, parseHTTPResponseHeaders("text/html; charset=UTF-8"));
};
return std::make_shared<HandlingRuleHTTPHandlerFactory<StaticRequestHandler>>(std::move(creator));
}
static auto createPingHandlerFactory(IServer & server, const Poco::Util::AbstractConfiguration & config, const String & config_prefix,
std::unordered_map<String, String> common_headers)
{
auto creator = [&server, &config, config_prefix, common_headers]() -> std::unique_ptr<StaticRequestHandler>
{
constexpr auto ping_response_expression = "Ok.\n";
auto headers = parseHTTPResponseHeadersWithCommons(config, config_prefix, "text/html; charset=UTF-8", common_headers);
return std::make_unique<StaticRequestHandler>(
server, ping_response_expression, headers);
};
return std::make_shared<HandlingRuleHTTPHandlerFactory<StaticRequestHandler>>(std::move(creator));
}
template <typename UIRequestHandler>
static auto createWebUIHandlerFactory(IServer & server, const Poco::Util::AbstractConfiguration & config, const String & config_prefix,
std::unordered_map<String, String> common_headers)
{
auto creator = [&server, &config, config_prefix, common_headers]() -> std::unique_ptr<UIRequestHandler>
{
auto headers = parseHTTPResponseHeadersWithCommons(config, config_prefix, "text/html; charset=UTF-8", common_headers);
return std::make_unique<UIRequestHandler>(server, headers);
};
return std::make_shared<HandlingRuleHTTPHandlerFactory<UIRequestHandler>>(std::move(creator));
}
static inline auto createHandlersFactoryFromConfig(
IServer & server,
const Poco::Util::AbstractConfiguration & config,
const std::string & name,
const String & prefix,
AsynchronousMetrics & async_metrics,
const std::optional<String> & default_session_user)
{
auto main_handler_factory = std::make_shared<HTTPRequestHandlerFactoryMain>(name);
Poco::Util::AbstractConfiguration::Keys keys;
config.keys(prefix, keys);
std::unordered_map<String, String> common_headers_override;
if (std::find(keys.begin(), keys.end(), "common_http_response_headers") != keys.end())
{
auto common_headers_prefix = prefix + ".common_http_response_headers";
Poco::Util::AbstractConfiguration::Keys headers_keys;
config.keys(common_headers_prefix, headers_keys);
for (const auto & header_key : headers_keys)
{
common_headers_override[header_key] = config.getString(common_headers_prefix + "." + header_key);
}
}
/// Process configured rules first, then fall back to defaults. This guarantees that a
/// configured rule (e.g. a redirect for `/upyachka` or a dynamic-query handler under a URL
/// prefix like `/api/v1`) takes precedence over the built-in catch-all dynamic handler that
/// `<defaults/>` registers. Without this ordering, when the config is split across multiple
/// files (config.d/) the merged child-key iteration order is not insertion order, and the
/// default catch-all may be registered before the user's rule, breaking it.
bool has_defaults = std::find(keys.begin(), keys.end(), "defaults") != keys.end();
for (const auto & key : keys)
{
if (key == "defaults")
{
/// Defer.
}
else if (startsWith(key, "rule"))
{
const auto & handler_type = config.getString(prefix + "." + key + ".handler.type", "");
if (handler_type.empty())
throw Exception(ErrorCodes::INVALID_CONFIG_PARAMETER, "Handler type in config is not specified here: "
"{}.{}.handler.type", prefix, key);
if (handler_type == "static")
{
main_handler_factory->addHandler(createStaticHandlerFactory(server, config, prefix + "." + key, common_headers_override));
}
else if (handler_type == "redirect")
{
main_handler_factory->addHandler(createRedirectHandlerFactory(config, prefix + "." + key, common_headers_override));
}
else if (handler_type == "dynamic_query_handler")
{
main_handler_factory->addHandler(createDynamicHandlerFactory(server, config, prefix + "." + key, common_headers_override, default_session_user));
}
else if (handler_type == "predefined_query_handler")
{
main_handler_factory->addHandler(createPredefinedHandlerFactory(server, config, prefix + "." + key, common_headers_override, default_session_user));
}
else if (handler_type.starts_with("prometheus"))
{
main_handler_factory->addHandler(
createPrometheusHandlerFactoryForHTTPRule(server, config, prefix + "." + key, async_metrics, common_headers_override, default_session_user));
}
else if (handler_type == "replicas_status")
{
main_handler_factory->addHandler(createReplicasStatusHandlerFactory(server, config, prefix + "." + key, common_headers_override));
}
else if (handler_type == "ping")
{
const String config_prefix = prefix + "." + key;
auto handler = createPingHandlerFactory(server, config, config_prefix, common_headers_override);
handler->addFiltersFromConfig(config, config_prefix);
main_handler_factory->addHandler(std::move(handler));
}
else if (handler_type == "index")
{
const String config_prefix = prefix + "." + key;
auto handler = createWebUIHandlerFactory<IndexRequestHandler>(server, config, prefix + "." + key, common_headers_override);
handler->addFiltersFromConfig(config, config_prefix);
main_handler_factory->addHandler(std::move(handler));
}
else if (handler_type == "play")
{
auto handler = createWebUIHandlerFactory<PlayWebUIRequestHandler>(server, config, prefix + "." + key, common_headers_override);
handler->addFiltersFromConfig(config, prefix + "." + key);
main_handler_factory->addHandler(std::move(handler));
}
else if (handler_type == "dashboard")
{
auto handler = createWebUIHandlerFactory<DashboardWebUIRequestHandler>(server, config, prefix + "." + key, common_headers_override);
handler->addFiltersFromConfig(config, prefix + "." + key);
main_handler_factory->addHandler(std::move(handler));
}
else if (handler_type == "binary")
{
auto handler = createWebUIHandlerFactory<BinaryWebUIRequestHandler>(server, config, prefix + "." + key, common_headers_override);
handler->addFiltersFromConfig(config, prefix + "." + key);
main_handler_factory->addHandler(std::move(handler));
}
else if (handler_type == "merges")
{
auto handler = createWebUIHandlerFactory<MergesWebUIRequestHandler>(server, config, prefix + "." + key, common_headers_override);
handler->addFiltersFromConfig(config, prefix + "." + key);
main_handler_factory->addHandler(std::move(handler));
}
else if (handler_type == "jemalloc")
{
auto handler = createWebUIHandlerFactory<JemallocWebUIRequestHandler>(server, config, prefix + "." + key, common_headers_override);
handler->addFiltersFromConfig(config, prefix + "." + key);
main_handler_factory->addHandler(std::move(handler));
}
else if (handler_type == "schema")
{
auto handler = createWebUIHandlerFactory<SchemaWebUIRequestHandler>(server, config, prefix + "." + key, common_headers_override);
handler->addFiltersFromConfig(config, prefix + "." + key);
main_handler_factory->addHandler(std::move(handler));
}
else if (handler_type == "docs")
{
auto handler = createWebUIHandlerFactory<DocsWebUIRequestHandler>(server, config, prefix + "." + key, common_headers_override);
handler->addFiltersFromConfig(config, prefix + "." + key);
main_handler_factory->addHandler(std::move(handler));
}
else if (handler_type == "js")
{
/// `JavaScriptWebUIRequestHandler` serves a fixed set of embedded JS/CSS
/// assets hardcoded inside other UI pages (`dashboard.html` references
/// `/js/uplot.js` and `/js/lz-string.js`; `webterminal.html` references
/// the xterm files). The handler itself routes by exact path and replies
/// with `404` for anything else, so accept any URL under the `/js/` prefix
/// here rather than maintaining a parallel allowlist that drifts every
/// time a new asset is embedded.
const auto & path = config.getString(prefix + "." + key + ".url", "");
if (!startsWith(path, "/js/"))
{
throw Exception(ErrorCodes::INVALID_CONFIG_PARAMETER,
"Handler type 'js' is only supported for urls under '/js/'. "
"Configured path here: {}", path);
}
auto handler = createWebUIHandlerFactory<JavaScriptWebUIRequestHandler>(server, config, prefix + "." + key, common_headers_override);
handler->addFiltersFromConfig(config, prefix + "." + key);
main_handler_factory->addHandler(std::move(handler));
}
else if (handler_type == "webterminal")
{
/// Build the handler through a creator lambda (like `addDefaultHandlersFactory`)
/// so that a composable HTTP endpoint exposing the web terminal via a custom
/// `handlers` section honors the per-endpoint `default_session_user` override
/// (including an empty override, which disables anonymous access) instead of
/// falling back to the global setting.
auto webterminal_creator = [&server, default_session_user] () -> std::unique_ptr<WebTerminalRequestHandler>
{
return std::make_unique<WebTerminalRequestHandler>(server, default_session_user);
};
auto handler = std::make_shared<HandlingRuleHTTPHandlerFactory<WebTerminalRequestHandler>>(std::move(webterminal_creator));
handler->addFiltersFromConfig(config, prefix + "." + key);
main_handler_factory->addHandler(std::move(handler));
}
#if USE_SSL
else if (handler_type == "acme")
{
auto handler = std::make_shared<HandlingRuleHTTPHandlerFactory<ACMERequestHandler>>(server);
handler->addFiltersFromConfig(config, prefix + "." + key);
main_handler_factory->addHandler(std::move(handler));
}
#endif
#if CLICKHOUSE_CLOUD
else if (handler_type == "cloud")
{
main_handler_factory->addHandler(createCloudHandlerFactory(server, config, prefix + "." + key));
}
#endif
else
throw Exception(ErrorCodes::INVALID_CONFIG_PARAMETER, "Unknown handler type '{}' in config here: {}.{}.handler.type",
handler_type, prefix, key);
}
else if (key != "common_http_response_headers")
throw Exception(ErrorCodes::UNKNOWN_ELEMENT_IN_CONFIG, "Unknown element in config: "
"{}.{}, must be 'rule' or 'defaults'", prefix, key);
}
/// All configured rules are now registered. Add defaults (which includes the catch-all
/// dynamic-query handler) last so they only match what the configured rules didn't.
if (has_defaults)
addDefaultHandlersFactory(*main_handler_factory, server, config, async_metrics, default_session_user);
return main_handler_factory;
}
static inline HTTPRequestHandlerFactoryPtr createHTTPHandlerFactory(
IServer & server,
const Poco::Util::AbstractConfiguration & config,
const std::string & name,
AsynchronousMetrics & async_metrics,
const std::string & http_handlers_key,
const std::string & protocol_name,
const std::optional<String> & default_session_user)
{
std::shared_ptr<HTTPRequestHandlerFactoryMain> factory;
if (config.has(http_handlers_key))
{
factory = createHandlersFactoryFromConfig(server, config, name, http_handlers_key, async_metrics, default_session_user);
}
else
{
factory = std::make_shared<HTTPRequestHandlerFactoryMain>(name);
addDefaultHandlersFactory(*factory, server, config, async_metrics, default_session_user);
}
/// SQL-defined handlers (CREATE HANDLER) are matched after all configuration-defined handlers.
factory->addHandler(std::make_shared<SQLDefinedHTTPHandlerFactory>(server, protocol_name, default_session_user));
/// And the catch-all query handler comes last of all, so that it only sees the requests no
/// handler claimed: it matches paths that belong to somebody else (any `OPTIONS` preflight, and -
/// when `http_allow_path_requests` is on - any path at all, to interpret it as a database/table
/// reference). Registering it earlier would shadow every SQL-defined handler.
if (factory->areDefaultHandlersRegistered())
addCatchAllQueryHandlerFactory(*factory, server, config, default_session_user);
return factory;
}
static inline HTTPRequestHandlerFactoryPtr createInterserverHTTPHandlerFactory(IServer & server, const std::string & name, const Poco::Util::AbstractConfiguration & config)
{
auto factory = std::make_shared<HTTPRequestHandlerFactoryMain>(name);
addCommonDefaultHandlersFactory(*factory, server, config);
auto main_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<InterserverIOHTTPHandler>>(server);
main_handler->allowPostAndGetParamsAndOptionsRequest();
factory->addHandler(main_handler);
return factory;
}
HTTPRequestHandlerFactoryPtr createHandlerFactory(
IServer & server,
const Poco::Util::AbstractConfiguration & config,
AsynchronousMetrics & async_metrics,
const std::string & name,
const std::string & http_handlers_key,
const std::string & protocol_name,
const std::optional<String> & default_session_user)
{
if (name == "HTTPHandler-factory" || name == "HTTPSHandler-factory")
return createHTTPHandlerFactory(server, config, name, async_metrics, http_handlers_key.empty() ? "http_handlers" : http_handlers_key, protocol_name, default_session_user);
if (name == "InterserverIOHTTPHandler-factory" || name == "InterserverIOHTTPSHandler-factory")
return createInterserverHTTPHandlerFactory(server, name, config);
if (name == "PrometheusHandler-factory")
return createPrometheusHandlerFactory(server, config, async_metrics, name, default_session_user);
if (name == "KeeperPrometheusHandler-factory")
return createKeeperPrometheusHandlerFactory(server, config, async_metrics, name, default_session_user);
#if CLICKHOUSE_CLOUD
if (name == "CloudHandler-factory")
return createCloudMainHandlerFactory(server, config, name);
#endif
throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown HTTP handler factory name.");
}
void addCommonDefaultHandlersFactory(HTTPRequestHandlerFactoryMain & factory, IServer & server, const Poco::Util::AbstractConfiguration & config)
{
if (config.has("http_server_default_response"))
{
auto root_creator = [&server]() -> std::unique_ptr<StaticRequestHandler>
{
constexpr auto root_response_expression = "config://http_server_default_response";
return std::make_unique<StaticRequestHandler>(
server, root_response_expression, parseHTTPResponseHeaders("text/html; charset=UTF-8"));
};
auto root_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<StaticRequestHandler>>(std::move(root_creator));
root_handler->attachStrictPath("/");
root_handler->allowGetAndHeadRequest();
factory.addHandler(root_handler);
}
else
{
/// Use the default landing page / ping handler.
auto root_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<IndexRequestHandler>>(server);
root_handler->attachStrictPath("/");
root_handler->allowGetAndHeadRequest();
factory.addHandler(root_handler);
}
auto ping_handler = createPingHandlerFactory(server);
ping_handler->attachStrictPath("/ping");
ping_handler->allowGetAndHeadRequest();
factory.addPathToHints("/ping");
factory.addHandler(ping_handler);
auto replicas_status_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<ReplicasStatusHandler>>(server);
replicas_status_handler->attachNonStrictPath("/replicas_status");
replicas_status_handler->allowGetAndHeadRequest();
factory.addPathToHints("/replicas_status");
factory.addHandler(replicas_status_handler);
auto play_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<PlayWebUIRequestHandler>>(server);
play_handler->attachNonStrictPath("/play");
play_handler->allowGetAndHeadRequest();
factory.addPathToHints("/play");
factory.addHandler(play_handler);
auto dashboard_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<DashboardWebUIRequestHandler>>(server);
dashboard_handler->attachNonStrictPath("/dashboard");
dashboard_handler->allowGetAndHeadRequest();
factory.addPathToHints("/dashboard");
factory.addHandler(dashboard_handler);
auto binary_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<BinaryWebUIRequestHandler>>(server);
binary_handler->attachNonStrictPath("/binary");
binary_handler->allowGetAndHeadRequest();
factory.addPathToHints("/binary");
factory.addHandler(binary_handler);
auto merges_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<MergesWebUIRequestHandler>>(server);
merges_handler->attachNonStrictPath("/merges");
merges_handler->allowGetAndHeadRequest();
factory.addPathToHints("/merges");
factory.addHandler(merges_handler);
auto jemalloc_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<JemallocWebUIRequestHandler>>(server);
jemalloc_handler->attachNonStrictPath("/jemalloc");
jemalloc_handler->allowGetAndHeadRequest();
factory.addPathToHints("/jemalloc");
factory.addHandler(jemalloc_handler);
auto schema_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<SchemaWebUIRequestHandler>>(server);
schema_handler->attachNonStrictPath("/schema");
schema_handler->allowGetAndHeadRequest();
factory.addPathToHints("/schema");
factory.addHandler(schema_handler);
auto processors_profile_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<ProcessorsProfileWebUIRequestHandler>>(server);
processors_profile_handler->attachNonStrictPath("/processors-profile");
processors_profile_handler->allowGetAndHeadRequest();
factory.addPathToHints("/processors-profile");
factory.addHandler(processors_profile_handler);
auto docs_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<DocsWebUIRequestHandler>>(server);
docs_handler->attachNonStrictPath("/docs");
docs_handler->allowGetAndHeadRequest();
factory.addPathToHints("/docs");
factory.addHandler(docs_handler);
auto js_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<JavaScriptWebUIRequestHandler>>(server);
js_handler->attachNonStrictPath("/js/");
js_handler->allowGetAndHeadRequest();
factory.addHandler(js_handler);
auto clickstack_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<ClickStackUIRequestHandler>>(server);
clickstack_handler->attachNonStrictPath("/clickstack");
clickstack_handler->allowGetAndHeadRequest();
factory.addPathToHints("/clickstack");
factory.addHandler(clickstack_handler);
auto sql_console_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<SQLConsoleUIRequestHandler>>(server);
/// Match "/ui" exactly or "/ui" followed by a path/query/fragment boundary, so that sibling
/// routes like "/uix" are not hijacked by the SQL Console SPA fallback.
sql_console_handler->addFilter([](const auto & request)
{
const auto & uri = request.getURI();
return uri == "/ui"
|| startsWith(uri, "/ui/")
|| startsWith(uri, "/ui?")
|| startsWith(uri, "/ui#");
});
sql_console_handler->allowGetAndHeadRequest();
factory.addPathToHints("/ui");
factory.addHandler(sql_console_handler);
#if USE_SSL
if (server.config().has("acme"))
{
auto acme_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<ACMERequestHandler>>(server);
acme_handler->attachNonStrictPath(ACME::CHALLENGE_HTTP_PATH);
acme_handler->allowGetAndHeadRequest();
factory.addHandler(acme_handler);
}
#endif
}
void addDefaultHandlersFactory(
HTTPRequestHandlerFactoryMain & factory,
IServer & server,
const Poco::Util::AbstractConfiguration & config,
AsynchronousMetrics & async_metrics,
const std::optional<String> & default_session_user)
{
addCommonDefaultHandlersFactory(factory, server, config);
/// `/webterminal` is intentionally registered only on the user-facing HTTP
/// port, never on the interserver port (which `createInterserverHTTPHandlerFactory`
/// builds via `addCommonDefaultHandlersFactory`). The interserver port has a
/// different (HMAC) trust model and is typically less-firewalled inside the
/// cluster, so exposing an interactive PTY shell there would punch a hole
/// through that boundary even when `enable_webterminal` is set.
auto webterminal_creator = [&server, default_session_user] () -> std::unique_ptr<WebTerminalRequestHandler>
{
return std::make_unique<WebTerminalRequestHandler>(server, default_session_user);
};
auto webterminal_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<WebTerminalRequestHandler>>(std::move(webterminal_creator));
webterminal_handler->attachNonStrictPath("/webterminal");
webterminal_handler->allowGetAndHeadRequest();
factory.addPathToHints("/webterminal");
factory.addHandler(webterminal_handler);
/// Register Prometheus BEFORE the dynamic query handler. The dynamic handler's catch-all
/// path match (gated by the `http_allow_*_as_path` settings) would otherwise shadow
/// `/metrics` and other prometheus endpoints.
/// createPrometheusHandlerFactoryForHTTPRuleDefaults() can return nullptr if prometheus protocols must not be served on http port.
if (auto prometheus_handler = createPrometheusHandlerFactoryForHTTPRuleDefaults(server, config, async_metrics, default_session_user))
factory.addHandler(prometheus_handler);
auto path_hints = factory.getPathHints();
auto dynamic_creator = [&server, default_session_user, path_hints] () -> std::unique_ptr<DynamicQueryHandler>
{
HTTPHandlerConnectionConfig connection_config;
connection_config.default_session_user = default_session_user;
return std::make_unique<DynamicQueryHandler>(server, connection_config, "query", std::nullopt, "", path_hints);
};
auto query_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<DynamicQueryHandler>>(std::move(dynamic_creator));
query_handler->addFilter([](const auto & request)
{
/// The explicit query-string forms (`?...`, `/?...`, `/query?...`) plus an empty or "/"
/// POST. These name no path of their own, so nothing else can be competing for them and
/// they are claimed here, among the defaults. The catch-all forms (a CORS preflight for
/// any path, and the path-as-file routing) are registered separately, after the
/// SQL-defined handlers - see `addCatchAllQueryHandlerFactory`.
bool path_matches_get_or_head = startsWith(request.getURI(), "?")
|| startsWith(request.getURI(), "/?")
|| startsWith(request.getURI(), "/query?");
bool is_get_or_head_request = request.getMethod() == Poco::Net::HTTPRequest::HTTP_GET
|| request.getMethod() == Poco::Net::HTTPRequest::HTTP_HEAD;
bool path_matches_post_or_options = path_matches_get_or_head
|| request.getURI() == "/"
|| request.getURI().empty();
bool is_post_or_options_request = request.getMethod() == Poco::Net::HTTPRequest::HTTP_POST
|| request.getMethod() == Poco::Net::HTTPRequest::HTTP_OPTIONS;
return (path_matches_get_or_head && is_get_or_head_request) || (path_matches_post_or_options && is_post_or_options_request);
}
);
factory.addHandler(query_handler);
/// Record that the catch-all still has to be appended. It cannot be added here: it claims paths
/// it does not own, so it has to lose to every handler that does - including the SQL-defined ones
/// (`CREATE HANDLER`), which `createHTTPHandlerFactory` registers after all of these.
factory.setDefaultHandlersRegistered();
}
void addCatchAllQueryHandlerFactory(
HTTPRequestHandlerFactoryMain & factory,
IServer & server,
const Poco::Util::AbstractConfiguration & config,
const std::optional<String> & default_session_user)
{
auto path_hints = factory.getPathHints();
auto dynamic_creator = [&server, default_session_user, path_hints] () -> std::unique_ptr<DynamicQueryHandler>
{
HTTPHandlerConnectionConfig connection_config;
connection_config.default_session_user = default_session_user;
return std::make_unique<DynamicQueryHandler>(server, connection_config, "query", std::nullopt, "", path_hints);
};
/// Path-as-file routing is gated by a single server-level flag (`http_allow_path_requests`,
/// default off), evaluated here at routing time — before authentication, where the connecting
/// user is unknown. The per-user `http_allow_database_as_path` / `http_allow_table_as_file` /
/// `http_allow_filters_as_path` settings then control, after authentication, whether a routed
/// path is actually interpreted (see `HTTPHandler::processQuery`). When the server flag is off,
/// path requests are not claimed at all, so unknown paths keep returning a plain pre-auth 404
/// (`NotFoundHandler`).
const bool allow_path_requests = config.getBool("http_allow_path_requests", false);
auto query_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<DynamicQueryHandler>>(std::move(dynamic_creator));
query_handler->addFilter([allow_path_requests](const auto & request)
{
const auto & method = request.getMethod();
bool is_get_or_head = method == Poco::Net::HTTPRequest::HTTP_GET
|| method == Poco::Net::HTTPRequest::HTTP_HEAD;
bool is_post_or_options = method == Poco::Net::HTTPRequest::HTTP_POST
|| method == Poco::Net::HTTPRequest::HTTP_OPTIONS;
/// An `OPTIONS` request is a CORS preflight (and the web-UI connectivity health-check).
/// `HTTPHandler::handleRequest` answers it via `processOptionsRequest` before
/// authentication and without running a query, so it is claimed here for any path —
/// regardless of the URL shape and independent of `http_allow_path_requests`. Otherwise an
/// `OPTIONS` preflight to a path the page will later GET (e.g. `/play`, `/db/table`)
/// reaches no handler and the browser treats the connection as broken. A handler that owns
/// the path answers the preflight itself: config-defined and SQL-defined handlers both
/// match `OPTIONS`, and both are registered before this one.
if (method == Poco::Net::HTTPRequest::HTTP_OPTIONS)
return true;
if (!is_get_or_head && !is_post_or_options)
return false;
/// Everything below is the path-as-file extension. Skip it unless path requests are
/// allowed server-wide, so unknown paths fall through to `NotFoundHandler` (HTTP 404)
/// exactly as before this PR. (The path features are still gated again per-user inside
/// `HTTPHandler::processQuery`; this server-level flag is only the routing-time gate.)
if (!allow_path_requests)
return false;
/// Skip the path-as-file routing for clients sending an `Authorization` header with a
/// scheme ClickHouse does not implement (e.g. `AWS4-HMAC-SHA256`, used by
/// `clickhouse-local`'s S3 client when probing paths like `/nonexistent`). The dynamic
/// handler would otherwise reject the request with `AUTHENTICATION_FAILED` (HTTP 403)
/// before it has a chance to look up the path against the catalog; the
/// `NotFoundHandler` fallback returns a plain 404 the S3 client is already prepared to
/// handle as non-retriable. Supported schemes (Basic, Negotiate) still get the
/// dynamic-handler treatment.
if (request.has("Authorization"))
{
const auto & auth_header = request.get("Authorization");
std::string_view scheme = auth_header;
auto sep = scheme.find(' ');
if (sep != std::string_view::npos)
scheme = scheme.substr(0, sep);
/// `Authorization: never` is a supported sentinel that makes `authenticateUserByHTTP`
/// ignore credentials (see `03362_basic_auth_interactive_not_with_authorization_never`);
/// let it through so a path-style request is handled the same way the query-string
/// route is, instead of falling through to `NotFoundHandler`.
if (!boost::iequals(scheme, "Basic") && !boost::iequals(scheme, "Negotiate") && !boost::iequals(auth_header, "never"))
return false;
}
/// Path-as-file routing: accept any single-component or multi-segment path so the
/// dynamic handler can either resolve it as a database/table/filter reference or
/// surface the combined handler+catalog hints on a typo. The actual interpretation
/// (and "is this really a database?" check) happens inside the handler.
return true;
}
);
factory.addHandler(query_handler);
}
}