diff --git a/changes-entries/rfc10008-query-modules.txt b/changes-entries/rfc10008-query-modules.txt new file mode 100644 index 00000000000..aea920d921b --- /dev/null +++ b/changes-entries/rfc10008-query-modules.txt @@ -0,0 +1,3 @@ + *) mod_dir, mod_cgi, mod_cgid, mod_lua, mod_charset_lite, mod_reflector: + Handle QUERY (RFC 10008) requests and their content like POST. + [Michiel W. Beijen] diff --git a/changes-entries/rfc10008-query-proxy.txt b/changes-entries/rfc10008-query-proxy.txt new file mode 100644 index 00000000000..b80b7517a8f --- /dev/null +++ b/changes-entries/rfc10008-query-proxy.txt @@ -0,0 +1,3 @@ + *) mod_proxy_ajp: Retry QUERY (RFC 10008), PROPFIND and REPORT requests + without content after a backend failure, like GET. + [Michiel W. Beijen] diff --git a/changes-entries/rfc10008-query.txt b/changes-entries/rfc10008-query.txt new file mode 100644 index 00000000000..10215a6c1cd --- /dev/null +++ b/changes-entries/rfc10008-query.txt @@ -0,0 +1,3 @@ + *) core: Add the QUERY method of RFC 10008 as a built-in method. QUERY + requests without Content-Type get 400, and conditional QUERY requests + get 304 like GET. [Michiel W. Beijen] diff --git a/docs/manual/mod/core.xml b/docs/manual/mod/core.xml index b907926ad7e..41a3b0c44bc 100644 --- a/docs/manual/mod/core.xml +++ b/docs/manual/mod/core.xml @@ -1399,6 +1399,11 @@ EnableSendfile On to service their internal private network.

+

In Strict mode, a QUERY request + (10008) without Content-Type is answered with 400, as + the media type is part of what defines the query. Unsafe + passes such requests on to the handler.

+ Example of a request leading to HTTP 400 with Strict mode # Missing CRLF
@@ -2866,7 +2871,8 @@ methods CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, - LOCK, and UNLOCK. The method name is + LOCK, UNLOCK, and QUERY. + The method name is case-sensitive. If GET is used, it will also restrict HEAD requests. The TRACE method cannot be limited (see -r:requestbody(filename) -- Reads and returns the request body of a request. +r:requestbody(filename) -- Reads and returns the request body of a POST, PUT + -- or QUERY request. -- If 'filename' is specified, it instead saves the -- contents to that file: diff --git a/docs/manual/mod/mod_reflector.xml b/docs/manual/mod/mod_reflector.xml index 06e44967832..91e294279b3 100644 --- a/docs/manual/mod/mod_reflector.xml +++ b/docs/manual/mod/mod_reflector.xml @@ -35,6 +35,9 @@ stack. A suitably configured chain of filters can be used to transform the request into a response. This module can be used to turn an output filter into an HTTP service.

+ +

Request bodies of POST and, from 2.5.1, QUERY + (10008) requests are reflected.

Examples diff --git a/docs/manual/new_features_2_6.xml b/docs/manual/new_features_2_6.xml index c507b3c801e..2c5d1462f86 100644 --- a/docs/manual/new_features_2_6.xml +++ b/docs/manual/new_features_2_6.xml @@ -87,7 +87,13 @@ specified in an IPv6 link-local address used with the Listen or VirtualHost directive. - + +
HTTP QUERY method
+
The QUERY method of 10008, a safe and idempotent + request with content, is a built-in method. QUERY requests are routed + to applications like POST, and conditional QUERY requests + are answered with 304 like GET.
+
@@ -202,6 +208,13 @@
Module Developer Changes
+
QUERY method
+
The new built-in method M_QUERY moves + M_INVALID from 26 to 27, so modules that use + M_INVALID need to be recompiled. + ap_method_is_safe() and + ap_method_is_idempotent() classify built-in methods.
+
Core / HTTP module separation
A large amount of code has been moved out of the diff --git a/include/ap_mmn.h b/include/ap_mmn.h index ff852ea7058..163e7fdb4ee 100644 --- a/include/ap_mmn.h +++ b/include/ap_mmn.h @@ -747,14 +747,17 @@ * 20211221.36 (2.5.1-dev) Add ungrowable to struct proxy_balancer * 20211221.37 (2.5.1-dev) Add the optional function ap_authn_cache_store_env() * to mod_auth.h + * 20261031.0 (2.5.1-dev) Add M_QUERY (RFC 10008) to httpd.h, which moves + * M_INVALID from 26 to 27; add ap_method_is_safe() + * and ap_method_is_idempotent() to http_protocol.h */ #define MODULE_MAGIC_COOKIE 0x41503235UL /* "AP25" */ #ifndef MODULE_MAGIC_NUMBER_MAJOR -#define MODULE_MAGIC_NUMBER_MAJOR 20211221 +#define MODULE_MAGIC_NUMBER_MAJOR 20261031 #endif -#define MODULE_MAGIC_NUMBER_MINOR 37 /* 0...n */ +#define MODULE_MAGIC_NUMBER_MINOR 0 /* 0...n */ /** * Determine if the server's current MODULE_MAGIC_NUMBER is at least a diff --git a/include/http_protocol.h b/include/http_protocol.h index 2b509b341fe..5a0fa4c714c 100644 --- a/include/http_protocol.h +++ b/include/http_protocol.h @@ -810,6 +810,26 @@ AP_DECLARE(int) ap_method_number_of(const char *method); */ AP_DECLARE(const char *) ap_method_name_of(apr_pool_t *p, int methnum); +/** + * Determine whether a built-in method is "safe" in the sense of + * RFC 9110, Section 9.2.1 (GET, HEAD, OPTIONS, TRACE, and the read-only + * WebDAV methods PROPFIND and REPORT) or RFC 10008 (QUERY). + * Methods registered at runtime are never considered safe. + * @param methnum The method number (e.g. r->method_number) + * @return 1 if the method is safe, 0 otherwise + */ +AP_DECLARE(int) ap_method_is_safe(int methnum); + +/** + * Determine whether a built-in method is idempotent in the sense of + * RFC 9110, Section 9.2.2: all safe methods (see ap_method_is_safe()) + * plus PUT and DELETE. + * Methods registered at runtime are never considered idempotent. + * @param methnum The method number (e.g. r->method_number) + * @return 1 if the method is idempotent, 0 otherwise + */ +AP_DECLARE(int) ap_method_is_idempotent(int methnum); + /* Hooks */ /* diff --git a/include/httpd.h b/include/httpd.h index 8c9d24b6c6b..9e76e274ac0 100644 --- a/include/httpd.h +++ b/include/httpd.h @@ -623,13 +623,14 @@ AP_DECLARE(const char *) ap_get_server_built(void); #define M_MKACTIVITY 23 #define M_BASELINE_CONTROL 24 #define M_MERGE 25 +#define M_QUERY 26 /** RFC 10008: HTTP QUERY */ /* Additional methods must be registered by the implementor, we have only * room for 64 bit-wise methods available, so do not squander them (more of * the above methods should probably move here) */ /* #define M_BREW nn */ /** RFC 2324: HTCPCP/1.0 */ /* #define M_WHEN nn */ /** RFC 2324: HTCPCP/1.0 */ -#define M_INVALID 26 /** invalid method value terminates the +#define M_INVALID 27 /** invalid method value terminates the * listed ap_method_registry_init() */ diff --git a/modules/filters/mod_charset_lite.c b/modules/filters/mod_charset_lite.c index e6a67cc90c8..78bfc13363a 100644 --- a/modules/filters/mod_charset_lite.c +++ b/modules/filters/mod_charset_lite.c @@ -258,6 +258,7 @@ static int find_code_page(request_rec *r) switch (r->method_number) { case M_PUT: case M_POST: + case M_QUERY: /* Set up input translation. Note: A request body can be included * with the OPTIONS method, but for now we don't set up translation * of it. diff --git a/modules/filters/mod_reflector.c b/modules/filters/mod_reflector.c index 5979cb8f727..e0f7417629a 100644 --- a/modules/filters/mod_reflector.c +++ b/modules/filters/mod_reflector.c @@ -56,13 +56,13 @@ static int reflector_handler(request_rec * r) conf = (reflector_cfg *) ap_get_module_config(r->per_dir_config, &reflector_module); - ap_allow_methods(r, 1, "POST", "OPTIONS", NULL); + ap_allow_methods(r, 1, "POST", "QUERY", "OPTIONS", NULL); if (r->method_number == M_OPTIONS) { return ap_send_http_options(r); } - else if (r->method_number == M_POST) { + else if (r->method_number == M_POST || r->method_number == M_QUERY) { const char *content_length, *content_type; int seen_eos; diff --git a/modules/generators/mod_cgi.c b/modules/generators/mod_cgi.c index e81bb806b21..fbafeee6be5 100644 --- a/modules/generators/mod_cgi.c +++ b/modules/generators/mod_cgi.c @@ -244,7 +244,8 @@ static int log_script(request_rec *r, cgi_server_conf * conf, int ret, continue; apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val); } - if ((r->method_number == M_POST || r->method_number == M_PUT) && + if ((r->method_number == M_POST || r->method_number == M_PUT + || r->method_number == M_QUERY) && *dbuf) { apr_file_printf(f, "\n%s\n", dbuf); } diff --git a/modules/generators/mod_cgid.c b/modules/generators/mod_cgid.c index c4ea6ff43b1..fb9a7131ba6 100644 --- a/modules/generators/mod_cgid.c +++ b/modules/generators/mod_cgid.c @@ -1280,7 +1280,8 @@ static int log_script(request_rec *r, cgid_server_conf * conf, int ret, continue; apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val); } - if ((r->method_number == M_POST || r->method_number == M_PUT) + if ((r->method_number == M_POST || r->method_number == M_PUT + || r->method_number == M_QUERY) && *dbuf) { apr_file_printf(f, "\n%s\n", dbuf); } diff --git a/modules/http/http_protocol.c b/modules/http/http_protocol.c index d0fb88c37ae..b2ac6be396c 100644 --- a/modules/http/http_protocol.c +++ b/modules/http/http_protocol.c @@ -199,6 +199,12 @@ AP_IMPLEMENT_HOOK_VOID(insert_error_filter, (request_rec *r), (r)) */ #define METHOD_NUMBER_LAST 62 +/* GET, HEAD and QUERY (RFC 10008, Section 2.6) share the GET semantics + * of conditional requests: weak ETag comparison and 304 (Not Modified). + */ +#define IS_GET_OR_QUERY(r) ((r)->method_number == M_GET \ + || (r)->method_number == M_QUERY) + static int is_mpm_running(void) { int mpm_state = 0; @@ -432,9 +438,10 @@ AP_DECLARE(ap_condition_e) ap_condition_if_none_match(request_rec *r, /* See section 13.3.3 for rules on how to determine if two entities tags * match. The weak comparison function can only be used with GET or HEAD - * requests. + * requests, and with QUERY whose selected representation is defined + * like GET's (RFC 10008, Section 2.6). */ - if (r->method_number == M_GET) { + if (IS_GET_OR_QUERY(r)) { if ((etag = apr_table_get(headers, "ETag")) != NULL) { if (apr_table_get(r->headers_in, "Range")) { if (ap_find_etag_strong(r->pool, if_nonematch, etag)) { @@ -628,13 +635,14 @@ AP_DECLARE(int) ap_meets_conditions(request_rec *r) * AND the field value is "*" (meaning match anything) * OR our ETag matches any of the entity tags in that field, fail. * - * If the request method was GET or HEAD, failure means the server + * If the request method was GET, HEAD or QUERY, failure means the server * SHOULD respond with a 304 (Not Modified) response. * For all other request methods, failure means the server MUST * respond with a status of 412 (Precondition Failed). * - * GET or HEAD allow weak etag comparison, all other methods require - * strong comparison. We can only use weak if it's not a range request. + * GET, HEAD or QUERY allow weak etag comparison, all other methods + * require strong comparison. We can only use weak if it's not a range + * request. */ cond = ap_condition_if_none_match(r, r->headers_out); has_if_none_match = (AP_CONDITION_NONE != cond); @@ -642,7 +650,7 @@ AP_DECLARE(int) ap_meets_conditions(request_rec *r) not_modified = 0; } else if (cond >= AP_CONDITION_WEAK) { - if (r->method_number == M_GET) { + if (IS_GET_OR_QUERY(r)) { if (not_modified) { not_modified = 1; } @@ -653,7 +661,7 @@ AP_DECLARE(int) ap_meets_conditions(request_rec *r) } /* If a valid If-Modified-Since request-header field was given - * AND it is a GET or HEAD request + * AND it is a GET, HEAD or QUERY request * AND the requested resource has not been modified since the time * specified in this field, then the server MUST * respond with a status of 304 (Not Modified). @@ -670,7 +678,7 @@ AP_DECLARE(int) ap_meets_conditions(request_rec *r) not_modified = 0; } else if (cond >= AP_CONDITION_WEAK) { - if (r->method_number == M_GET) { + if (IS_GET_OR_QUERY(r)) { if (not_modified) { not_modified = 1; } @@ -762,6 +770,7 @@ AP_DECLARE(void) ap_method_registry_init(apr_pool_t *p) register_one_method(p, "MKACTIVITY", M_MKACTIVITY); register_one_method(p, "BASELINE-CONTROL", M_BASELINE_CONTROL); register_one_method(p, "MERGE", M_MERGE); + register_one_method(p, "QUERY", M_QUERY); } AP_DECLARE(int) ap_method_register(apr_pool_t *p, const char *methname) @@ -816,6 +825,32 @@ AP_DECLARE(int) ap_method_number_of(const char *method) return M_INVALID; } +AP_DECLARE(int) ap_method_is_safe(int methnum) +{ + switch (methnum) { + case M_GET: /* includes HEAD */ + case M_OPTIONS: + case M_TRACE: + case M_PROPFIND: + case M_REPORT: + case M_QUERY: + return 1; + default: + return 0; + } +} + +AP_DECLARE(int) ap_method_is_idempotent(int methnum) +{ + switch (methnum) { + case M_PUT: + case M_DELETE: + return 1; + default: + return ap_method_is_safe(methnum); + } +} + /* * Turn a known method number into a name. */ diff --git a/modules/lua/lua_request.c b/modules/lua/lua_request.c index b534c6bf705..b569d63369c 100644 --- a/modules/lua/lua_request.c +++ b/modules/lua/lua_request.c @@ -510,7 +510,8 @@ static int lua_ap_requestbody(lua_State *L) if (r) { apr_off_t size; int rc; - if (r->method_number != M_POST && r->method_number != M_PUT) + if (r->method_number != M_POST && r->method_number != M_PUT + && r->method_number != M_QUERY) return (0); if (!filename) { const char *data; diff --git a/modules/mappers/mod_dir.c b/modules/mappers/mod_dir.c index 53ecf0e533c..784ad0561a9 100644 --- a/modules/mappers/mod_dir.c +++ b/modules/mappers/mod_dir.c @@ -297,7 +297,8 @@ static int fixup_dir(request_rec *r) return HTTP_MOVED_PERMANENTLY; } - if (r->method_number != M_GET && r->method_number != M_POST) { + if (r->method_number != M_GET && r->method_number != M_POST + && r->method_number != M_QUERY) { return DECLINED; } diff --git a/modules/proxy/ajp_header.c b/modules/proxy/ajp_header.c index af2f27b2415..f1d5b13847e 100644 --- a/modules/proxy/ajp_header.c +++ b/modules/proxy/ajp_header.c @@ -164,6 +164,7 @@ static const unsigned char sc_for_req_method_table[] = { SC_M_MKACTIVITY, SC_M_BASELINE_CONTROL, SC_M_MERGE, + 0, /* M_QUERY, sent as SC_A_STORED_METHOD */ 0 /* M_INVALID */ }; diff --git a/modules/proxy/mod_proxy_ajp.c b/modules/proxy/mod_proxy_ajp.c index e269ae31d96..c5019f17cb6 100644 --- a/modules/proxy/mod_proxy_ajp.c +++ b/modules/proxy/mod_proxy_ajp.c @@ -119,28 +119,22 @@ static int proxy_ajp_canon(request_rec *r, char *url) static int is_idempotent(request_rec *r) { /* - * RFC2616 (9.1.2): GET, HEAD, PUT, DELETE, OPTIONS, TRACE are considered - * idempotent. Hint: HEAD requests use M_GET as method number as well. + * RFC 9110, Section 9.2.2: the safe methods (GET, HEAD, OPTIONS, TRACE, + * PROPFIND, REPORT and the QUERY of RFC 10008), PUT and DELETE are + * idempotent. Everything else is not considered idempotent. */ - switch (r->method_number) { - case M_GET: - case M_DELETE: - case M_PUT: - case M_OPTIONS: - case M_TRACE: - /* - * If the request has arguments it might have side-effects and thus - * it might be undesirable to resend it to a backend again - * automatically. - */ - if (r->args) { - return METHOD_IDEMPOTENT_WITH_ARGS; - } - return METHOD_IDEMPOTENT; - /* Everything else is not considered idempotent. */ - default: - return METHOD_NON_IDEMPOTENT; + if (!ap_method_is_idempotent(r->method_number)) { + return METHOD_NON_IDEMPOTENT; + } + /* + * If the request has arguments it might have side-effects and thus + * it might be undesirable to resend it to a backend again + * automatically. + */ + if (r->args) { + return METHOD_IDEMPOTENT_WITH_ARGS; } + return METHOD_IDEMPOTENT; } static apr_off_t get_content_length(request_rec * r) diff --git a/server/protocol.c b/server/protocol.c index 1986178d143..51e31926f44 100644 --- a/server/protocol.c +++ b/server/protocol.c @@ -1547,6 +1547,25 @@ AP_DECLARE(int) ap_post_read_request(request_rec *r) return HTTP_BAD_REQUEST; } + /* RFC 10008, Section 2: the content and its media type define a + * QUERY, so servers MUST fail a QUERY request without Content-Type. + * Forward proxy requests are left alone (the origin server decides), + * as are servers configured with "HttpProtocolOptions Unsafe". + */ + if (r->method_number == M_QUERY + && r->proxyreq != PROXYREQ_PROXY + && !apr_table_get(r->headers_in, "Content-Type")) { + core_server_config *conf; + + conf = ap_get_core_module_config(r->server->module_config); + if (conf->http_conformance != AP_HTTP_CONFORMANCE_UNSAFE) { + ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO() + "QUERY request without Content-Type: %s", + r->uri); + return HTTP_BAD_REQUEST; + } + } + return OK; } diff --git a/server/util_script.c b/server/util_script.c index 53a6f3a64ec..85d31d3ba31 100644 --- a/server/util_script.c +++ b/server/util_script.c @@ -572,7 +572,9 @@ AP_DECLARE(int) ap_scan_script_header_err_core_ex(request_rec *r, char *buffer, * ap_meets_conditions returns anything interesting. * That would be safer wrt HTTP, but would break CGI. */ - if ((cgi_status == HTTP_UNSET) && (r->method_number == M_GET)) { + if ((cgi_status == HTTP_UNSET) + && (r->method_number == M_GET + || r->method_number == M_QUERY)) { cond_status = ap_meets_conditions(r); } apr_table_overlap(r->err_headers_out, merge, diff --git a/test/modules/filters/env.py b/test/modules/filters/env.py index 16c6d8312f4..2496248db33 100644 --- a/test/modules/filters/env.py +++ b/test/modules/filters/env.py @@ -1,6 +1,7 @@ import inspect import logging import os +import subprocess from typing import List from pyhttpd.env import HttpdTestEnv, HttpdTestSetup @@ -16,7 +17,8 @@ def __init__(self, env: 'HttpdTestEnv'): self.add_source_dir(os.path.dirname(inspect.getfile(FiltersTestSetup))) self.add_modules(["substitute", "sed", "buffer", "ext_filter", "include"]) self.add_cgi_module() - self.add_optional_modules(["xml2enc", "proxy_html", "brotli", "deflate"]) + self.add_optional_modules(["xml2enc", "proxy_html", "brotli", "deflate", + "charset_lite"]) class FiltersTestEnv(HttpdTestEnv): @@ -47,3 +49,12 @@ def configtest(self, lines: List[str]) -> ExecResult: ] + lines) + '\n') return self.run([os.path.join(self.bin_dir, 'httpd'), '-t', '-f', conf_path]) + + @property + def has_charset_lite_module(self) -> bool: + """Whether mod_charset_lite was built, shared or static.""" + if self.has_shared_module("charset_lite"): + return True + p = subprocess.run([os.path.join(self.bin_dir, "httpd"), "-l"], + capture_output=True, text=True) + return "mod_charset_lite.c" in p.stdout diff --git a/test/modules/filters/htdocs/test1/cgi/hexbody.py b/test/modules/filters/htdocs/test1/cgi/hexbody.py new file mode 100644 index 00000000000..8ff81683641 --- /dev/null +++ b/test/modules/filters/htdocs/test1/cgi/hexbody.py @@ -0,0 +1,9 @@ +#!/usr/bin/env python3 +# Print the request body in hex, so a test of an input filter which +# translates the body sees its bytes whatever is done to the response. +import sys + +body = sys.stdin.buffer.read() +print("Content-Type: application/octet-stream") +print() +print(body.hex()) diff --git a/test/modules/filters/test_010_charset_lite.py b/test/modules/filters/test_010_charset_lite.py new file mode 100644 index 00000000000..66007c2f36f --- /dev/null +++ b/test/modules/filters/test_010_charset_lite.py @@ -0,0 +1,50 @@ +import os + +import pytest + +from pyhttpd.conf import HttpdConf + + +class TestCharsetLite: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env): + env.require(env.has_charset_lite_module, "mod_charset_lite not built", + dep="mod_charset_lite", + detected=f"not found in {env.libexec_dir}") + conf = HttpdConf(env, extras={ + f"test1.{env.http_tld}": """ + + AddHandler cgi-script .py + Options +ExecCGI + CharsetSourceEnc UTF-8 + CharsetDefault ISO-8859-1 + CharsetOptions TranslateAllMimeTypes + + """, + }) + conf.add_vhost_test1() + conf.install() + assert env.apache_restart() == 0 + + # The request body is translated from CharsetDefault to + # CharsetSourceEnc for the methods that carry content to a script, + # which includes QUERY (RFC 10008), and left alone for the others. + @pytest.mark.parametrize(["method", "translated"], [ + ["POST", True], + ["PUT", True], + ["QUERY", True], + ["DELETE", False], + ]) + def test_filters_010_01(self, env, method, translated): + latin1 = "caf\u00e9".encode("iso-8859-1") + fpath = os.path.join(env.gen_dir, "charset-lite-body") + with open(fpath, "wb") as fd: + fd.write(latin1) + r = env.curl_raw([env.mkurl("http", "test1", "/cgi/hexbody.py")], + options=["-X", method, "--data-binary", f"@{fpath}", + "-H", "Content-Type: text/plain"]) + assert r.exit_code == 0, f"{r}" + assert r.response["status"] == 200 + expected = "caf\u00e9".encode("utf-8") if translated else latin1 + assert r.response["body"].decode().strip() == expected.hex() diff --git a/test/modules/generators/test_001_cgid.py b/test/modules/generators/test_001_cgid.py index 728b6850286..e024413bab7 100644 --- a/test/modules/generators/test_001_cgid.py +++ b/test/modules/generators/test_001_cgid.py @@ -101,6 +101,25 @@ def test_generators_001_02_script_log(self, env): lognos=["AH01215", "AH10599"], matches=[r".*End of script output before headers: stderr_fail\.py"]) + def test_generators_001_15_script_log_query(self, env): + """ScriptLog records the content of a QUERY (RFC 10008) request + like that of a POST.""" + log = self.script_log(env) + if os.path.exists(log): + os.unlink(log) + r = env.curl_raw([env.mkurl("http", "cgi", "/stderr_fail.py")], + options=["-X", "QUERY", + "--data-binary", "query-body-marker", + "-H", "Content-Type: application/sql"]) + assert r.response["status"] == 500 + with open(log) as fd: + content = fd.read() + assert "%request\n" in content + assert "\nquery-body-marker\n" in content + env.httpd_error_log.ignore_recent( + lognos=["AH01215", "AH10599"], + matches=[r".*End of script output before headers: stderr_fail\.py"]) + def test_generators_001_03_timeout(self, env): """CGIDScriptTimeout gives 504 for a script which says nothing.""" start = time.time() diff --git a/test/modules/http1/env.py b/test/modules/http1/env.py index 91487830c74..a2ea7f8bb45 100644 --- a/test/modules/http1/env.py +++ b/test/modules/http1/env.py @@ -17,7 +17,7 @@ class H1TestSetup(HttpdTestSetup): def __init__(self, env: 'HttpdTestEnv'): super().__init__(env=env) self.add_source_dir(os.path.dirname(inspect.getfile(H1TestSetup))) - self.add_modules(["cgid", "autoindex", "ssl"]) + self.add_modules(["cgid", "autoindex", "ssl", "reflector"]) def make(self): super().make() diff --git a/test/modules/http1/htdocs/cgi/query.py b/test/modules/http1/htdocs/cgi/query.py new file mode 100755 index 00000000000..0e3259cc11d --- /dev/null +++ b/test/modules/http1/htdocs/cgi/query.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +# Echo a QUERY (RFC 10008) request back as JSON, with fixed validators +# so that conditional requests can be tested. +import json +import os +import sys + +length = int(os.getenv('CONTENT_LENGTH', '0') or '0') +body = sys.stdin.buffer.read(length) if length > 0 else b'' + +print("Content-Type: application/json") +print('ETag: "query-1"') +print("Last-Modified: Sun, 31 Aug 2025 08:44:00 GMT") +print() +print(json.dumps({ + "method": os.getenv('REQUEST_METHOD', ''), + "content_type": os.getenv('CONTENT_TYPE', ''), + "query_string": os.getenv('QUERY_STRING', ''), + "body": body.decode('utf-8', errors='replace'), +})) diff --git a/test/modules/http1/test_008_query.py b/test/modules/http1/test_008_query.py new file mode 100644 index 00000000000..5f76f1dd297 --- /dev/null +++ b/test/modules/http1/test_008_query.py @@ -0,0 +1,170 @@ +import socket + +import pytest + +from .env import H1Conf + + +def _query(env, path, body="q=foo&limit=10", ctype="application/x-www-form-urlencoded", + headers=None, method="QUERY", vhost="cgi"): + url = env.mkurl("https", vhost, path) + options = ["-X", method, "--data-binary", body] + # an empty value makes curl drop the header it would add by itself + options.extend(["-H", f"Content-Type: {ctype}" if ctype else "Content-Type:"]) + for h in (headers or []): + options.extend(["-H", h]) + return env.curl_raw([url], options=options) + + +class TestQuery: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env): + conf = H1Conf(env) + conf.add([ + f'', + " DirectoryIndex ../query.py", + "", + ]) + conf.add_vhost_cgi() + conf.start_vhost(domains=[f"test1.{env.http_tld}"], + port=env.https_port, doc_root="htdocs/test1") + conf.add([ + "", + " ", + " Require all denied", + " ", + "", + "", + " Require method GET QUERY", + "", + "", + " SetHandler reflector", + "", + ]) + conf.end_vhost() + conf.install() + assert env.apache_restart() == 0 + + # QUERY with content reaches a CGI handler unchanged + def test_h1_008_01(self, env): + r = _query(env, "/query.py?x=1", body="select=surname&limit=10") + assert r.exit_code == 0, f"{r}" + assert r.response["status"] == 200 + j = r.json + assert j["method"] == "QUERY" + assert j["content_type"] == "application/x-www-form-urlencoded" + assert j["query_string"] == "x=1" + assert j["body"] == "select=surname&limit=10" + + # QUERY without Content-Type MUST fail (RFC 10008, Section 2) + def test_h1_008_02(self, env): + r = _query(env, "/query.py", ctype=None) + assert r.exit_code == 0, f"{r}" + assert r.response["status"] == 400 + + # same, on a raw HTTP/1.1 connection: the 400 closes the connection + # like any other 400 to a malformed request + def test_h1_008_03(self, env): + req = (f"QUERY /query.py HTTP/1.1\r\n" + f"Host: cgi.{env.http_tld}\r\n" + f"Content-Length: 5\r\n" + f"\r\n" + f"hello") + with socket.create_connection(('localhost', int(env.http_port))) as sock: + sock.sendall(req.encode()) + resp = b"" + while True: + chunk = sock.recv(8192) + if not chunk: + break + resp += chunk + text = resp.decode(errors='replace') + assert text.startswith("HTTP/1.1 400 "), text + assert "Connection: close" in text, text + + # conditional QUERY gets a 304 like GET (RFC 10008, Section 2.6) + @pytest.mark.parametrize("cond", [ + 'If-None-Match: "query-1"', + 'If-None-Match: W/"query-1"', + 'If-Modified-Since: Sun, 31 Aug 2025 08:44:00 GMT', + ]) + def test_h1_008_04(self, env, cond): + r = _query(env, "/query.py", headers=[cond]) + assert r.exit_code == 0, f"{r}" + assert r.response["status"] == 304 + + # non-matching validators give the full result + @pytest.mark.parametrize("cond", [ + 'If-None-Match: "query-2"', + 'If-Modified-Since: Sat, 30 Aug 2025 08:44:00 GMT', + ]) + def test_h1_008_05(self, env, cond): + r = _query(env, "/query.py", headers=[cond]) + assert r.exit_code == 0, f"{r}" + assert r.response["status"] == 200 + assert r.json["method"] == "QUERY" + + # CGI output only gets the GET-style 304 for GET and QUERY, not POST + def test_h1_008_06(self, env): + r = _query(env, "/query.py", method="POST", + headers=['If-None-Match: "query-1"']) + assert r.exit_code == 0, f"{r}" + assert r.response["status"] == 200 + assert r.json["method"] == "POST" + + # a static resource does not implement QUERY + def test_h1_008_07(self, env): + r = _query(env, "/index.html", vhost="test1") + assert r.exit_code == 0, f"{r}" + assert r.response["status"] == 405 + allow = r.response["header"]["allow"] + assert "GET" in allow and "QUERY" not in allow + + # and Require method know the method + def test_h1_008_08(self, env): + r = _query(env, "/limit/index.html", vhost="test1") + assert r.response["status"] == 403 + r = env.curl_get(env.mkurl("https", "test1", "/limit/")) + assert r.response["status"] != 403 + r = _query(env, "/method/", vhost="test1", method="POST") + assert r.response["status"] == 403 + r = _query(env, "/method/", vhost="test1") + assert r.response["status"] != 403 + env.httpd_error_log.ignore_recent(lognos=["AH01630"]) + + # DirectoryIndex hands QUERY on a directory to the index script + def test_h1_008_09(self, env): + r = _query(env, "/files/", body="a=b") + assert r.exit_code == 0, f"{r}" + assert r.response["status"] == 200 + assert r.json["method"] == "QUERY" + assert r.json["body"] == "a=b" + + # mod_reflector reflects QUERY content + def test_h1_008_11(self, env): + r = _query(env, "/reflect", vhost="test1", body='{"q": 1}', + ctype="application/json") + assert r.exit_code == 0, f"{r}" + assert r.response["status"] == 200 + assert r.response["header"]["content-type"] == "application/json" + assert r.response["body"] == b'{"q": 1}' + + +class TestQueryUnsafe: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env): + conf = H1Conf(env) + conf.add("HttpProtocolOptions Unsafe") + conf.add_vhost_cgi() + conf.install() + assert env.apache_restart() == 0 + + # "HttpProtocolOptions Unsafe" lets QUERY without Content-Type through + def test_h1_008_10(self, env): + r = _query(env, "/query.py", ctype=None) + assert r.exit_code == 0, f"{r}" + assert r.response["status"] == 200 + assert r.json["method"] == "QUERY" + assert r.json["content_type"] == "" diff --git a/test/modules/http2/test_204_query.py b/test/modules/http2/test_204_query.py new file mode 100644 index 00000000000..c2d1ceb21a8 --- /dev/null +++ b/test/modules/http2/test_204_query.py @@ -0,0 +1,38 @@ +import pytest + +from .env import H2Conf, H2TestEnv + + +@pytest.mark.skipif(condition=H2TestEnv.is_unsupported(), reason="mod_http2 not supported here") +class TestQuery: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env): + conf = H2Conf(env) + conf.add_vhost_cgi(proxy_self=True, h2proxy_self=True).install() + assert env.apache_restart() == 0 + + def _query(self, env, path, body, ctype="application/jsonpath"): + url = env.mkurl("https", "cgi", path) + options = ["-X", "QUERY", "--data-binary", body, + "-H", f"Content-Type: {ctype}" if ctype else "Content-Type:"] + return env.curl_raw([url], options=options) + + # QUERY content reaches the CGI over HTTP/2 (RFC 10008) + @pytest.mark.parametrize("path", [ + "/echo.py", "/proxy/echo.py", "/h2proxy/echo.py", + ]) + def test_h2_204_01(self, env, path): + body = '$..[?@.status=="Rejected"]["doc-id"]' + r = self._query(env, path, body) + assert r.exit_code == 0, f"{r}" + assert r.response["protocol"] == "HTTP/2" + assert r.response["status"] == 200 + assert r.response["body"] == body.encode() + + # a QUERY without Content-Type fails on HTTP/2 as on HTTP/1.1 + def test_h2_204_02(self, env): + r = self._query(env, "/echo.py", "q=1", ctype=None) + assert r.exit_code == 0, f"{r}" + assert r.response["protocol"] == "HTTP/2" + assert r.response["status"] == 400 diff --git a/test/modules/lua/test_004_body.py b/test/modules/lua/test_004_body.py index c148564aa08..e7bb359c9bb 100644 --- a/test/modules/lua/test_004_body.py +++ b/test/modules/lua/test_004_body.py @@ -101,3 +101,25 @@ def test_lua_004_06_file_overwrite(self, env): self.post(env, "file") assert self.post(env, "fileover", b"abc") == \ f"3|nil|{hashlib.md5(b'abc').hexdigest()}" + + # r:requestbody() returns the body of the methods that carry content + # to an application, which includes QUERY (RFC 10008), and nothing + # for the others. + @pytest.mark.parametrize(["method", "has_body"], [ + ["POST", True], + ["PUT", True], + ["QUERY", True], + ["DELETE", False], + ]) + def test_lua_004_07_methods(self, env, method, has_body): + url = env.mkurl("http", "test1", "/lua/body.lua?read") + r = env.curl_raw([url], options=[ + "-X", method, "-H", "Content-Type: text/plain", + "--data-binary", "select=surname"]) + assert r.response["status"] == 200, r.response + length, digest, _ = r.response["body"].decode().split() + if has_body: + assert length == str(len("select=surname")) + assert digest == hashlib.md5(b"select=surname").hexdigest() + else: + assert (length, digest) == ("nil", "-") diff --git a/test/modules/proxy/test_08_query.py b/test/modules/proxy/test_08_query.py new file mode 100644 index 00000000000..f58c27fb123 --- /dev/null +++ b/test/modules/proxy/test_08_query.py @@ -0,0 +1,109 @@ +import time + +import pytest + +from pyhttpd.conf import HttpdConf +from .env import TCPFaker + + +class _HttpFaker(TCPFaker): + + def _make_response(self, data): + return (b"HTTP/1.1 200 OK\r\n" + b"Content-Type: text/csv\r\n" + b"Content-Length: 6\r\n" + b"Connection: close\r\n" + b"\r\n" + b"a,b,c\n") + + +def _ajp_packet(body): + return b"\x41\x42" + len(body).to_bytes(2, "big") + body + + +class _AjpFaker(TCPFaker): + + def _make_response(self, data): + # SEND_HEADERS 200 "OK" without headers, then END_RESPONSE + headers = (b"\x04" + b"\x00\xc8" + + len(b"OK").to_bytes(2, "big") + b"OK" + b"\x00" + + b"\x00\x00") + return _ajp_packet(headers) + _ajp_packet(b"\x05\x00") + + +def _wait_request(faker, timeout=5): + end = time.time() + timeout + while faker._request is None and time.time() < end: + time.sleep(0.05) + return faker._request + + +def _query(env, url, body, ctype="application/sql"): + return env.curl_raw([url], options=[ + "-X", "QUERY", "--data-binary", body, "-H", f"Content-Type: {ctype}", + ]) + + +class TestProxyQueryHttp: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env): + faker = _HttpFaker("127.0.0.1", env.http_port2) + faker.start() + conf = HttpdConf(env) + conf.start_vhost(domains=[f"test1.{env.http_tld}"], port=env.http_port) + conf.add([f"ProxyPass / http://127.0.0.1:{env.http_port2}/"]) + conf.end_vhost() + conf.install() + assert env.apache_restart() == 0 + yield faker + faker.stop() + + # mod_proxy_http forwards method, Content-Type and content + def test_proxy_008_01(self, env, _class_scope): + _class_scope._request = None + body = "SELECT * FROM rfc WHERE year > 2020" + r = _query(env, env.mkurl("http", "test1", "/rfc-index?x=1"), body) + assert r.exit_code == 0, f"{r}" + assert r.response["status"] == 200 + assert r.response["body"] == b"a,b,c\n" + req = _wait_request(_class_scope) + assert req is not None + head, _, content = req.partition(b"\r\n\r\n") + assert head.startswith(b"QUERY /rfc-index?x=1 HTTP/1.1\r\n"), req + assert b"\r\nContent-Type: application/sql" in head, req + assert content == body.encode(), req + + +class TestProxyQueryAjp: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env): + env.require(env.has_shared_module("proxy_ajp"), "mod_proxy_ajp not available", + dep="mod_proxy_ajp", + detected=f"no mod_proxy_ajp.so in {env.libexec_dir}") + faker = _AjpFaker("127.0.0.1", env.http_port2) + faker.start() + conf = HttpdConf(env) + conf.start_vhost(domains=[f"test1.{env.http_tld}"], port=env.http_port) + conf.add([f"ProxyPass / ajp://127.0.0.1:{env.http_port2}/"]) + conf.end_vhost() + conf.install() + assert env.apache_restart() == 0 + yield faker + faker.stop() + + # AJP13 has no code for QUERY: it is sent as a stored method attribute + def test_proxy_008_02(self, env, _class_scope): + _class_scope._request = None + r = _query(env, env.mkurl("http", "test1", "/"), "q=1") + assert r.exit_code == 0, f"{r}" + assert r.response["status"] == 200 + req = _wait_request(_class_scope) + assert req is not None + # 0x12 0x34 magic, length, FORWARD_REQUEST (2), method + assert req[0:2] == b"\x12\x34", req + assert req[4] == 0x02, req + assert req[5] == 0xff, req + # SC_A_STORED_METHOD (13) followed by the AJP string "QUERY" + assert b"\x0d\x00\x05QUERY\x00" in req, req