From 362fe3935ccf4cb9aeb5e52010014d6d22d88460 Mon Sep 17 00:00:00 2001 From: Dmitry Volyntsev Date: Fri, 26 Apr 2024 16:48:17 -0700 Subject: [PATCH] Fetch: fixed request Host header when the port is non-standard. This fixes #707 issue on Github. --- nginx/ngx_js_fetch.c | 5 +++ nginx/t/js_fetch_resolver.t | 69 +++++++++++++++++++++++++++++++++---- 2 files changed, 67 insertions(+), 7 deletions(-) diff --git a/nginx/ngx_js_fetch.c b/nginx/ngx_js_fetch.c index d943f73c..b95f6d55 100644 --- a/nginx/ngx_js_fetch.c +++ b/nginx/ngx_js_fetch.c @@ -786,6 +786,11 @@ ngx_js_ext_fetch(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, if (!has_host) { njs_chb_append_literal(&http->chain, "Host: "); njs_chb_append(&http->chain, u.host.data, u.host.len); + + if (!u.no_port) { + njs_chb_sprintf(&http->chain, 32, ":%d", u.port); + } + njs_chb_append_literal(&http->chain, CRLF); } diff --git a/nginx/t/js_fetch_resolver.t b/nginx/t/js_fetch_resolver.t index 8b0dc450..8fb6b66f 100644 --- a/nginx/t/js_fetch_resolver.t +++ b/nginx/t/js_fetch_resolver.t @@ -65,6 +65,23 @@ http { location /loc { js_content test.loc; } + + location /host { + return 200 8080:$http_host; + } + } + + server { + listen 127.0.0.1:8081; + server_name aaa; + + location /loc { + js_content test.loc; + } + + location /host { + return 200 8081:$http_host; + } } server { @@ -80,19 +97,29 @@ http { EOF my $p0 = port(8080); +my $p1 = port(8081); $t->write_file('test.js', < reply.text()) - .then(body => r.return(200, body)) - .catch(e => r.return(501, e.message)) + } catch (e) { + r.return(501, e.message); + } } function str(v) { return v ? v : ''}; @@ -109,7 +136,7 @@ $t->write_file('test.js', <try_run('no njs.fetch')->plan(3); +$t->try_run('no njs.fetch')->plan(5); $t->run_daemon(\&dns_daemon, port(8981), $t); $t->waitforfile($t->testdir . '/' . port(8981)); @@ -121,6 +148,34 @@ like(http_get('/dns?domain=many'), qr/many:GET:::$/s, 'fetch dns many'); like(http_get('/dns?domain=unknown'), qr/"unknown" could not be resolved/s, 'fetch dns unknown'); +TODO: { +local $TODO = 'not yet' unless has_version('0.8.5'); + +like(http_get('/dns?domain=aaa&port=p0&loc=host'), qr/8080:aaa:$p0$/s, + 'fetch aaa:8080'); +like(http_get('/dns?domain=aaa&port=p1&loc=host'), qr/8081:aaa:$p1$/s, + 'fetch aaa:8081'); +} + +############################################################################### + +sub has_version { + my $need = shift; + + http_get('/njs') =~ /^([.0-9]+)$/m; + + my @v = split(/\./, $1); + my ($n, $v); + + for $n (split(/\./, $need)) { + $v = shift @v || 0; + return 0 if $n > $v; + return 1 if $v > $n; + } + + return 1; +} + ############################################################################### sub reply_handler { -- 2.47.3