Skip to content

ngx_mruby v2.7.1

Choose a tag to compare

@matsumotory matsumotory released this 19 Oct 05:11
ce5eb11

Behavior changes: read before upgrading

ngx_mruby 2.7.1 fixes the issues described in the security advisory GHSA-h7fw-wf49-8rv5.

ngx_mruby 2.7.1は、セキュリティアドバイザリGHSA-h7fw-wf49-8rv5に書いてある問題を直しました。

If your build, configuration or scripts use Read
Redis and the default build_config.rb 1
mruby_output_body_filter*, mruby_output_header_filter* or Nginx::Filter 2
raise after Nginx.rputs or Nginx.echo 3
Nginx::Async or Fiber.yield in a log handler or an output filter 4
Nginx::Async.sleep or Nginx::Async::HTTP.sub_request in a handler that raises or calls Nginx.redirect after it resumes, or sub_request to a location that sleeps 5
mruby_enable_read_request_body on 6
Nginx::SSL or mruby_ssl_handshake_handler* 7
request methods or Nginx.log in mruby_init*, mruby_init_worker*, mruby_exit_worker*, mruby_server_context_handler_code or the handshake handler; Nginx::Server#add_listener or Nginx::Stream.add_listener; the stream init, init worker, exit worker or server context code 8
mruby_set* and Nginx::Async.sleep in a later handler of the same request 9
a configuration without an http {} block 10
mruby_output_header_filter* and mruby_output_body_filter* in one location, with Nginx.rputs or Nginx.echo in the body filter 11
a handler that answers a request with a body (POST, PUT) with Nginx.rputs or Nginx.echo without reading the body 12
mruby_content_handler* that can end without output, or log monitoring that matches response body is empty 13
mruby_enable_read_request_body on with a post-read or access handler, and mruby_log_handler* or an mruby output filter for the same request 14

1. Redis is no longer in the default build

  • Before: build_config.rb included matsumotory/mruby-redis, so a binary
    built with the default configuration had the Redis class.
  • Now: that line is commented out (#528), because the gem clones its
    hiredis dependency from an unpinned branch, which broke the build. A binary
    built with the default build_config.rb has no Redis class, and code that
    refers to it raises NameError (uninitialized constant Redis).
  • Why it changed:
    • The reason: except on macOS, the build of mruby-redis clones hiredis from
      the head of its default branch, so a change there could break every build
      made with the default build_config.rb; the comment that
      #528 added to build_config.rb records such a failure of CI
      under -Werror.
    • Why the old behavior could not be kept: keeping the gem in the default
      list would have left every default build open to such a failure. The
      default build has to succeed, and build_config.rb cannot pin hiredis,
      because mruby-redis clones it in its own build script, so the gem cannot
      stay in the default list until mruby-redis pins hiredis.
    • What the documentation promised: the 2.7.0 documentation listed
      mruby-redis among "the default mrbgems"
      (docs/install of 2.7.0) and Redis among
      the classes that can be used "with default build configuration"
      (built-in mrbgems of 2.7.0), so it
      described the old behavior. Choosing the mrbgems in build_config.rb is
      the documented way to build ngx_mruby with extra gems (docs/install), and
      it is how you keep Redis.
  • Affected: scripts that use Redis, such as the examples in the README and
    in docs/use_case, and users of the bundled auto-ssl mrbgem, whose client
    takes a Redis connection. A build with your own build_config.rb is not
    affected.
  • What to do: if you use Redis, uncomment
    conf.gem github: 'matsumotory/mruby-redis' in build_config.rb before you
    build. The build of that gem can fail while hiredis has the problem that #528
    describes.

2. Output filters: response length and Nginx::Filter

This entry has four parts.

The response length follows the body filter.

  • Before: when an mruby handler, such as mruby_content_handler*, wrote the
    response body with Nginx.rputs or Nginx.echo and
    mruby_output_body_filter* replaced it with Nginx::Filter#body= or
    #output, the response kept the length of the Nginx.rputs output. A longer
    replacement body was cut to that length, and a shorter one was padded to it
    with bytes that were not part of the response. When the body filter itself
    called Nginx.rputs or Nginx.echo, which the documentation has never
    allowed there, Content-Length was the length of the response before the
    filter plus the length of that output, and the output itself was not sent.
    These responses were corrupted, and nothing should depend on them; the
    repository's own test of this case expected the cut response, and its
    expectation changes with this release. This part is about locations without
    an mruby header filter; for locations with one, see the fourth part.
  • Now: the body is exactly the output of the body filter, and
    Content-Length is its length. What the body filter writes with
    Nginx.rputs or Nginx.echo is neither sent nor counted.
location /filter/output_rputs_origin {
    mruby_content_handler_code 'Nginx.rputs "origin"';
    mruby_output_body_filter_code '
        f = Nginx::Filter.new
        f.output "[#{f.body}] and more"
    ';
}
Version Content-Length Body
2.7.0 6 [origi
2.7.1 17 [origin] and more
  • Why it changed:
    • The defect: ngx_mruby sends as many bytes of the body filter's buffer as
      the length that it keeps for the body, and sets Content-Length to the
      same number. In 2.7.0 that length came from the Content-Length that
      Nginx.rputs had counted, and the buffer from the body filter, so the two
      disagreed whenever the filter changed the length: a longer body was cut,
      and after a shorter one ngx_mruby sent bytes from beyond the end of the
      new body, memory that was not part of the response.
    • Why the old behavior could not be kept: the length and the buffer must
      agree, and the buffer is the filter's output, so the length has to follow
      the output; keeping the old length would mean keeping the cut or the read
      past the buffer.
    • What the documentation promised: the response is now what
      Nginx::Filter#body= is documented to do ("Sets the string to the
      response body"), as it already was for every other origin. The same
      section of the 2.7.0 documentation
      (Nginx::Filter Class) says "You can NOT use
      Nginx.rputs and Nginx.echo in the output body handlers".
  • Affected: locations whose body filter changes the length of a body
    written with Nginx.rputs or Nginx.echo, and body filters that call
    Nginx.rputs or Nginx.echo themselves, whatever the origin. A body filter
    that keeps the length and does not call them sees no change. Neither does a
    body filter on a response from a file, return, proxy_pass or another
    content handler: there the length already followed the filter's output.
  • What to do: nothing, unless a client or a test expected the cut response.
    Remove Nginx.rputs and Nginx.echo from body filters: what they write there
    is not sent.
  • Tests: port 18112 (test/t/cases/filter_connection.rb).

Nginx::Filter#body before the body is read.

  • Before: in mruby_output_header_filter*, where the body has not been read
    yet, Nginx::Filter#body returned a string as long as Content-Length whose
    bytes were not the response body. When the length was unknown, or 10485760
    bytes (10 MiB) or more, it raised ArgumentError instead.
  • Now: it returns an empty string there, as it already did in a content
    handler.
  • Why it changed:
    • The defect: in a header filter the body has not been read yet, and 2.7.0
      returned a string as long as Content-Length whose bytes were not the
      response body, or raised ArgumentError, as "Before" says.
    • Why the old behavior could not be kept: there is no body to return at
      that point, so the only correct result is an empty string; the length is
      available from $sent_http_content_length.
    • What the documentation promised: the documentation has always described
      Nginx::Filter as a class for the output body filters ("designed to be
      used in the output body handlers",
      Nginx::Filter Class of 2.7.0).
  • Affected: header filters that read f.body, for example its size to
    learn the response length.
  • What to do: read the length with
    Nginx::Var.new.sent_http_content_length (a String, or nil when the length
    is unknown), and read the body in mruby_output_body_filter*.
  • Tests: port 18080 (test/t/ngx_mruby.rb).

Nginx::Filter#body= and #output only in a body filter.

  • Before: they could be called anywhere. When a handler other than a body
    filter called them in a location that also had a body filter, the worker
    crashed as soon as that body filter read a response that was not empty.
    Without a body filter in the location, the call had no effect on the
    response.
  • Now: outside mruby_output_body_filter* they raise RuntimeError
    (Nginx::Filter#body= can only be used in an output body filter), which
    ends the handler like any other exception.
  • Why it changed:
    • The defect: a body set with Nginx::Filter#body= or #output outside a
      body filter made the worker crash when a body filter of the location read
      a response that was not empty, and had no effect without a body filter,
      as "Before" says.
    • Why the old behavior could not be kept: 2.x keeps one buffer for the body
      that the body filter reads and sends and for the body that
      Nginx::Filter#body= sets, and a body set outside a body filter was never
      supported, so 2.7.1 refuses the call instead of adding a second buffer.
    • What the documentation promised: the documentation has always said that
      Nginx::Filter does not work in other handlers ("It doesn't work in other
      handlers like mruby_content_handler_code",
      Nginx::Filter Class of 2.7.0).
  • Affected: header filters and other handlers that call body= or output.
  • What to do: set the body in mruby_output_body_filter*.
  • Tests: port 18080 (test/t/ngx_mruby.rb).

With an mruby header filter, the header waits for the body filter.

  • Before: in a location with mruby_output_header_filter* and
    mruby_output_body_filter*, the header went out as soon as the header
    filter's code had run, with the Content-Length of the response before the
    body filter. A body filter that made the body longer then sent more bytes
    than Content-Length announced, and one that made it shorter sent fewer.
    With an Nginx.rputs handler as the origin, such a location did not answer
    at all (see "Fixes").
  • Now: the header waits until the body filter has run, as it already did
    in a location with only a body filter, and goes out with the length of the
    body filter's output and with the changes that the header filter made. The
    header filter's code still runs before the body filter's code. A response
    without a known length is passed on without the body filter, as before.
  • Why it changed:
    • The defect: sending the header first committed the response to a
      Content-Length that the body filter then changed, and a client that
      reads a response by its Content-Length cannot read a body of another
      length correctly.
    • Why the old behavior could not be kept: the body filter decides the
      length of the body, so the header can carry the right Content-Length
      only after the body filter has run. A location with only a body filter
      already held the header back for this reason.
    • What the documentation promised: the documentation did not say when the
      header is sent in a location that has both filters. It says that
      Nginx::Filter#body= "Sets the string to the response body"
      (Nginx::Filter Class of 2.7.0).
  • Affected: locations with both an mruby header filter and an mruby body
    filter whose body filter changes the length of the body.
  • What to do: nothing.
  • Tests: port 18150 (test/t/cases/header_and_body_filter.rb, with a file
    and with an Nginx.rputs handler as the origin).

3. An exception after Nginx.rputs answers 500

  • Before: a post-read, server rewrite, rewrite, access or content handler
    that wrote output with Nginx.rputs or Nginx.echo and then raised an
    exception (without waiting in Nginx::Async first) answered 200 with the
    output written so far. In an access or post-read handler, nginx then went on
    with the later phases, so the location's content handler ran as well and its
    output followed.
  • Now: the request gets nginx's 500 page, the output is dropped, and the
    later phases do not run. This is what a handler that raises without output
    already got, and what a handler that raises after Nginx::Async gets (entry
    5).
    • mruby_set*: in 2.7.0 the output was sent as the response, and the
      variable got a value that the handler had not set. Now the output is
      dropped, the variable is an empty string, as for a handler that returns
      nil (also when an earlier directive of the location gave it a value), the
      request goes on, and the Content-Length of the response does not count
      the dropped output. This is for an exception before the handler waits in
      Nginx::Async.sleep or Nginx::Async::HTTP.sub_request. After
      Nginx::Async.sleep the request does not go on: it gets nginx's 500 page
      without the output (2.7.0 sent the output as the response, with 200).
      After Nginx::Async::HTTP.sub_request nginx goes on with the content
      phase without waiting for the variable, so the 500 that follows the
      exception cannot be sent and the client gets no response (entry 5).
    • Output header filters: an exception there already gave the response status
      500 with the body of the origin. A header filter that called Nginx.rputs
      or Nginx.echo crashed the worker in 2.7.0 (see "Fixes"); when it raises
      afterwards, its output is now dropped, and Content-Length is the length
      of the origin's body. Only the header filter's own output is dropped: when
      the origin is an mruby content handler that writes with Nginx.rputs or
      Nginx.echo, the response has that handler's output and its
      Content-Length, also when the header filter raises without output,
      which is what 2.7.0 sent in that case.
    • Log handlers and output body filters: the output is no longer sent after an
      exception.
  • Why it changed:
    • The defect: after the exception ngx_mruby logged mrb_run failed: return 500 HTTP status code to client and set the status to 500, and then the
      output path reset the status and sent the partial output with 200, so a
      failed handler was reported to the client as a success. In an access or
      post-read handler that path also returned the value that nginx reads as
      "go on", so an access check that failed with an exception let the request
      through.
    • Why the old behavior could not be kept: an exception has to end the
      handler with an error status, or the access decision is wrong, and the
      output path cannot send 200 and stop the phase at the same time, so the
      output is dropped. The client now gets the 500 that error.log has always
      announced, the same as after an exception without output or after
      Nginx::Async. An mruby_set* handler does not answer the request, so
      the request goes on after its exception: the dropped output must then not
      count in the length of the response that follows, and the variable needs
      a defined value, where 2.7.0 let nginx store whatever value its script
      engine held at that point.
    • What the documentation promised: the documentation said nothing about a
      handler that raises an exception. It shows a content handler that writes
      output, calls Nginx.return Nginx::HTTP_OK and leaves with return
      (Nginx.return of 2.7.0), and that answers 200 in 2.7.0 and in
      2.7.1, as "What to do" shows.
  • Affected: scripts that use raise to stop a handler after writing
    output, access checks that write a message and then raise, and mruby_set*
    handlers that write output and then raise.
  • What to do: keep raise for errors. To end a content handler early with
    its output, end it without an exception:
# 2.7.0: 200 "under maintenance"   2.7.1: 500
Nginx.rputs "under maintenance"
raise "stop"
# 2.7.0 and 2.7.1: 200 "under maintenance"
Nginx.rputs "under maintenance"
Nginx.return Nginx::HTTP_OK
return   # leaves the handler; omit it when nothing follows

Nginx.return with a status other than 200 makes nginx send its own page for
that status without the Nginx.rputs output, as in 2.7.0. Do not write output
in an access or post-read handler: it is sent as the response when the handler
ends, and with Nginx::HTTP_OK or without a status nginx then goes on with the
later phases, whose output follows the response beyond its Content-Length, in
2.7.0 as in 2.7.1 (see "Known limitations"). To stop the request there, return
an error status such as Nginx.return Nginx::HTTP_FORBIDDEN.

  • Not changed by this release: a handler that called Nginx.return,
    Nginx.send_header or Nginx.status_code= after Nginx.rputs and then
    raised already got 500. A handler that called Nginx.redirect to a local URI
    before it raised still ends with the response of the redirect target.
  • Tests: port 18143 (test/t/cases/sync_exception.rb).

4. Nginx::Async raises in log handlers and output filters

  • Before: Nginx::Async.sleep in mruby_log_handler* left a timer on a
    request that nginx was already freeing, and the worker could crash when it
    expired. Nginx::Async::HTTP.sub_request there started a subrequest. In
    mruby_output_header_filter* and mruby_output_body_filter*,
    Nginx::Async.sleep stopped the filter at that point: the response went out
    unfiltered with the status of the origin (200 in the tested configurations),
    and the code after the sleep did not run, because the request ended before
    the timer expired. sub_request in a header filter started a subrequest. A
    direct Fiber.yield in these handlers stopped the handler without a message.
  • Now: both methods raise RuntimeError there, for example
    Nginx::Async.sleep is not available in a log handler (also ... in a header filter and ... in a body filter), before they arm a timer or start a
    subrequest. The exception is handled like any other: error.log gets an
    [error] line, and in a filter the response gets status 500 (with the
    unfiltered body in the tested configurations). In a log handler the response
    has already been sent. A direct Fiber.yield there logs ... yielded its fiber, but nginx cannot resume it there and, in a filter, sets status 500.
  • Why it changed:
    • The defect: nginx runs the log phase while it frees the request, after
      the request cleanups and right before the request's memory is released,
      so a timer armed there fired on freed memory and resumed the handler with
      a request that no longer existed. Output filters run inside
      ngx_http_send_header and ngx_http_output_filter, which return to their
      caller at once, so a handler that yields there just stops and its
      filtering is skipped; if a timer or a subrequest resumes it later, the
      response has already gone out, and a direct Fiber.yield is never resumed
      (#551).
    • Why the old behavior could not be kept: nginx has no point in these
      places at which resuming a handler could still change the response, so
      the call has to fail before it arms a timer or starts a subrequest.
    • What the documentation promised: the documentation has always listed
      where Nginx::Async works (the set, rewrite and access handlers); log
      handlers and filters were never among them
      (Nginx::Async Class of 2.7.0).
  • Affected: log handlers and output filters that call Nginx::Async.sleep,
    Nginx::Async::HTTP.sub_request or Fiber.yield.
  • What to do: do the waiting in a rewrite or access handler (or
    mruby_set_code), and hand the result to the filter or the log handler in an
    nginx variable.
  • Not changed by this release: mruby_set* and the post-read, server
    rewrite, rewrite, access and content handlers can still use both methods
    (for the content handler, see "Known limitations").
  • Tests: ports 18129 (test/t/cases/async_sleep_in_log.rb) and 18131
    (test/t/cases/async_sleep_in_output_filter.rb).

5. An exception after Nginx::Async answers 500

This entry concerns a handler that Nginx::Async.sleep or
Nginx::Async::HTTP.sub_request has resumed: when it raises, and when it calls
Nginx.redirect and then raises or calls Nginx.return; and sub_request to a
location that sleeps (#550).

  • Before:
    • Without output, nginx closed the connection without a response.
    • After Nginx.rputs, the client got 200 with the output written so far.
    • After a status had been set, for example with Nginx.return 503, the
      client got that status. When a handler of the request had called
      Nginx.return Nginx::DECLINED before (for example a server-level handler),
      nginx went on with the next phase, for example served the file with 200.
    • The next request on the same worker that ran any mruby handler failed with
      500, and error.log logged the earlier exception again.
  • Now: the request gets nginx's 500 page and the output is dropped. The
    next request is not affected.
    • When the response had already started, the 500 cannot be sent: nginx logs
      header already sent and ends the request, and the client keeps what was
      sent before. When Nginx.redirect to a local URI followed
      Nginx::Async.sleep, that is the redirect target's response. In two
      cases measured for #550 the client now gets no response at all, where
      2.7.0 sent one: Nginx.redirect after Nginx::Async::HTTP.sub_request
      (2.7.0 sent the redirect target's response and then kept the connection
      open until the client closed it), and a mruby_set_code that raises after
      sub_request (nginx does not wait for the variable before the content
      phase; 2.7.0 sent 200 with the content handler's output).
    • After Nginx.redirect followed by an exception or by Nginx.return in a
      resumed handler, nginx closes the connection right after the redirect
      target's response. On an HTTP/1.1 keep-alive connection, a request
      pipelined behind it gets no response, and the client has to send it again
      on a new connection. 2.7.0 kept the connection open, but the pipelined
      request did not get its own response either: after an exception it got a
      500 page caused by the exception that the worker kept (see the last point
      of "Before" above), and after Nginx.return it got nothing until the
      client or a timeout closed the connection.
    • Nginx::Async::HTTP.sub_request to a location whose handler waits in
      Nginx::Async.sleep now completes. 2.7.0 sent nothing until the client or
      send_timeout ended the request. When that location raises,
      Nginx::Async::HTTP.last_response.status is 0.
  • Why it changed:
    • The defect: after an exception in a resumed handler, ngx_mruby logged
      return 500 HTTP status code to client and then replaced the 500 with the
      status the handler had before the exception: 0 (no response), 200 with the
      partial output, or a value such as Nginx::DECLINED that let nginx go on
      with the next phase. The exception also stayed in the mruby state that all
      requests of the worker share, so the next request failed with it. In
      2.7.0, after Nginx.redirect and then Nginx.return with a status, the
      request and its connection stayed open until the client or a timeout ended
      them (#550).
    • Why the old behavior could not be kept: that state must be cleared after
      an exception, or the next request on the worker fails, and the status must
      stay an error, or nginx treats the failed handler as a success. Running
      the requests that nginx posted while it finished the request is how nginx
      completes a request that is finished from a timer. In 2.7.1 the 500 (or
      the status) reaches nginx after the redirect target's response has been
      sent, so nginx can only end the request by closing the connection, and
      running the posted requests does that at once; that is why a keep-alive
      connection is now closed after the redirect target's response. The client
      now gets the 500 that error.log announces, as after an exception in a
      handler that did not wait.
    • What the documentation promised: the README of 2.7.0 says that the server
      process frees "the exception flag" of the mruby state that the scripts
      share, to "extend safety by preventing interference between each script"
      (Abstract); the next request that failed with the
      exception of an earlier one is such interference. The documentation said
      nothing about an exception in a handler that Nginx::Async had resumed,
      or about Nginx.redirect in such a handler. It lists the set, rewrite and
      access handlers as the places where Nginx::Async.sleep and
      Nginx::Async::HTTP.sub_request work
      (Nginx::Async Class of 2.7.0).
  • Affected: handlers that use Nginx::Async and can raise afterwards,
    clients that relied on the empty reply or on the status set before the
    exception, mruby_set_code handlers that use sub_request, and clients that
    pipeline requests on a keep-alive connection to a location that calls
    Nginx.redirect in a resumed handler and then raises or calls
    Nginx.return.
  • What to do: if a handler should answer something other than 500, rescue
    the exception inside the handler and set the status there.
  • Tests: ports 18130 (test/t/cases/async_exception_state.rb) and 18124
    (test/t/cases/async_subrequest_raise.rb).

6. mruby_enable_read_request_body: which handlers wait for the whole body

With mruby_enable_read_request_body on, ngx_mruby reads the request body
before it runs the code of a handler. This entry has two parts: the handlers
that can wait for a body that is not complete yet, and those that cannot.

Post-read, server rewrite, rewrite, access and content handlers wait.

  • Before: a mruby_server_rewrite_handler*, mruby_rewrite_handler* or
    mruby_content_handler* whose request body had not fully arrived when the
    handler started never ran. The client got no response, and nginx did not end
    the request when the client closed the connection or client_body_timeout
    expired. A body that arrives in more than one read, from a large upload or a
    slow client, was enough. Post-read and access handlers waited for the body
    and ran with it, but after such a wait a later phase handler that waits for a
    subrequest, such as auth_request, was never resumed: again the client got
    no response, and the connection stayed open after the client had closed it.
  • Now: the handler runs once nginx has read the whole body, and the
    request then goes on with the later phases, including a phase handler that
    waits for a subrequest, such as auth_request. On a keep-alive connection
    the next request is answered as usual, and an exception in the handler
    answers 500. If the client closes the connection first, nginx logs client prematurely closed connection and ends the request; when
    client_body_timeout expires, nginx closes the connection without a response,
    and the access log records 408. The handler does not run in either case
    (for the log handler and the filters of such a request, see entry 14).
  • Why it changed:
    • The defect: while the body was incomplete, ngx_mruby returned
      NGX_AGAIN, which nginx's rewrite and content phases read as "finished":
      nginx stopped reading the body, removed client_body_timeout and never ran
      the handler again, so the client got no answer, and the request and its
      connection stayed open after the client had left, until the worker exited.
      After a post-read or access handler had waited for the body, ngx_mruby ran
      the phases again with the write event handler that nginx sets while it
      reads a body, one that does nothing, and nginx resumes a phase handler that
      waits for a subrequest, such as auth_request, through that event
      handler, so that handler was never resumed.
    • Why the old behavior could not be kept: these phases leave a request
      waiting only when the handler returns NGX_DONE, and no return value both
      ends the request and keeps reading the body, so the handler has to wait;
      ngx_mruby runs the phases again when the body is complete. A phase handler
      that waits for a subrequest is resumed only through the write event
      handler, so ngx_mruby now sets it back before it runs the phases again, as
      nginx's mirror module does.
    • What the documentation promised: the handler now gets the body, which is
      what the directive is documented to do ("reads a HTTP request body before
      calling mruby code"). The 2.7.0 documentation of the directive
      (mruby_enable_read_request_body) also says that "a request
      body is not always read when invoking a handler like
      mruby_content_handler" and that "The directive force to read the request
      body".
  • Affected: configurations that use the directive with server rewrite,
    rewrite or content handlers, and with post-read or access handlers that are
    followed by auth_request or another phase handler that waits for a
    subrequest.
  • What to do: nothing.
  • Tests: ports 18144 (the five kinds of handler, keep-alive,
    client_body_timeout and an exception after the body) and 18147
    (auth_request after a rewrite and an access handler), in
    test/t/cases/request_body_later.rb.

mruby_set*, log handlers and output filters do not wait.

  • Before: these handlers started to read the body before their code ran,
    like the others. When nginx could read the whole body at once, for example
    because all of it had already arrived, the code ran with it. Otherwise the
    code did not run at that point (the variable of mruby_set* got a value that
    the handler had not set), and the body read that ngx_mruby had started stayed
    behind and, when it completed, ran the phases of the request again from
    wherever the request was then. With nginx 1.31.6 this happened to every
    HTTP/2 request whose body no earlier handler had read, because nginx reads
    such a body through events. In the tested configurations, with
    mruby_set_code and a body that arrived in two parts:
    • an mruby content handler in the same location ran twice and answered with
      the first part of the body only;
    • with proxy_pass, the upstream server got only the part that had arrived.
      When the upstream server waited for the rest, the client got no response;
      when it did not, the client got the response, but nginx did not close the
      HTTP/1.0 connection;
    • a connection stayed open after its client had closed it.
  • Now: these handlers read the body only when the read completes at once:
    when an earlier handler or a module has read the body, when the request has
    no body, or, for HTTP/1.x with Content-Length, when the whole body is in the
    buffer that nginx read the request headers into (client_header_buffer_size,
    1k by default, or the buffer of large_client_header_buffers that the
    headers needed). Otherwise the code runs at once without the body:
    Nginx::Request#body returns nil, and error.log gets one line at the
    info level that ends with the request body is not complete and an mruby_set handler cannot wait for it, so it runs without the body (or a log handler, a header filter, a body filter). A chunked body, an HTTP/2
    or HTTP/3 body, and a body of which only a part is in that buffer count as
    not complete, even when the rest has already arrived. A later handler that
    can wait, and proxy_pass, still read the whole body. A body that a
    post-read, server rewrite, rewrite, access or content handler is still
    waiting for is not complete either; when nginx has ended that read,
    Nginx::Request#body returns the part of the body that nginx had read
    (entry 14).
  • Why it changed:
    • The defect: a read that did not complete at once kept a reference to the
      request after the handler had returned, and its completion ran the phases
      again from wherever the request was then, with the results above.
    • Why the old behavior could not be kept: these handlers cannot wait:
      mruby_set* runs inside the script of nginx's rewrite module, a log
      handler while nginx frees the request, and the filters while nginx sends
      the response, and nginx goes on as soon as they return. So such a handler
      can only run with a body that is already complete, or without one.
      ngx_mruby decides this before the read starts, from Content-Length and
      the bytes in nginx's header buffer: a chunked body has no
      Content-Length, and an HTTP/2 or HTTP/3 body is read through events, so
      they count as not complete.
    • What the documentation promised: the 2.7.0 documentation of the directive
      said that ngx_mruby "reads a HTTP request body before calling mruby code"
      (mruby_enable_read_request_body) and named no handler
      that cannot wait. Neither 2.7.0 nor 2.7.1 makes these handlers wait for the
      rest of a body: 2.7.0 did not run their code when the read that it started
      did not complete at once, and 2.7.1 runs it at once, without the body or,
      after nginx ended the read of a waiting handler, with the part that nginx
      had read (entry 14). The
      documentation of the directive
      now names these handlers and says when they run without the body.
  • Affected: configurations with mruby_enable_read_request_body on whose
    mruby_set* handlers, log handlers or output filters read the request body.
    These handlers get no body in 2.7.1 when it is chunked, comes over HTTP/2 or
    HTTP/3, does not fit in nginx's header buffer together with the headers, or
    arrives after the headers, unless an earlier handler or module has read it.
    In 2.7.0 some of these bodies, such as a chunked body that arrived with the
    headers or a larger body that had already arrived, were read at once.
  • What to do: to give these handlers the whole body, read it first in a
    handler that can wait and runs before them, for example a server-level
    mruby_post_read_handler_code with mruby_enable_read_request_body on: once
    it has run, the body is complete for the handlers that run after it.
  • Tests: ports 18148 and 18149 (test/t/cases/request_body_later.rb).

7. Nginx::SSL works only in the handshake handler

  • Before: Nginx::SSL methods (Nginx::SSL.new, #servername, the
    certificate setters, #local_port, #tls_version, Nginx::SSL.log) called
    outside mruby_ssl_handshake_handler*, which the documentation did not
    support, could crash the worker or return meaningless values (#339). A
    handshake whose code did not call Nginx::SSL.new could get the certificate
    that an earlier handshake on the same worker had set, or fail when the memory
    of that earlier handshake's connection had been reused.
  • Now: outside the handshake handler they raise RuntimeError
    (Nginx::SSL can only be used in mruby_ssl_handshake_handler). A handshake
    whose code sets no certificate, also one that does not call
    Nginx::SSL.new, uses the server's ssl_certificate and
    ssl_certificate_key.
  • Why it changed:
    • The defect: outside the handshake handler, Nginx::SSL could crash the
      worker or return meaningless values
      (#339), and a handshake whose code did not
      call Nginx::SSL.new could get the certificate of an earlier handshake, or
      fail, as "Before" says.
    • Why the old behavior could not be kept: outside the handshake there is no
      connection and no server name, so the methods have nothing valid to
      return, and the state of a handshake has to be cleared when the handshake
      ends, so that a later handshake does not get it.
    • What the documentation promised: the documentation has said since 2.1.4
      that Nginx::SSL is for the handshake handlers and does not work in other
      handlers (Nginx::SSL Class of 2.7.0), and
      ssl_certificate is nginx's certificate for a handshake that does not
      choose one.
  • Affected: handlers that call Nginx::SSL outside the handshake handler,
    for example a content handler that reads servername, and handshake handlers
    that skip Nginx::SSL.new on some handshakes, for example code that returns
    early on a condition, or that creates the object once and keeps it. Handshake
    handlers that call Nginx::SSL.new on every handshake are not affected by
    the change of the certificate.
  • What to do: call Nginx::SSL only in the handshake handler (to use a
    value later, store it there, for example with Userdata as in the
    documentation). If your handler sets a certificate only on some handshakes
    without calling Nginx::SSL.new on the others, those others now get
    ssl_certificate.
  • Tests: ports 18089 and 18090 (test/t/ngx_mruby.rb).

8. Request methods outside a request raise RuntimeError

The code of mruby_init*, mruby_init_worker*, mruby_exit_worker*,
mruby_ssl_handshake_handler* and mruby_server_context_handler_code runs
outside a request: mruby_init* and mruby_server_context_handler_code while
nginx reads the configuration, the others in a worker. In the stream module,
the init, init worker, exit worker and server context code runs outside a
session. This entry has two parts.

Request and session methods, and Nginx.log, outside a request.

  • Before: request-scoped methods found the current request through a
    pointer that kept the last request the worker had handled.
    • Where no request had been handled yet, they crashed: in mruby_init* and
      mruby_server_context_handler_code nginx itself, while it read the
      configuration, and in mruby_init_worker* the worker.
    • In mruby_exit_worker* and mruby_ssl_handshake_handler* they read the
      last request that the worker had handled, whose memory could already be
      freed (meaningless data or a crash), and crashed as in
      mruby_init_worker* when the worker had not handled a request yet, for
      example in its first handshake.
    • Nginx.log and Nginx.errlogger raised RuntimeError where no request
      had been handled yet, which in mruby_init* and
      mruby_server_context_handler_code made the configuration invalid, and
      elsewhere they wrote through the last request that the worker had handled.
    • The stream module had the same problem in its init, init worker and exit
      worker code.
  • Now: outside a request, request-scoped methods raise RuntimeError
    (this method can only be used while processing a request). They are the
    methods of Nginx::Request, Nginx::Var, Nginx::Headers_in,
    Nginx::Headers_out, Nginx::Connection, Nginx::Server (except
    add_listener), Nginx::Filter, Nginx::Upstream and Nginx::Async, and
    Nginx.rputs, Nginx.echo, Nginx.return, Nginx.send_header,
    Nginx.status_code= and Nginx.redirect. In code that runs while nginx reads
    the configuration, this exception makes the configuration invalid, as any
    exception there does, unless the code rescues it. Nginx.log and
    Nginx.errlogger write to nginx's error log outside a request. In the stream
    init, init worker, exit worker and server context code,
    Nginx::Stream::Connection.new, its methods that read the session, and
    Nginx::Stream::Async.sleep raise (this method can only be used while processing a stream session), Nginx::Stream::Connection.stream_status and
    stream_status= do not, and Nginx::Stream.log writes to nginx's error
    log.
  • Why it changed:
    • The defect: outside a request, request-scoped methods crashed nginx or the
      worker, or used the last request that the worker had handled, and
      Nginx.log and Nginx.errlogger raised or wrote through that request, as
      "Before" says.
    • Why the old behavior could not be kept: outside a request there is no
      request to return, so the methods have to report an error; the old results
      were a crash or another request's data. Nginx.log does not need a
      request, so it writes to nginx's error log there.
    • What the documentation promised: the documentation shows the request
      methods only in request handlers, and the code listed above runs outside
      any request. The 2.7.0 documentation of Nginx.errlogger, of which
      Nginx.log is an alias, says that it "Sends an error to the log file" and
      names no handler that it is limited to
      (Nginx.errlogger of 2.7.0).
  • Affected: init, init worker, exit worker, server context and handshake
    code that uses request data (it could not work reliably before), and code
    there that relied on Nginx.log raising.
  • What to do: use request data in request handlers only. Nginx.log can
    now be used in the code listed above.
  • Tests: ports 18080 (mruby_init_worker_code) and 18089 (handshake
    handler), in test/t/ngx_mruby.rb.

add_listener only in the server context code.

  • Before: Nginx::Server#add_listener called after nginx had read the
    configuration, for example in a request handler, used configuration data that
    was no longer valid. Nginx::Stream.add_listener called in a stream session
    (mruby_stream_code) or in the stream init, init worker or exit worker code
    took the internal context of the stream module, which holds the current
    session, for a server configuration, and the process crashed. While
    mruby_stream_server_context_code ran, Nginx::Stream.log and the session
    methods took the server configuration for that internal context.
  • Now: Nginx::Server#add_listener raises RuntimeError (add_listener can only be used in mruby_server_context_handler_code) outside
    mruby_server_context_handler_code, and Nginx::Stream.add_listener raises
    RuntimeError (add_listener can only be used in mruby_stream_server_context_code) outside mruby_stream_server_context_code.
    Both work as before in that code, while nginx reads the configuration. In
    mruby_stream_server_context_code, Nginx::Stream.log writes to nginx's
    error log and the session methods raise, as in the stream init and worker
    code.
  • Why it changed:
    • The defect: add_listener called outside the server context code used
      configuration data that was no longer valid or crashed the process, and
      in mruby_stream_server_context_code Nginx::Stream.log and the session
      methods took the server configuration for the internal context of the
      stream module, as "Before" says.
    • Why the old behavior could not be kept: add_listener adds a listener to
      nginx's configuration, which nginx can change only while it reads the
      configuration, so it raises outside the server context code.
      mruby_stream_server_context_code runs while nginx reads the
      configuration, outside any session, so the session methods raise there and
      Nginx::Stream.log writes to nginx's error log, as in the stream init and
      worker code.
    • What the documentation promised: the 2.7.0 documentation shows
      Nginx::Server#add_listener in a configuration only in
      mruby_server_context_handler_code
      (Nginx::Server#add_listener), refers to that
      example for Nginx::Stream.add_listener
      (Nginx::Stream.add_listener), and does not say
      where else they can be called. It does not describe
      mruby_stream_server_context_code.
  • Affected: code that calls add_listener outside the server context code
    (it could not work before), and mruby_stream_server_context_code that calls
    Nginx::Stream.log or session methods.
  • What to do: call add_listener only in the server context code. There is
    no session in mruby_stream_server_context_code, so do not call session
    methods there.
  • Tests: port 18080 (Nginx::Server#add_listener in a content handler,
    test/t/ngx_mruby.rb) and port 12357 (Nginx::Stream.add_listener in a
    session, in a second nginx that test/t/cases/_second_instance.rb starts
    and test/t/cases/stream.rb calls through second_instance of
    test/t/cases/_prelude.rb).

9. mruby_set variables are no longer overwritten by later handlers

  • Before: after mruby_set or mruby_set_code (also a server-level one) had
    run in a request, a later handler of the same request that resumed after
    Nginx::Async.sleep had its last expression assigned to that variable.
  • Now: only the mruby_set handler's own result is assigned to its
    variable (#548). An mruby_set_code that sleeps itself still sets its
    variable when it resumes.
  • Why it changed:
    • The defect: mruby_set stored the name of its variable in the request's
      context and nothing cleared it, so when a later handler of the request
      resumed after Nginx::Async.sleep, ngx_mruby wrote that handler's last
      expression into the variable, for example the $backend of a later
      proxy_pass (#548).
    • Why the old behavior could not be kept: the configuration never asked for
      that write, and keeping it would mean that a sleep in an unrelated handler
      changes the variable.
    • What the documentation promised: the variable of a mruby_set is set by
      that mruby_set, as the directive is documented ("called at one of the
      rewrite phases to set a nginx variable",
      mruby_set and mruby_set_code of 2.7.0).
  • Affected: requests that combine mruby_set* with a later handler that
    uses Nginx::Async.sleep.
  • What to do: nothing. If a later handler should change the variable, assign
    it explicitly, for example Nginx::Var.new.backend = "...".
  • Tests: port 18123 (test/t/cases/async_set_var_target.rb).

10. nginx starts without an http block

  • Before: with ngx_mruby built in, a configuration without an http {}
    block, such as a stream-only one, made every worker crash at start, and nginx
    kept starting new ones.
  • Now: nginx starts (#536).
  • Why it changed:
    • The defect: the HTTP module's worker start and exit hooks read its main
      configuration without checking that it exists; without an http {} block
      it does not, and the worker crashed (#536).
    • Why the old behavior could not be kept: nginx accepts configurations
      without http {}, and the stream module of ngx_mruby already handled this
      case. The old behavior was a crash, so there is nothing to keep.
    • What the documentation promised: the documentation said nothing about a
      configuration without an http {} block.
  • Affected: configurations without an http {} block, such as stream-only
    ones, in an nginx that has the HTTP module of ngx_mruby built in or loaded.
  • What to do: nothing.
  • Tests: port 12399 (test/t/ngx_mruby.rb).

11. A body filter that calls Nginx.rputs after an mruby header filter no longer logs "header already sent"

  • Before: in a location with an mruby header filter and an mruby body
    filter whose code calls Nginx.rputs or Nginx.echo (which the
    documentation says is not supported there), nginx logged
    [alert] header already sent for every request, and the body filter set
    the status to 200 after the header was sent. The client received the status
    that nginx sent, but the log phase saw 200: a log handler and $status in
    log_format read 200 for a 404 response.
  • Now: nginx does not log that alert, and the log phase sees the status
    that nginx sent. The response is the same as before
    (#563), unless the body filter changes the length of the body, which
    entry 2 (fourth part) describes.
  • Why it changed:
    • The defect: at the end of its code the body filter sent the output of
      Nginx.rputs through the path for a handler that answers, which sent the
      header a second time and set the status to 200
      (#563).
    • Why the old behavior could not be kept: keeping that path would keep the
      [alert] header already sent line for every request and, in the log
      phase, a status other than the one that nginx sent, as "Before" says. The
      body filter no longer takes that path once an mruby header filter is in
      the location, and the output of Nginx.rputs in a body filter is dropped,
      as before.
    • What the documentation promised: the documentation says that
      Nginx.rputs and Nginx.echo cannot be used in the output body filters
      ("You can NOT use Nginx.rputs and Nginx.echo in the output body
      handlers", Nginx::Filter Class of 2.7.0); it said
      nothing about the status that the log phase sees.
  • Affected: locations with mruby_output_header_filter (or _code) and
    mruby_output_body_filter (or _code) whose body filter calls
    Nginx.rputs or Nginx.echo; access logs, log handlers and alerts that
    read $status or the header already sent line for those requests.
  • What to do: nothing, unless a log statistic or an alert counts on the
    status 200 or on the header already sent line of those requests.
  • Tests: port 18138
    (test/t/cases/output_filters_with_content_handler.rb).

12. An unread request body is discarded before the answer

  • Before: when a handler answered a request with Nginx.rputs or
    Nginx.echo without reading its body, for example a content or rewrite
    handler that answers a POST without mruby_enable_read_request_body, the
    body stayed on the connection. On a connection that nginx kept open for the
    next request (HTTP/1.1 keep-alive), nginx then read that body as the
    beginning of the next request.
  • Now: before ngx_mruby sends the answer of such a handler, it discards a
    request body that no handler has read, as nginx does for its own responses
    (return, its error pages, static files), and the next request on the
    connection is the one that the client sent after the body. If the body
    cannot be discarded, nginx closes the connection after the answer. The same
    holds for the answer that a rewrite handler sends after
    Nginx::Async.sleep. A body that a handler has read is not affected.
  • Why it changed:
    • The defect: nginx expects a handler that answers a request to read or
      discard the request body first, because the next request on a kept
      connection starts after the body; nginx's own handlers do this
      (ngx_http_send_response, the error pages, the static module), and the
      answer of an mruby handler did not.
    • Why the old behavior could not be kept: a body left on the connection is
      read as the beginning of the next request, as "Before" says. Discarding
      the body keeps the connection usable without making the answer wait for a
      body that the handler did not want.
    • What the documentation promised: the documentation said nothing about a
      request body that no handler reads.
  • Affected: handlers that answer requests with a body (POST, PUT) with
    Nginx.rputs or Nginx.echo without reading the body, on connections that
    nginx keeps open for the next request.
  • What to do: nothing. A handler that needs the body reads it as before,
    with mruby_enable_read_request_body on.
  • Tests: port 18151 (test/t/cases/unread_request_body.rb: a content
    handler, a rewrite handler, and a rewrite handler that answers after
    Nginx::Async.sleep).

13. A content handler that ends without output answers 500

  • Before: an mruby_content_handler* on the main request that ended without
    output sent no response when it set no status (it wrote nothing, wrote only
    "" or nil with Nginx.rputs, or only set response headers) or set a
    status below 300 other than 200, 201 and 204, for example
    Nginx::HTTP_ACCEPTED, also when it ended so after
    Nginx::Async::HTTP.sub_request had resumed it. nginx closed an HTTP/1.0
    connection without sending a byte and kept an HTTP/1.1 keep-alive connection
    open without a response until keepalive_timeout (75 s by default), so the
    client waited for its own timeout.
  • Now: such a request gets 500 with nginx's error page (or the
    error_page configured for 500) and Connection: close, the answer that
    Nginx.return Nginx::HTTP_OK without output already got in 2.7.0
    (#566). error.log gets a line at the error
    level: status code is not set, and response body is empty. return NGX_HTTP_INTERNAL_SERVER_ERROR, or status code is <N>, but response body is empty. return NGX_HTTP_INTERNAL_SERVER_ERROR.
  • Why it changed:
    • The defect: nginx sends a response of its own for 201, 204 and the
      statuses from 300 up, but for any other status below 300, and when no
      status is set, it ends the request without sending anything; a handler
      without output handed exactly such a value to nginx. A request without a
      response is a defect
      (#225): the client hangs until its own
      timeout, and a keep-alive connection is held for nothing.
    • Why the old behavior could not be kept: keeping it would leave these
      requests without a response. The 2.x line answers these requests the way
      it already answered Nginx::HTTP_OK without output, so no request that got
      a response in 2.7.0 gets a different one.
    • What the documentation promised: the documentation said nothing about a
      content handler that ends without output. It says that Nginx.return
      "Returns nginx status code to send back HTTP status to the client"
      (Nginx.return of 2.7.0); a status such as 202 without output
      gets 500 in 2.7.1, as 200 without output already did in 2.7.0.
  • Affected: mruby_content_handler* handlers that can end without output,
    for example a handler that writes only when a condition holds, or one that
    passes a value that can be empty or nil to Nginx.rputs, and log
    monitoring of these lines: a pattern that matches status code is 200, but response body is empty does not match the new lines, and one that matches
    response body is empty counts them too.
  • What to do: a handler that should answer with an empty body returns
    Nginx.return Nginx::HTTP_NO_CONTENT (nginx answers 204 itself) or writes a
    body; a handler that means to deny returns the status it means
    (Nginx::HTTP_FORBIDDEN, Nginx::HTTP_UNAUTHORIZED). Log monitoring that
    matches status code is 200, but response body is empty should match
    response body is empty. return NGX_HTTP_INTERNAL_SERVER_ERROR to see the new
    lines too.
  • Not changed by this release: Nginx::HTTP_OK without output (500, as
    before), 201, 204 and the statuses from 300 up (nginx answers them itself),
    handlers with output, Nginx.redirect, the other kinds of handler, and
    subrequests: Nginx::Async::HTTP.sub_request, SSI includes and
    auth_request see the same subrequest status as before. A content handler
    that writes output and then sets a status below 300 other than 200, 201 and
    204, for example Nginx.rputs "x" followed by
    Nginx.return Nginx::HTTP_ACCEPTED, still sends no response (see "Known
    limitations").
  • Tests: port 18136 (test/conf/conf.d/54-content-empty-body.conf,
    test/t/cases/content_empty_body.rb).

14. The waiting handler no longer runs after nginx ended its body read

With mruby_enable_read_request_body on, a post-read, server rewrite, rewrite,
access or content handler waits for the rest of the request body (entry 6).
nginx can end that read without the rest of the body: when
client_body_timeout expires, when the client closes the connection, or when
nginx answers 400 or 413 to the body, for example to a malformed chunked body.
This entry concerns the mruby log handler and the mruby output filters that run
for such a request afterwards.

  • Before: when the handler that waited was a post-read or access handler,
    such a log handler or filter started a body read of its own, and that read
    ran the code of the waiting handler, which had not run yet, after nginx had
    already decided the answer. After client_body_timeout, or after the client
    had closed the connection, the code of an access handler ran during the log
    phase. After a malformed chunked body it ran while nginx sent its 400 page,
    and the response had that page twice under a Content-Length that counted
    it once (157 bytes counted, 314 sent). When the handler that waited was a
    server rewrite, rewrite or content handler, 2.7.0 did not end the request at
    all (entry 6), so these handlers did not run.
  • Now: the log handler or filter does not start a read: it runs at once,
    Nginx::Request#body returns the part of the body that nginx had read
    before it ended the read, or nil when that part did not fit in nginx's
    body buffer (client_body_buffer_size) and nginx had written it to a
    temporary file, and error.log gets the info line of entry 6 (the request body is not complete and a log handler cannot wait for it, so it runs without the body, or a header filter, a body filter). The code of
    the waiting handler does not run. After client_body_timeout nginx closes
    the connection without a response and the access log records 408; after the
    client has closed the connection the access log records 400; after a
    malformed chunked body the client gets nginx's 400 page once, and nginx
    closes the connection.
  • Why it changed:
    • The defect: when a body read of the request has already started, nginx
      calls the completion handler of a new read at once, and the completion
      handler of ngx_mruby runs the phases of the request again for the handler
      that waits. A log handler or a filter that started a read after nginx had
      ended the first one therefore ran those phases again, from the log phase
      or from inside the response.
    • Why the old behavior could not be kept: a read that nginx has ended does
      not complete, so the waiting handler has no body to run with, and nginx
      has already answered the request or closed it: running that handler's code
      then did its work, such as an access check or a log line, for a
      request that was over, and sent nginx's error page a second time. A log
      handler or a filter cannot wait for a body (entry 6), so it runs with what
      nginx had read, without starting a read of its own.
    • What the documentation promised: the 2.7.0 documentation of the directive
      said that ngx_mruby "reads a HTTP request body before calling mruby code"
      (mruby_enable_read_request_body); it said nothing about a
      read that nginx ends without the whole body.
  • Affected: configurations with mruby_enable_read_request_body on whose
    post-read or access handler reads the body and whose requests also run an
    mruby log handler or an mruby output filter, for the requests whose body
    nginx stops reading early (client_body_timeout, a closed connection, 400 or
    413 for the body).
  • What to do: nothing. The code of a handler that waits for the body runs
    once, with the whole body; when nginx ends the read before the body is
    complete, it does not run.
  • Tests: port 18152 (test/t/cases/request_body_later.rb: a rewrite
    handler that waits, with a log handler after client_body_timeout, and with
    a header filter and with a body filter after a malformed chunked body).

アップグレードの前に読む挙動の変更

ngx_mruby 2.7.1は、セキュリティアドバイザリGHSA-h7fw-wf49-8rv5に書いてある問題を直しました。

ビルド、設定、スクリプトで使っているもの 読む項目
Redisとデフォルトのbuild_config.rb 1
mruby_output_body_filter*、mruby_output_header_filter*、またはNginx::Filter 2
Nginx.rputsかNginx.echoの後のraise 3
logハンドラか出力フィルタの中の、Nginx::AsyncかFiber.yield 4
再開した後に例外を投げるかNginx.redirectを呼ぶハンドラの中のNginx::Async.sleepかNginx::Async::HTTP.sub_request、またはsleepするlocationへのsub_request 5
mruby_enable_read_request_body on 6
Nginx::SSLかmruby_ssl_handshake_handler* 7
mruby_init*、mruby_init_worker*、mruby_exit_worker*、mruby_server_context_handler_code、ハンドシェイクのハンドラで呼ぶリクエストのメソッドかNginx.log、またはNginx::Server#add_listenerかNginx::Stream.add_listener、またはstreamのinit、init worker、exit worker、server contextのコード 8
mruby_set*と、同じリクエストで後に動くハンドラが呼ぶNginx::Async.sleep 9
http {}ブロックの無い設定 10
1つのlocationにmruby_output_header_filter*とmruby_output_body_filter*があり、ボディフィルタがNginx.rputsかNginx.echoを呼ぶ設定 11
POSTやPUTのようにボディのあるリクエストに、ボディを読まずにNginx.rputsかNginx.echoで応答するハンドラ 12
出力なしで終わることのあるmruby_content_handler*、またはresponse body is emptyに一致させるログの監視 13
post-readハンドラかaccessハンドラと組み合わせたmruby_enable_read_request_body onで、同じリクエストにmruby_log_handler*かmrubyの出力フィルタがあるもの 14

1. Redisはデフォルトのビルドに含まれなくなりました

  • 変更前:build_config.rbにmatsumotory/mruby-redisが入っていたので、デフォルトの設定でビルドしたバイナリにはRedisクラスがありました。
  • 変更後:mruby-redisの行はコメントアウトしました(#528)。コメントアウトしたのは、このgemが依存するhiredisを、バージョンを固定していないブランチからcloneするためです。このcloneが原因で、ビルドが壊れました。デフォルトのbuild_config.rbでビルドしたバイナリにはRedisクラスが無く、Redisを参照するコードではNameErrorが発生します。そのメッセージは「uninitialized constant Redis」です。
  • 変更の理由:
    • 背景:macOS以外では、mruby-redisのビルドがhiredisをデフォルトブランチの先頭からcloneします。そのため、hiredisのデフォルトブランチが変わると、デフォルトのbuild_config.rbで作るすべてのビルドが壊れる可能性がありました。#528でbuild_config.rbに足したコメントには、-Werrorを付けたCIでこの種の失敗が起きたことが書いてあります。
    • 前の挙動を残せなかった理由:gemをデフォルトの一覧に残していたら、すべてのデフォルトのビルドがこの種の失敗にさらされたままでした。デフォルトのビルドは成功しなければなりません。一方、mruby-redisは自身のビルドスクリプトでhiredisをcloneするので、build_config.rbではhiredisのバージョンを固定できません。したがって、mruby-redisがhiredisを固定するまで、このgemはデフォルトの一覧に残せません。
    • ドキュメントが示していた挙動:2.7.0のドキュメントでは、mruby-redisが「the default mrbgems」の1つに入っていました(2.7.0のdocs/install)。また、Redisは「with default build configuration」で使えるクラスの1つに入っていました(2.7.0のbuilt-in mrbgems)。つまり、ドキュメントには前の挙動が書いてありました。docs/installには、追加のgemを入れてngx_mrubyをビルドする方法として、build_config.rbでmrbgemsを選ぶ方法が書いてあります。Redisを残すにも、この方法を使います。
  • 影響の範囲:Redisを使うスクリプトです。たとえば、READMEとdocs/use_caseの例がこれに当たります。同梱のauto-ssl mrbgemの利用者も影響を受けます。このmrbgemのクライアントは、Redisの接続を受け取るからです。独自のbuild_config.rbでビルドする場合は影響を受けません。
  • 必要な対応:Redisを使う場合は、ビルドの前に、build_config.rbのconf.gem github: 'matsumotory/mruby-redis'のコメントアウトを外してください。#528に書いたhiredisの問題が残っている間は、このgemのビルドが失敗することがあります。

2. 出力フィルタでのレスポンスの長さとNginx::Filter

この項目は4つの部分に分かれます。

レスポンスの長さは、ボディフィルタの出力に従います。

  • 変更前:mruby_content_handler*のようなmrubyのハンドラがNginx.rputsかNginx.echoでレスポンスのボディを書き、mruby_output_body_filter*がそれをNginx::Filter#body=か#outputで置き換えると、レスポンスの長さは、Nginx.rputsが出力した長さのままでした。置き換えたボディが長いとその長さで切れ、短いとレスポンスの一部でないバイトでその長さまで埋まりました。ボディフィルタ自身がNginx.rputsかNginx.echoを呼ぶと、Content-Lengthは、フィルタを通る前のレスポンスの長さに、その出力の長さを足した値になり、その出力自体は送られませんでした。ドキュメントには、ボディフィルタでのこの呼び出しを認める記述が、どのバージョンにもありません。これらのレスポンスは壊れていたので、これらに依存してよいものはありません。このケースを試すリポジトリ自身のテストは切れたレスポンスを期待しており、その期待値はこのリリースで変わります。この部分では、mrubyのヘッダフィルタの無いlocationについて書きます。ヘッダフィルタのあるlocationについては、4つ目の部分を見てください。
  • 変更後:ボディはボディフィルタの出力と同じになり、Content-Lengthはその長さになります。ボディフィルタがNginx.rputsかNginx.echoで書いたものは、送られず、Content-Lengthにも入りません。
location /filter/output_rputs_origin {
    mruby_content_handler_code 'Nginx.rputs "origin"';
    mruby_output_body_filter_code '
        f = Nginx::Filter.new
        f.output "[#{f.body}] and more"
    ';
}
バージョン Content-Length ボディ
2.7.0 6 [origi
2.7.1 17 [origin] and more
  • 変更の理由:
    • 不具合:ngx_mrubyは、ボディ用に保持している長さの分だけ、ボディフィルタのバッファからバイトを送り、Content-Lengthにも同じ数を設定します。2.7.0では、ngx_mrubyは、その長さにNginx.rputsが数えたContent-Lengthを使い、バッファにはボディフィルタの出力を使っていました。そのため、フィルタが長さを変えるたびに、長さとバッファが食い違いました。長いボディは切れ、短いボディの後では、ngx_mrubyが新しいボディの終わりより先のバイト、つまりレスポンスの一部でないメモリを送りました。
    • 前の挙動を残せなかった理由:長さとバッファは一致しなければならず、バッファはフィルタの出力なので、長さは出力に従う必要があります。前の長さを残すと、ボディが切れるか、バッファの先まで読む挙動が残ります。
    • ドキュメントが示していた挙動:ドキュメントには、Nginx::Filter#body=について「Sets the string to the response body」と書いてあり、2.7.1のレスポンスはこの記述のとおりです。ほかのものが作ったレスポンスでは、2.7.0でも既にこの記述のとおりでした。2.7.0のドキュメントの同じ節(Nginx::Filter Class)には、「You can NOT use Nginx.rputs and Nginx.echo in the output body handlers」と書いてあります。
  • 影響の範囲:Nginx.rputsかNginx.echoで書いたボディの長さをボディフィルタが変えるlocationと、レスポンスを何が作ったかに関わらず、自分でNginx.rputsかNginx.echoを呼ぶボディフィルタです。長さを変えず、これらを呼ばないボディフィルタでは、何も変わりません。ファイル、return、proxy_pass、ほかのcontentハンドラが作ったレスポンスに掛かるボディフィルタも変わりません。これらでは、長さが既にフィルタの出力に従っていたからです。
  • 必要な対応:クライアントやテストが切れたレスポンスを期待していた場合を除き、ありません。ボディフィルタからはNginx.rputsとNginx.echoを取り除いてください。ボディフィルタでこれらが書いたものは送られません。
  • テスト:test/t/cases/filter_connection.rbのポート18112のテストです。

ボディを読む前に呼んだNginx::Filter#bodyが返す値が変わります。

  • 変更前:mruby_output_header_filter*ではボディをまだ読んでいません。そこで呼んだNginx::Filter#bodyは、Content-Lengthと同じ長さで、中身がレスポンスのボディでない文字列を返しました。長さが不明なとき、または長さが10485760バイト、すなわち10 MiB以上のときは、代わりにArgumentErrorが発生しました。
  • 変更後:そこでは空の文字列を返します。contentハンドラでは、既に空の文字列を返していました。
  • 変更の理由:
    • 不具合:ヘッダフィルタではボディをまだ読んでいません。2.7.0では、「変更前」に書いたとおり、Content-Lengthと同じ長さで中身がレスポンスのボディでない文字列が返るか、ArgumentErrorが発生しました。
    • 前の挙動を残せなかった理由:その時点では返すボディが無いので、正しい結果は空の文字列だけです。長さは$sent_http_content_lengthで得られます。
    • ドキュメントが示していた挙動:ドキュメントには一貫して、Nginx::Filterは出力のボディフィルタで使うクラスだと書いてあります。2.7.0のドキュメントの記述は「designed to be used in the output body handlers」です(2.7.0のNginx::Filter Class)。
  • 影響の範囲:f.bodyを読むヘッダフィルタです。たとえば、レスポンスの長さを知るためにf.bodyのサイズを読むものが当たります。
  • 必要な対応:長さはNginx::Var.new.sent_http_content_lengthで読んでください。値はStringで、長さが不明なときはnilです。ボディはmruby_output_body_filter*で読んでください。
  • テスト:test/t/ngx_mruby.rbのポート18080のテストです。

Nginx::Filter#body=と#outputは、ボディフィルタの中でだけ使えます。

  • 変更前:これらはどこでも呼べました。ボディフィルタもあるlocationで、ボディフィルタ以外のハンドラがこれらを呼ぶと、そのボディフィルタが空でないレスポンスを読んだ時点でワーカーがクラッシュしました。locationにボディフィルタが無いときは、この呼び出しはレスポンスに何の影響もありませんでした。
  • 変更後:mruby_output_body_filter*の外ではRuntimeErrorが発生します。メッセージはNginx::Filter#body= can only be used in an output body filterです。ほかの例外と同じく、この例外でハンドラは終わります。
  • 変更の理由:
    • 不具合:ボディフィルタの外でNginx::Filter#body=か#outputでボディを設定すると、「変更前」に書いたとおり、locationのボディフィルタが空でないレスポンスを読んだときにワーカーがクラッシュしました。ボディフィルタが無いときは、何の影響もありませんでした。
    • 前の挙動を残せなかった理由:2.xでは、ボディフィルタが読んで送るボディと、Nginx::Filter#body=が設定するボディに、1つのバッファを使います。また、ボディフィルタの外でボディを設定する使い方は、一度もサポートしていませんでした。そのため、2.7.1では2つ目のバッファを足さずに、この呼び出しを拒否します。
    • ドキュメントが示していた挙動:ドキュメントには一貫して、Nginx::Filterはほかのハンドラでは動かないと書いてあります。2.7.0のドキュメントの記述は「It doesn't work in other handlers like mruby_content_handler_code」です(2.7.0のNginx::Filter Class)。
  • 影響の範囲:ヘッダフィルタやほかのハンドラのうち、body=かoutputを呼ぶものです。
  • 必要な対応:ボディはmruby_output_body_filter*で設定してください。
  • テスト:test/t/ngx_mruby.rbのポート18080のテストです。

mrubyのヘッダフィルタがあるときは、ヘッダがボディフィルタを待ちます。

  • 変更前:mruby_output_header_filter*とmruby_output_body_filter*のあるlocationでは、ヘッダフィルタのコードが終わるとすぐにヘッダが出ていき、そのContent-Lengthは、ボディフィルタを通る前のレスポンスの長さでした。そのため、ボディを長くするボディフィルタはContent-Lengthが示すより多いバイトを送り、短くするボディフィルタは少ないバイトを送りました。Nginx.rputsで書くハンドラがレスポンスを作る場合、このようなlocationはまったく応答しませんでした。この件は「不具合の修正」の節を見てください。
  • 変更後:ヘッダは、ボディフィルタが終わるまで待ちます。ボディフィルタだけのlocationでは、既にそうなっていました。ヘッダには、ボディフィルタの出力の長さと、ヘッダフィルタが加えた変更が入ります。ヘッダフィルタのコードは、これまでどおりボディフィルタのコードより先に動きます。長さが分からないレスポンスは、前と同じく、ボディフィルタを通らずに次へ渡ります。
  • 変更の理由:
    • 不具合:ヘッダを先に送ると、レスポンスのContent-Lengthがその時点で決まり、その後でボディフィルタが長さを変えていました。Content-Lengthでレスポンスを読むクライアントは、違う長さのボディを正しく読めません。
    • 前の挙動を残せなかった理由:ボディの長さを決めるのはボディフィルタなので、ヘッダに正しいContent-Lengthを入れられるのは、ボディフィルタが動いた後だけです。ボディフィルタだけのlocationでは、同じ理由で既にヘッダを待たせていました。
    • ドキュメントが示していた挙動:両方のフィルタがあるlocationでヘッダをいつ送るかは、ドキュメントに書いてありませんでした。Nginx::Filter#body=については、「Sets the string to the response body」と書いてあります(2.7.0のNginx::Filter Class)。
  • 影響の範囲:mrubyのヘッダフィルタとmrubyのボディフィルタの両方があり、ボディフィルタがボディの長さを変えるlocationです。
  • 必要な対応:ありません。
  • テスト:test/t/cases/header_and_body_filter.rbのポート18150のテストです。レスポンスをファイルが作る場合と、Nginx.rputsで書くハンドラが作る場合を試します。

3. Nginx.rputsの後で例外が発生すると、レスポンスは500になります

  • 変更前:post-read、server rewrite、rewrite、access、contentのいずれかのハンドラが、Nginx.rputsかNginx.echoで出力を書いてから例外を投げると、それまでに書いた出力を付けて200で応答しました。これは、先にNginx::Asyncで待たなかった場合です。accessハンドラかpost-readハンドラでは、nginxがその後のフェーズへ進んだので、locationのcontentハンドラも動き、その出力が後に続きました。
  • 変更後:リクエストにはnginxの500エラーページが返り、出力は破棄されます。その後のフェーズは動きません。出力なしで例外を投げるハンドラは、既にこの結果になっていました。Nginx::Asyncの後で例外を投げるハンドラも、この結果になります(項目5)。
    • mruby_set*:2.7.0では、出力がレスポンスとして送られ、変数にはハンドラが設定していない値が入りました。いまは出力が破棄され、変数は空の文字列になります。これはnilを返すハンドラと同じです。locationの前のディレクティブが変数に値を与えていた場合も、変数は空の文字列になります。リクエストは先へ進み、レスポンスのContent-Lengthには破棄した出力が入りません。ここまでは、ハンドラがNginx::Async.sleepかNginx::Async::HTTP.sub_requestで待つ前に例外を投げた場合です。Nginx::Async.sleepの後では、リクエストは先へ進まず、出力の無いnginxの500エラーページが返ります。2.7.0では、出力がレスポンスとして200で送られていました。Nginx::Async::HTTP.sub_requestの後では、nginxが変数を待たずにcontentフェーズへ進むので、例外に続く500を送れず、クライアントには何のレスポンスも届きません(項目5)。
    • ヘッダフィルタ:ヘッダフィルタで例外が発生したときは、2.7.0でも既にレスポンスのステータスが500になり、ボディには元のレスポンスのボディが残りました。2.7.0では、Nginx.rputsかNginx.echoを呼ぶヘッダフィルタでワーカーがクラッシュしました。この件は「不具合の修正」の節を見てください。そのようなヘッダフィルタがその後で例外を投げると、いまはその出力が破棄され、Content-Lengthは、元のレスポンスが持っていたボディの長さになります。破棄するのは、ヘッダフィルタ自身の出力だけです。レスポンスを作るのがNginx.rputsかNginx.echoで書くmrubyのcontentハンドラなら、レスポンスにはそのハンドラの出力とそのContent-Lengthが残ります。ヘッダフィルタが出力なしで例外を投げた場合も同じで、この場合は2.7.0も同じレスポンスを送っていました。
    • logハンドラとボディフィルタ:例外の後は、出力を送らなくなりました。
  • 変更の理由:
    • 不具合:例外の後、ngx_mrubyはmrb_run failed: return 500 HTTP status code to clientをログに出してステータスを500にしました。ところが、その後で出力を送るコードパスがステータスをリセットし、途中までの出力を200で送りました。そのため、失敗したハンドラが、クライアントには成功として伝わりました。accessハンドラかpost-readハンドラでは、このコードパスが、nginxが「先へ進む」と読む値も返しました。そのため、例外で失敗したアクセスチェックでも、リクエストが通りました。
    • 前の挙動を残せなかった理由:例外が発生したら、ハンドラはエラーのステータスで終わらなければなりません。そうしないと、アクセスの判定を誤ります。出力を送るコードパスでは、200を送りながらフェーズを止められないので、出力を破棄します。クライアントには、error.logの行が前から示していた500が届きます。これは、出力なしの例外の後やNginx::Asyncの後と同じです。mruby_set*のハンドラはリクエストに応答しないので、例外の後もリクエストは先へ進みます。そのため、破棄した出力は、その後に続くレスポンスの長さに入ってはいけません。また、変数には決まった値が要ります。2.7.0では、nginxのスクリプトエンジンがその時点で持っていた値が、そのまま変数に入りました。
    • ドキュメントが示していた挙動:例外を投げるハンドラについては、ドキュメントに何も書いてありませんでした。ドキュメントには、出力を書いてからNginx.return Nginx::HTTP_OKを呼び、returnで抜けるcontentハンドラの例があります(2.7.0のNginx.return)。このハンドラは、「必要な対応」に示すとおり、2.7.0でも2.7.1でも200で応答します。
  • 影響の範囲:出力を書いた後でハンドラを止めるためにraiseを使うスクリプト、メッセージを書いてから例外を投げるアクセスチェック、出力を書いてから例外を投げるmruby_set*のハンドラです。
  • 必要な対応:raiseは、エラーのためだけに使ってください。出力を返してcontentハンドラを途中で終えたいときは、例外を使わずに終えてください。
# 2.7.0: 200 "under maintenance"   2.7.1: 500
Nginx.rputs "under maintenance"
raise "stop"
# 2.7.0 and 2.7.1: 200 "under maintenance"
Nginx.rputs "under maintenance"
Nginx.return Nginx::HTTP_OK
return   # leaves the handler; omit it when nothing follows

200以外のステータスでNginx.returnを呼ぶと、2.7.0と同じく、nginxはNginx.rputsの出力を付けずに、そのステータスのnginx自身のページを送ります。accessハンドラとpost-readハンドラでは、出力を書かないでください。書いた出力は、ハンドラが終わるときにレスポンスとして送られます。Nginx::HTTP_OKを返すかステータスを設定しない場合は、nginxがその後のフェーズへ進み、そのフェーズの出力がContent-Lengthを超えてレスポンスの後に続きます。これは2.7.0でも2.7.1でも同じで、この件は「既知の制限」の節に書きました。accessハンドラやpost-readハンドラでリクエストを止めるには、Nginx.return Nginx::HTTP_FORBIDDENのようにエラーのステータスを返してください。

  • このリリースで変わらない挙動:Nginx.rputsの後でNginx.return、Nginx.send_header、Nginx.status_code=のどれかを呼んでから例外を投げたハンドラは、既に500になっていました。例外を投げる前にローカルのURIへNginx.redirectしたハンドラは、これまでどおり、リダイレクト先のレスポンスで終わります。
  • テスト:test/t/cases/sync_exception.rbのポート18143のテストです。

4. logハンドラと出力フィルタでは、Nginx::Asyncで例外が発生します

  • 変更前:mruby_log_handler*でNginx::Async.sleepを呼ぶと、nginxが既に解放している途中のリクエストにタイマーが残り、タイマーが切れたときにワーカーがクラッシュすることがありました。logハンドラでNginx::Async::HTTP.sub_requestを呼ぶと、サブリクエストが始まりました。mruby_output_header_filter*とmruby_output_body_filter*では、Nginx::Async.sleepを呼んだ位置でフィルタが止まりました。レスポンスはフィルタを通らずに、元のレスポンスのステータスで出ていきました。テストした設定では、そのステータスは200でした。タイマーが切れる前にリクエストが終わるので、sleepの後のコードは動きませんでした。ヘッダフィルタでsub_requestを呼ぶと、サブリクエストが始まりました。これらのハンドラで直接Fiber.yieldを呼ぶと、メッセージなしでハンドラが止まりました。
  • 変更後:これらのハンドラでは、どちらのメソッドでもRuntimeErrorが発生します。メッセージは、たとえばNginx::Async.sleep is not available in a log handlerで、ヘッダフィルタでは... in a header filter、ボディフィルタでは... in a body filterです。例外は、タイマーをセットする前、サブリクエストを始める前に発生します。この例外は、ほかの例外と同じように扱われます。error.logに[error]の行が出て、フィルタではレスポンスのステータスが500になります。テストした設定では、そのボディはフィルタを通っていないボディでした。logハンドラでは、レスポンスは既に送ってあります。これらのハンドラで直接Fiber.yieldを呼ぶと、... yielded its fiber, but nginx cannot resume it thereがログに出て、フィルタではステータスが500になります。
  • 変更の理由:
    • 不具合:nginxは、リクエストを解放する途中でlogフェーズを動かします。それは、リクエストのクリーンアップの後で、リクエストのメモリを解放する直前です。そのため、logフェーズでセットしたタイマーは解放済みのメモリの上で発火し、もう存在しないリクエストでハンドラが再開しました。出力フィルタはngx_http_send_headerとngx_http_output_filterの中で動き、この2つはすぐに呼び出し元へ戻ります。そのため、出力フィルタの中でyieldしたハンドラはただ止まり、フィルタの処理が飛ばされます。後でタイマーかサブリクエストがハンドラを再開しても、レスポンスは既に出ていっています。直接のFiber.yieldは、一度も再開されません(#551)。
    • 前の挙動を残せなかった理由:これらの場所でハンドラを再開しても、nginxには、レスポンスをまだ変えられる時点がありません。そのため、この呼び出しは、タイマーをセットする前、サブリクエストを始める前に失敗しなければなりません。
    • ドキュメントが示していた挙動:ドキュメントには一貫して、Nginx::Asyncが動く場所として、set、rewrite、accessのハンドラが挙げてあります。logハンドラとフィルタは、その中に一度も入っていません(2.7.0のNginx::Async Class)。
  • 影響の範囲:Nginx::Async.sleep、Nginx::Async::HTTP.sub_request、Fiber.yieldを呼ぶlogハンドラと出力フィルタです。
  • 必要な対応:rewriteハンドラかaccessハンドラ、またはmruby_set_codeの中で待ち、結果はnginxの変数でフィルタやlogハンドラへ渡してください。
  • このリリースで変わらない挙動:mruby_set*と、post-read、server rewrite、rewrite、access、contentの各ハンドラは、これまでどおり両方のメソッドを使えます。contentハンドラについては、「既知の制限」の節を見てください。
  • テスト:test/t/cases/async_sleep_in_log.rbのポート18129のテストと、test/t/cases/async_sleep_in_output_filter.rbのポート18131のテストです。

5. Nginx::Asyncの後で例外が発生すると、レスポンスは500になります

この項目では、Nginx::Async.sleepかNginx::Async::HTTP.sub_requestが再開したハンドラについて書きます。対象は、そのハンドラが例外を投げる場合と、Nginx.redirectを呼んでから例外を投げるかNginx.returnを呼ぶ場合です。sleepするlocationへのsub_requestも対象です(#550)。

  • 変更前:
    • 出力が無いときは、nginxがレスポンスなしで接続を閉じました。
    • Nginx.rputsの後では、クライアントには、それまでに書いた出力を付けた200が返りました。
    • ステータスを設定した後、たとえばNginx.return 503の後では、クライアントにはそのステータスが返りました。serverレベルのハンドラのように、同じリクエストのハンドラが前にNginx.return Nginx::DECLINEDを呼んでいたときは、nginxが次のフェーズへ進みました。たとえば、ファイルを200で返しました。
    • 同じワーカーで次にいずれかのmrubyのハンドラを動かすリクエストは500で失敗し、error.logには前の例外がもう一度出ました。
  • 変更後:リクエストにはnginxの500エラーページが返り、出力は破棄されます。次のリクエストは影響を受けません。
    • レスポンスが既に始まっていたときは、500を送れません。nginxはheader already sentをログに出してリクエストを終え、クライアントには、それまでに送ったものが残ります。Nginx::Async.sleepの後でローカルのURIへNginx.redirectしたときは、クライアントに残るのはリダイレクト先のレスポンスです。#550のために測った2つのケースでは、2.7.0ではレスポンスが届いていたのに、いまはクライアントに何のレスポンスも届きません。1つ目は、Nginx::Async::HTTP.sub_requestの後のNginx.redirectです。2.7.0では、リダイレクト先のレスポンスが送られた後、クライアントが閉じるまで接続が開いたままでした。2つ目は、sub_requestの後で例外を投げるmruby_set_codeです。nginxは、contentフェーズの前に変数を待ちません。2.7.0では、contentハンドラの出力を付けた200が送られていました。
    • 再開したハンドラでNginx.redirectの後に例外かNginx.returnが続くと、nginxは、リダイレクト先のレスポンスのすぐ後で接続を閉じます。HTTP/1.1のkeep-aliveの接続では、その後ろにパイプラインで送ったリクエストにはレスポンスが返りません。クライアントは、新しい接続でそのリクエストを送り直す必要があります。2.7.0では接続が開いたままでしたが、パイプラインで送ったリクエストにそのリクエストのレスポンスが返らない点は同じでした。例外の後では、ワーカーが持ち続けた例外による500エラーページが返りました。これは、上の「変更前」の最後の点に書いた挙動です。Nginx.returnの後では、クライアントかタイムアウトが接続を閉じるまで、何も返りませんでした。
    • Nginx::Async.sleepで待つハンドラのあるlocationへのNginx::Async::HTTP.sub_requestは、いまは完了します。2.7.0では、クライアントかsend_timeoutがリクエストを終えるまで、何も送られませんでした。そのlocationが例外を投げたときは、Nginx::Async::HTTP.last_response.statusは0です。
  • 変更の理由:
    • 不具合:再開したハンドラで例外が発生した後、ngx_mrubyはreturn 500 HTTP status code to clientをログに出し、その後で500を、例外の前にハンドラが持っていたステータスに置き換えました。そのステータスは、0、つまりレスポンスなしか、途中までの出力を付けた200か、nginxが次のフェーズへ進むNginx::DECLINEDのような値でした。例外は、ワーカーのすべてのリクエストが共有するmrubyの状態にも残り、次のリクエストがその例外で失敗しました。2.7.0では、Nginx.redirectの後にステータスを付けてNginx.returnを呼ぶと、クライアントかタイムアウトが終えるまで、リクエストとその接続が開いたままでした(#550)。
    • 前の挙動を残せなかった理由:例外の後は、その状態をクリアしなければなりません。そうしないと、ワーカーの次のリクエストが失敗します。ステータスも、エラーのままでなければなりません。そうしないと、nginxは失敗したハンドラを成功として扱います。nginxは、タイマーの中で終えたリクエストを完了させるとき、そのリクエストを終える間にキューへ入れたposted requestsを実行します。2.7.1では、500か、Nginx.returnで設定したステータスがnginxに届くのは、リダイレクト先のレスポンスを送った後です。そのため、nginxは接続を閉じる以外の方法でリクエストを終えられず、posted requestsを実行すると、すぐに接続が閉じます。keep-aliveの接続がリダイレクト先のレスポンスの後で閉じるようになったのは、このためです。クライアントには、error.logの行が示す500が届きます。これは、待たなかったハンドラで例外が発生した後と同じです。
    • ドキュメントが示していた挙動:2.7.0のREADMEには、スクリプトが共有するmrubyの状態の「the exception flag」を、サーバーのプロセスが解放すると書いてあります。解放する目的は「extend safety by preventing interference between each script」です(Abstract)。前のリクエストの例外で次のリクエストが失敗するのは、この干渉に当たります。Nginx::Asyncが再開したハンドラでの例外と、そのようなハンドラでのNginx.redirectについては、ドキュメントに何も書いてありませんでした。ドキュメントには、Nginx::Async.sleepとNginx::Async::HTTP.sub_requestが動く場所として、set、rewrite、accessのハンドラが挙げてあります(2.7.0のNginx::Async Class)。
  • 影響の範囲:Nginx::Asyncを使い、その後で例外を投げることのあるハンドラ、レスポンスなしで接続が閉じる挙動や例外の前に設定したステータスに頼っていたクライアント、sub_requestを使うmruby_set_codeのハンドラです。再開したハンドラでNginx.redirectを呼んでから例外を投げるかNginx.returnを呼ぶlocationに、keep-aliveの接続でリクエストをパイプラインで送るクライアントも、影響を受けます。
  • 必要な対応:例外の後に500以外を返したいハンドラは、ハンドラの中で例外をrescueし、そこでステータスを設定してください。
  • テスト:test/t/cases/async_exception_state.rbのポート18130のテストと、test/t/cases/async_subrequest_raise.rbのポート18124のテストです。

6. mruby_enable_read_request_bodyで、どのハンドラがボディ全体を待つか

mruby_enable_read_request_body onのとき、ngx_mrubyは、ハンドラのコードを動かす前にリクエストボディを読みます。この項目は2つの部分に分かれます。1つ目は、まだそろっていないボディを待てるハンドラ、2つ目は待てないハンドラです。

post-read、server rewrite、rewrite、access、contentの各ハンドラは待ちます。

  • 変更前:ハンドラが始まったときにリクエストボディが全部届いていないと、mruby_server_rewrite_handler*、mruby_rewrite_handler*、mruby_content_handler*は一度も動きませんでした。クライアントにはレスポンスが返らず、クライアントが接続を閉じても、client_body_timeoutが切れても、nginxはリクエストを終えませんでした。大きなアップロードや遅いクライアントのように、ボディが2回以上の読み込みに分かれて届くだけで、この状態になりました。post-readハンドラとaccessハンドラはボディを待ち、ボディを受け取って動きました。しかし、そのように待った後では、auth_requestのようにサブリクエストを待つ後のフェーズのハンドラが、再開しませんでした。この場合もクライアントにはレスポンスが返らず、クライアントが閉じた後も接続が開いたままでした。
  • 変更後:ハンドラは、nginxがボディを全部読んだ後に動きます。続いて、リクエストは後のフェーズへ進み、auth_requestのようにサブリクエストを待つフェーズのハンドラも動きます。keep-aliveの接続では、次のリクエストにも通常どおり応答し、ハンドラで例外が発生した場合は500を返します。クライアントが先に接続を閉じると、nginxはclient prematurely closed connectionをログに出してリクエストを終えます。client_body_timeoutが切れると、nginxはレスポンスなしで接続を閉じ、アクセスログには408が記録されます。どちらの場合も、ハンドラは動きません。そのようなリクエストのlogハンドラとフィルタについては、項目14を見てください。
  • 変更の理由:
    • 不具合:ボディがそろっていない間、ngx_mrubyはNGX_AGAINを返していました。nginxは、rewriteフェーズとcontentフェーズでこの値を「終わった」と読みます。そのため、nginxはボディの読み込みをやめて、client_body_timeoutを外しました。ハンドラは、二度と動きませんでした。クライアントには応答が無く、クライアントが去った後も、ワーカーが終了するまでリクエストとその接続が開いたままでした。post-readハンドラかaccessハンドラがボディを待った後は、ngx_mrubyがフェーズを動かし直しました。このとき、書き込みイベントのハンドラは、nginxがボディを読む間に設定する何もしないハンドラのままでした。nginxは、auth_requestのようにサブリクエストを待つフェーズのハンドラを、この書き込みイベントのハンドラから再開します。そのため、そのハンドラは再開しませんでした。
    • 前の挙動を残せなかった理由:これらのフェーズでリクエストを待たせておけるのは、ハンドラがNGX_DONEを返したときだけです。リクエストを終えつつボディを読み続ける戻り値はありません。そのため、ハンドラは待つ必要があり、ngx_mrubyは、ボディがそろったときにフェーズを動かし直します。サブリクエストを待つフェーズのハンドラは、書き込みイベントのハンドラからしか再開しません。そのため、ngx_mrubyは、nginxのmirrorモジュールと同じく、フェーズを動かし直す前に書き込みイベントのハンドラを元に戻すようになりました。
    • ドキュメントが示していた挙動:いまは、ハンドラがボディを受け取ります。ドキュメントには、このディレクティブの動作として「reads a HTTP request body before calling mruby code」と書いてあり、2.7.1の動作はこの記述のとおりです。2.7.0のこのディレクティブのドキュメント(mruby_enable_read_request_body)には、「a request body is not always read when invoking a handler like mruby_content_handler」と書いてあります。同じドキュメントには、「The directive force to read the request body」ともあります。
  • 影響の範囲:このディレクティブをserver rewrite、rewrite、contentのハンドラと使う設定です。このディレクティブをpost-readハンドラかaccessハンドラと使い、その後にauth_requestか、サブリクエストを待つほかのフェーズのハンドラが続く設定も、影響を受けます。
  • 必要な対応:ありません。
  • テスト:test/t/cases/request_body_later.rbの、ポート18144とポート18147のテストです。ポート18144のテストは、5種類のハンドラ、keep-alive、client_body_timeout、ボディの後の例外を試します。ポート18147のテストは、rewriteハンドラとaccessハンドラの後のauth_requestを試します。

mruby_set*、logハンドラ、出力フィルタは待ちません。

  • 変更前:これらのハンドラも、ほかのハンドラと同じく、コードを動かす前にボディを読み始めました。ボディが既に全部届いていたときのように、nginxがボディを一度で全部読めたときは、コードはボディを受け取って動きました。そうでないときは、コードはその時点では動かず、mruby_set*の変数には、ハンドラが設定していない値が入りました。ngx_mrubyが始めたボディの読み込みは残りました。その読み込みが完了すると、リクエストのフェーズが、そのときnginxが処理していたフェーズからもう一度動きました。nginx 1.31.6では、前のハンドラがボディを読んでいないHTTP/2のリクエストのすべてで、これが起きました。nginxがそのようなボディをイベントで読むからです。テストした設定では、mruby_set_codeと2つに分かれて届くボディで、次のことが起きました。
    • 同じlocationのmrubyのcontentハンドラが2回動き、ボディの最初の部分だけで応答しました。
    • proxy_passでは、upstreamのサーバーが、届いた部分だけを受け取りました。upstreamのサーバーが残りを待つときは、クライアントにレスポンスが返りませんでした。待たないときは、クライアントにレスポンスは返りましたが、nginxはHTTP/1.0の接続を閉じませんでした。
    • クライアントが閉じた後も、接続が開いたままでした。
  • 変更後:これらのハンドラがボディを読むのは、読み込みがすぐに完了するときだけです。それは、前のハンドラかモジュールがボディを読んだとき、リクエストにボディが無いとき、Content-LengthのあるHTTP/1.xのリクエストでボディ全体がヘッダのバッファに入っているときです。ヘッダのバッファは、nginxがリクエストヘッダを読み込んだバッファで、デフォルトで1kのclient_header_buffer_sizeのバッファか、ヘッダが必要としたlarge_client_header_buffersのバッファです。それ以外のときは、コードはボディなしですぐに動きます。Nginx::Request#bodyはnilを返し、error.logにはinfoレベルの行が1行出ます。その行の末尾はthe request body is not complete and an mruby_set handler cannot wait for it, so it runs without the bodyで、ハンドラによって、an mruby_set handlerの部分がa log handler、a header filter、a body filterになります。chunkedのボディ、HTTP/2かHTTP/3のボディ、そのバッファに一部だけが入っているボディは、残りが既に届いていても、そろっていないものとして扱います。待てる後のハンドラとproxy_passは、これまでどおりボディ全体を読みます。post-read、server rewrite、rewrite、access、contentのハンドラがまだ待っているボディも、そろっていないものとして扱います。nginxがその読み込みを打ち切ったときは、Nginx::Request#bodyは、ボディのうちnginxが読んだ部分を返します(項目14)。
  • 変更の理由:
    • 不具合:すぐに完了しなかった読み込みは、ハンドラが戻った後もリクエストへの参照を持ち続けました。その読み込みが完了すると、リクエストのフェーズが、そのときnginxが処理していたフェーズからもう一度動き、上に書いた結果になりました。
    • 前の挙動を残せなかった理由:これらのハンドラは待てません。mruby_set*は、nginxのrewriteモジュールが実行するスクリプトの中で動きます。logハンドラはnginxがリクエストを解放する途中で動き、フィルタはnginxがレスポンスを送る途中で動きます。nginxは、これらが戻るとすぐに先へ進みます。そのため、このようなハンドラは、既にそろっているボディを受け取って動くか、ボディなしで動くしかありません。ngx_mrubyは、読み込みを始める前に、Content-Lengthとnginxのヘッダのバッファにあるバイトから、これを決めます。chunkedのボディにはContent-Lengthが無く、HTTP/2かHTTP/3のボディはイベントで読むので、そろっていないものとして扱います。
    • ドキュメントが示していた挙動:2.7.0のこのディレクティブのドキュメントには、ngx_mrubyが「reads a HTTP request body before calling mruby code」と書いてありました(mruby_enable_read_request_body)。待てないハンドラは、挙げてありませんでした。2.7.0でも2.7.1でも、これらのハンドラはボディの残りを待ちません。2.7.0では、始めた読み込みがすぐに完了しないと、コードが動きませんでした。2.7.1では、コードがすぐに動きます。そのとき、ボディは無いか、待っているハンドラの読み込みをnginxが打ち切った後なら、nginxが読んだ部分になります(項目14)。いまのディレクティブのドキュメントには、これらのハンドラと、ボディなしで動く場合が書いてあります。
  • 影響の範囲:mruby_enable_read_request_body onの設定で、mruby_set*のハンドラ、logハンドラ、出力フィルタがリクエストボディを読むものです。2.7.1では、これらのハンドラは次のボディを受け取りません。それは、chunkedのボディ、HTTP/2かHTTP/3で届くボディ、ヘッダと一緒にnginxのヘッダのバッファに収まらないボディ、ヘッダの後に届くボディです。ただし、前のハンドラかモジュールがボディを読んでいた場合は受け取ります。2.7.0では、これらのボディのうちいくつかを、すぐに読めていました。たとえば、ヘッダと一緒に届いたchunkedのボディや、既に届いていたもっと大きなボディです。
  • 必要な対応:これらのハンドラにボディ全体を渡すには、これらより前に動く、待てるハンドラで、先にボディを読んでください。たとえば、mruby_enable_read_request_body onを付けたserverレベルのmruby_post_read_handler_codeです。そのハンドラが動いた後は、後に動くハンドラにとって、ボディはそろっています。
  • テスト:test/t/cases/request_body_later.rbの、ポート18148とポート18149のテストです。

7. Nginx::SSLはハンドシェイクのハンドラの中だけで動きます

  • 変更前:Nginx::SSLのメソッドをmruby_ssl_handshake_handler*の外で呼ぶと、ワーカーがクラッシュするか、意味の無い値が返ることがありました(#339)。対象のメソッドは、Nginx::SSL.new、#servername、証明書のセッター、#local_port、#tls_version、Nginx::SSL.logです。ドキュメントでは、この使い方はサポートの対象外でした。コードがNginx::SSL.newを呼ばないハンドシェイクは、同じワーカーの前のハンドシェイクが設定した証明書を受け取ることがありました。前のハンドシェイクが使った接続のメモリが再利用されていたときは、ハンドシェイクが失敗することもありました。
  • 変更後:ハンドシェイクのハンドラの外では、RuntimeErrorが発生します。メッセージはNginx::SSL can only be used in mruby_ssl_handshake_handlerです。コードが証明書を設定しないハンドシェイクは、サーバーのssl_certificateとssl_certificate_keyを使います。Nginx::SSL.newを呼ばないハンドシェイクも、これに含まれます。
  • 変更の理由:
    • 不具合:「変更前」に書いたとおり、ハンドシェイクのハンドラの外では、Nginx::SSLでワーカーがクラッシュするか、意味の無い値が返ることがありました(#339)。コードがNginx::SSL.newを呼ばないハンドシェイクは、前のハンドシェイクの証明書を受け取るか、失敗することがありました。
    • 前の挙動を残せなかった理由:ハンドシェイクの外には接続もサーバー名も無いので、メソッドには返せる正しい値がありません。また、後のハンドシェイクが前のハンドシェイクの状態を受け取らないように、ハンドシェイクの状態は、ハンドシェイクが終わるときにクリアしなければなりません。
    • ドキュメントが示していた挙動:ドキュメントには2.1.4から、Nginx::SSLはハンドシェイクのハンドラで使うもので、ほかのハンドラでは動かないと書いてあります(2.7.0のNginx::SSL Class)。また、ssl_certificateは、証明書を選ばないハンドシェイクにnginxが使う証明書です。
  • 影響の範囲:ハンドシェイクのハンドラの外でNginx::SSLを呼ぶハンドラと、一部のハンドシェイクでNginx::SSL.newを呼ばないハンドシェイクのハンドラです。前者の例は、servernameを読むcontentハンドラです。後者の例は、条件によって早く戻るコードや、オブジェクトを一度だけ作って持ち続けるコードです。毎回のハンドシェイクでNginx::SSL.newを呼ぶハンドシェイクのハンドラは、証明書の変更の影響を受けません。
  • 必要な対応:Nginx::SSLは、ハンドシェイクのハンドラの中でだけ呼んでください。値を後で使うには、そこで値を保存してください。たとえば、ドキュメントの例のようにUserdataを使います。ハンドラが一部のハンドシェイクでだけ証明書を設定し、ほかのハンドシェイクでNginx::SSL.newを呼んでいない場合、そのほかのハンドシェイクは、いまはssl_certificateを受け取ります。
  • テスト:test/t/ngx_mruby.rbの、ポート18089とポート18090のテストです。

8. リクエストの外でリクエストのメソッドを呼ぶと、RuntimeErrorが発生します

mruby_init*、mruby_init_worker*、mruby_exit_worker*、mruby_ssl_handshake_handler*、mruby_server_context_handler_codeのコードは、リクエストの外で動きます。mruby_init*とmruby_server_context_handler_codeはnginxが設定を読む間に動き、ほかはワーカーの中で動きます。streamモジュールでは、init、init worker、exit worker、server contextのコードが、セッションの外で動きます。この項目は2つの部分に分かれます。

リクエストの外では、リクエストのメソッド、セッションのメソッド、Nginx.logの挙動が変わります。

  • 変更前:リクエストスコープのメソッドは、ワーカーが最後に処理したリクエストを持ち続けるポインタから、いまのリクエストを探していました。
    • まだリクエストを処理していない場所では、これらのメソッドを呼ぶとクラッシュしました。mruby_init*とmruby_server_context_handler_codeでは、設定を読んでいる最中のnginx自身がクラッシュし、mruby_init_worker*ではワーカーがクラッシュしました。
    • mruby_exit_worker*とmruby_ssl_handshake_handler*では、ワーカーが最後に処理したリクエストを読みました。そのリクエストのメモリは既に解放されていることがあり、その場合は意味の無いデータを読むか、クラッシュしました。ワーカーがまだリクエストを処理していないとき、たとえば最初のハンドシェイクでは、mruby_init_worker*と同じくクラッシュしました。
    • Nginx.logとNginx.errloggerでは、まだリクエストを処理していない場所でRuntimeErrorが発生しました。そのため、mruby_init*とmruby_server_context_handler_codeでは、設定が無効になりました。ワーカーが既にリクエストを処理していた場合は、最後に処理したリクエストを通してログを書いていました。
    • streamモジュールの、init、init worker、exit workerのコードにも、同じ問題がありました。
  • 変更後:リクエストの外では、リクエストスコープのメソッドでRuntimeErrorが発生します。メッセージはthis method can only be used while processing a requestです。対象は、Nginx::Request、Nginx::Var、Nginx::Headers_in、Nginx::Headers_out、Nginx::Connection、Nginx::Server、Nginx::Filter、Nginx::Upstream、Nginx::Asyncのメソッドと、Nginx.rputs、Nginx.echo、Nginx.return、Nginx.send_header、Nginx.status_code=、Nginx.redirectです。Nginx::Serverのうち、add_listenerは対象から外れます。nginxが設定を読む間に動くコードでは、そこでのほかの例外と同じく、コードがこの例外をrescueしなければ、設定は無効になります。Nginx.logとNginx.errloggerは、リクエストの外ではnginxのエラーログに書きます。streamのinit、init worker、exit worker、server contextのコードでは、Nginx::Stream::Connection.new、そのメソッドのうちセッションを読むもの、Nginx::Stream::Async.sleepで例外が発生します。メッセージはthis method can only be used while processing a stream sessionです。Nginx::Stream::Connection.stream_statusとstream_status=では、例外は発生しません。Nginx::Stream.logは、nginxのエラーログに書きます。
  • 変更の理由:
    • 不具合:「変更前」に書いたとおり、リクエストの外では、リクエストスコープのメソッドでnginxかワーカーがクラッシュするか、ワーカーが最後に処理したリクエストが使われました。Nginx.logとNginx.errloggerでは、例外が発生するか、そのリクエストを通してログが書かれました。
    • 前の挙動を残せなかった理由:リクエストの外には返すべきリクエストが無いので、メソッドはエラーを伝えなければなりません。前の結果は、クラッシュか、ほかのリクエストのデータでした。Nginx.logはリクエストを必要としないので、そこではnginxのエラーログに書きます。
    • ドキュメントが示していた挙動:ドキュメントは、リクエストのメソッドを、リクエストのハンドラの中でだけ示しています。上に挙げたコードは、どのリクエストにも属さずに動きます。2.7.0のドキュメントには、Nginx.errloggerについて「Sends an error to the log file」と書いてあり、使えるハンドラを限る記述はありません(2.7.0のNginx.errlogger)。Nginx.logは、Nginx.errloggerのエイリアスです。
  • 影響の範囲:リクエストのデータを使う、init、init worker、exit worker、server context、ハンドシェイクのコードです。このようなコードは、前から確実には動きませんでした。そこでNginx.logの例外に頼っていたコードも、影響を受けます。
  • 必要な対応:リクエストのデータは、リクエストのハンドラの中でだけ使ってください。上に挙げたコードでは、いまはNginx.logを使えます。
  • テスト:test/t/ngx_mruby.rbの、ポート18080でmruby_init_worker_codeを試すテストと、ポート18089でハンドシェイクのハンドラを試すテストです。

add_listenerは、server contextのコードの中でだけ使えます。

  • 変更前:nginxが設定を読み終えた後、たとえばリクエストのハンドラでNginx::Server#add_listenerを呼ぶと、もう有効でない設定のデータが使われました。Nginx::Stream.add_listenerは、streamのセッション(mruby_stream_code)か、streamのinit、init worker、exit workerのコードで呼ぶと、streamモジュールの内部のコンテキストをサーバーの設定と取り違えました。この内部のコンテキストは、いまのセッションを持つものです。その結果、プロセスがクラッシュしました。mruby_stream_server_context_codeが動く間は、Nginx::Stream.logとセッションのメソッドが、サーバーの設定をこの内部のコンテキストと取り違えていました。
  • 変更後:mruby_server_context_handler_codeの外でNginx::Server#add_listenerを呼ぶと、RuntimeErrorが発生します。メッセージはadd_listener can only be used in mruby_server_context_handler_codeです。mruby_stream_server_context_codeの外でNginx::Stream.add_listenerを呼ぶと、RuntimeErrorが発生します。メッセージはadd_listener can only be used in mruby_stream_server_context_codeです。どちらのメソッドも、そのコードの中では、nginxが設定を読む間にこれまでどおり動きます。mruby_stream_server_context_codeでは、streamのinitとworkerのコードと同じく、Nginx::Stream.logはnginxのエラーログに書き、セッションのメソッドでは例外が発生します。
  • 変更の理由:
    • 不具合:「変更前」に書いたとおり、server contextのコードの外でadd_listenerを呼ぶと、もう有効でない設定のデータが使われるか、プロセスがクラッシュしました。mruby_stream_server_context_codeでは、Nginx::Stream.logとセッションのメソッドが、サーバーの設定をstreamモジュールの内部のコンテキストと取り違えていました。
    • 前の挙動を残せなかった理由:add_listenerは、nginxの設定にリスナーを足します。nginxが設定を変えられるのは設定を読む間だけなので、server contextのコードの外では例外が発生します。mruby_stream_server_context_codeは、nginxが設定を読む間に、どのセッションにも属さずに動きます。そのため、streamのinitとworkerのコードと同じく、そこではセッションのメソッドで例外が発生し、Nginx::Stream.logはnginxのエラーログに書きます。
    • ドキュメントが示していた挙動:2.7.0のドキュメントは、設定の中のNginx::Server#add_listenerを、mruby_server_context_handler_codeの中でだけ示しています(Nginx::Server#add_listener)。Nginx::Stream.add_listenerの説明は、その例を参照しています(Nginx::Stream.add_listener)。ほかのどこで呼べるかは、書いてありません。mruby_stream_server_context_codeについては、何も書いてありません。
  • 影響の範囲:server contextのコードの外でadd_listenerを呼ぶコードと、Nginx::Stream.logかセッションのメソッドを呼ぶmruby_stream_server_context_codeです。前者のコードは、前から動きませんでした。
  • 必要な対応:add_listenerは、server contextのコードの中でだけ呼んでください。mruby_stream_server_context_codeにはセッションが無いので、そこではセッションのメソッドを呼ばないでください。
  • テスト:ポート18080のテストは、test/t/ngx_mruby.rbで、contentハンドラの中のNginx::Server#add_listenerを試します。ポート12357のテストは、2つ目のnginxで、セッションの中のNginx::Stream.add_listenerを試します。2つ目のnginxはtest/t/cases/_second_instance.rbが起動し、test/t/cases/stream.rbはtest/t/cases/_prelude.rbのsecond_instanceでそれを呼びます。

9. 後のハンドラがmruby_setの変数を上書きしなくなりました

  • 変更前:mruby_setかmruby_set_codeがリクエストの中で動いた後、同じリクエストの後のハンドラがNginx::Async.sleepから再開すると、そのハンドラの最後の式が、その変数に代入されました。serverレベルのmruby_setやmruby_set_codeでも、同じでした。
  • 変更後:変数に代入されるのは、そのmruby_setのハンドラ自身の結果だけです(#548)。自分でsleepするmruby_set_codeは、これまでどおり、再開したときに変数を設定します。
  • 変更の理由:
    • 不具合:mruby_setは、変数の名前をリクエストのコンテキストに保存しました。その名前を消す処理はありませんでした。そのため、リクエストの後のハンドラがNginx::Async.sleepから再開すると、ngx_mrubyはそのハンドラの最後の式を変数に書きました。たとえば、後のproxy_passが使う$backendに書きました(#548)。
    • 前の挙動を残せなかった理由:設定には、この書き込みを指示する記述がありません。残すと、関係の無いハンドラでsleepしただけで、変数が変わります。
    • ドキュメントが示していた挙動:mruby_setの変数は、そのmruby_setが設定するものです。ディレクティブのドキュメントには、「called at one of the rewrite phases to set a nginx variable」と書いてあります(2.7.0のmruby_set and mruby_set_code)。
  • 影響の範囲:mruby_set*と、Nginx::Async.sleepを使う後のハンドラを組み合わせるリクエストです。
  • 必要な対応:ありません。後のハンドラで変数を変えたいときは、Nginx::Var.new.backend = "..."のように、明示的に代入してください。
  • テスト:test/t/cases/async_set_var_target.rbのポート18123のテストです。

10. httpブロックの無い設定でもnginxが起動します

  • 変更前:ngx_mrubyを組み込んだnginxで、streamだけの設定のようにhttp {}ブロックの無い設定を使うと、起動時にすべてのワーカーがクラッシュしました。nginxは、新しいワーカーを起動し続けました。
  • 変更後:nginxが起動します(#536)。
  • 変更の理由:
    • 不具合:ワーカーの起動と終了のときに動くHTTPモジュールのフックは、HTTPモジュールのメインの設定があるかを確かめずに、その設定を読んでいました。http {}ブロックが無いとメインの設定も無く、ワーカーがクラッシュしました(#536)。
    • 前の挙動を残せなかった理由:nginxは、http {}の無い設定を受け付けます。ngx_mrubyのstreamモジュールは、既にこの場合を扱っていました。前の挙動はクラッシュなので、残すものはありません。
    • ドキュメントが示していた挙動:http {}ブロックの無い設定については、ドキュメントに何も書いてありませんでした。
  • 影響の範囲:ngx_mrubyのHTTPモジュールを組み込んだかロードしたnginxで、streamだけの設定のようにhttp {}ブロックの無い設定です。
  • 必要な対応:ありません。
  • テスト:test/t/ngx_mruby.rbのポート12399のテストです。

11. mrubyのヘッダフィルタの後でNginx.rputsを呼ぶボディフィルタで、「header already sent」がログに出なくなりました

  • 変更前:mrubyのヘッダフィルタと、コードがNginx.rputsかNginx.echoを呼ぶmrubyのボディフィルタのあるlocationでは、nginxがリクエストごとに[alert] header already sentをログに出しました。また、ボディフィルタは、ヘッダを送った後でステータスを200にしました。ドキュメントには、ボディフィルタでのこの呼び出しをサポートしないと書いてあります。クライアントはnginxが送ったステータスを受け取りましたが、logフェーズには200が見えていました。logハンドラとlog_formatの$statusは、404のレスポンスでも200を読みました。
  • 変更後:nginxはこのアラートをログに出さず、logフェーズには、nginxが送ったステータスが見えます。レスポンスは前と同じです(#563)。ただし、ボディフィルタがボディの長さを変える場合は、レスポンスが変わります。この場合は、項目2の4つ目の部分に書きました。
  • 変更の理由:
    • 不具合:ボディフィルタは、コードの最後でNginx.rputsの出力を送るときに、応答するハンドラのためのコードパスを使っていました。このコードパスでヘッダが2回目に送られ、ステータスが200になりました(#563)。
    • 前の挙動を残せなかった理由:このコードパスを残すと、「変更前」に書いたとおり、リクエストごとに[alert] header already sentの行が出続けます。また、logフェーズで見えるステータスが、nginxが送ったステータスと違ったままになります。locationにmrubyのヘッダフィルタがあるときは、ボディフィルタはもうこのコードパスを通りません。ボディフィルタでのNginx.rputsの出力は、前と同じく破棄します。
    • ドキュメントが示していた挙動:ドキュメントには、Nginx.rputsとNginx.echoは出力のボディフィルタでは使えないと書いてあります。その記述は「You can NOT use Nginx.rputs and Nginx.echo in the output body handlers」です(2.7.0のNginx::Filter Class)。logフェーズが見るステータスについては、何も書いてありませんでした。
  • 影響の範囲:mruby_output_header_filterかその_codeの形と、mruby_output_body_filterかその_codeの形があり、ボディフィルタがNginx.rputsかNginx.echoを呼ぶlocationです。それらのリクエストの$statusかheader already sentの行を読む、アクセスログ、logハンドラ、アラートも影響を受けます。
  • 必要な対応:ログの統計かアラートが、それらのリクエストのステータス200かheader already sentの行に頼っている場合を除き、ありません。
  • テスト:test/t/cases/output_filters_with_content_handler.rbのポート18138のテストです。

12. 応答の前に、読まれていないリクエストボディを破棄します

  • 変更前:ハンドラがリクエストボディを読まずにNginx.rputsかNginx.echoで応答すると、ボディが接続に残りました。たとえば、mruby_enable_read_request_bodyなしでPOSTに応答するcontentハンドラやrewriteハンドラが、これに当たります。nginxが次のリクエストのために開いておく接続、つまりHTTP/1.1のkeep-aliveの接続では、nginxはそのボディを次のリクエストの始まりとして読みました。
  • 変更後:ngx_mrubyは、そのようなハンドラの応答を送る前に、どのハンドラも読んでいないリクエストボディを破棄します。nginxも、return、エラーページ、静的ファイルのような自分のレスポンスの前に、同じようにボディを破棄します。接続の次のリクエストは、クライアントがボディの後に送ったリクエストになります。ボディを破棄できない場合は、nginxは応答の後に接続を閉じます。Nginx::Async.sleepの後でrewriteハンドラが送る応答も、同じです。ハンドラが読んだボディは、影響を受けません。
  • 変更の理由:
    • 不具合:nginxは、リクエストに応答するハンドラが、先にリクエストボディを読むか破棄すると想定しています。開いたままの接続では、次のリクエストがボディの後から始まるからです。nginx自身のハンドラは、これをしています。ngx_http_send_response、エラーページ、staticモジュールがそうです。mrubyのハンドラの応答は、これをしていませんでした。
    • 前の挙動を残せなかった理由:「変更前」に書いたとおり、接続に残ったボディは、次のリクエストの始まりとして読まれます。ボディを破棄すれば、ハンドラが必要としないボディのために応答を待たせずに、接続を使える状態に保てます。
    • ドキュメントが示していた挙動:どのハンドラも読まないリクエストボディについては、ドキュメントに何も書いてありませんでした。
  • 影響の範囲:POSTやPUTのようにボディのあるリクエストに、ボディを読まずにNginx.rputsかNginx.echoで応答するハンドラのうち、nginxが次のリクエストのために開いておく接続で応答するものです。
  • 必要な対応:ありません。ボディが必要なハンドラは、これまでどおりmruby_enable_read_request_body onでボディを読みます。
  • テスト:test/t/cases/unread_request_body.rbのポート18151のテストです。contentハンドラ、rewriteハンドラ、Nginx::Async.sleepの後で応答するrewriteハンドラを試します。

13. contentハンドラが出力なしで終わると、レスポンスは500になります

  • 変更前:メインリクエストのmruby_content_handler*が出力なしで終わり、ステータスを設定していないか、200、201、204以外の300未満のステータスを設定していると、レスポンスが送られませんでした。ステータスを設定していない場合とは、何も書かない場合、Nginx.rputsで""かnilだけを書く場合、レスポンスヘッダだけを設定する場合です。300未満のステータスの例はNginx::HTTP_ACCEPTEDです。Nginx::Async::HTTP.sub_requestが再開した後にこのように終わった場合も、同じでした。nginxは、HTTP/1.0の接続を1バイトも送らずに閉じ、HTTP/1.1のkeep-aliveの接続を、keepalive_timeoutまでレスポンスなしで開いたままにしました。keepalive_timeoutのデフォルトは75秒です。そのため、クライアントは自分のタイムアウトまで待ちました。
  • 変更後:そのようなリクエストには500が返ります。そのボディはnginxのエラーページか、500に設定したerror_pageで、ヘッダにはConnection: closeが付きます。これは、出力なしでNginx.return Nginx::HTTP_OKを呼んだ場合に、2.7.0でも既に返っていた応答と同じです(#566)。error.logには、errorレベルの行が出ます。その行は、status code is not set, and response body is empty. return NGX_HTTP_INTERNAL_SERVER_ERRORか、status code is <N>, but response body is empty. return NGX_HTTP_INTERNAL_SERVER_ERRORです。
  • 変更の理由:
    • 不具合:nginxは、201、204、300以上のステータスには、自分でレスポンスを送ります。しかし、ステータスが300未満で201と204以外のときと、ステータスが設定されていないときは、何も送らずにリクエストを終えます。出力の無いハンドラは、そのような値をそのままnginxに渡していました。レスポンスの無いリクエストは、不具合です(#225)。クライアントは自分のタイムアウトまで待たされ、keep-aliveの接続が無駄に占有されます。
    • 前の挙動を残せなかった理由:残すと、これらのリクエストはレスポンスの無いままになります。2.x系列では、これらのリクエストに、出力なしのNginx::HTTP_OKに既に返していたのと同じ応答を返します。そのため、2.7.0でレスポンスを受け取っていたリクエストが、違うレスポンスを受け取ることはありません。
    • ドキュメントが示していた挙動:出力なしで終わるcontentハンドラについては、ドキュメントに何も書いてありませんでした。Nginx.returnについては、「Returns nginx status code to send back HTTP status to the client」と書いてあります(2.7.0のNginx.return)。2.7.1では、202のようなステータスを出力なしで返すと、500になります。2.7.0でも、出力なしの200は、既に500になっていました。
  • 影響の範囲:出力なしで終わることのあるmruby_content_handler*のハンドラと、これらの行を見るログの監視です。ハンドラの例は、条件が成り立つときだけ書くハンドラや、空かnilになりうる値をNginx.rputsに渡すハンドラです。status code is 200, but response body is emptyに一致させるパターンは新しい行に一致せず、response body is emptyに一致させるパターンでは、新しい行も数に入ります。
  • 必要な対応:空のボディで応答すべきハンドラは、Nginx.return Nginx::HTTP_NO_CONTENTを呼ぶか、ボディを書いてください。Nginx::HTTP_NO_CONTENTの場合は、nginx自身が204で応答します。拒否するつもりのハンドラは、Nginx::HTTP_FORBIDDENやNginx::HTTP_UNAUTHORIZEDのように、意図したステータスを返してください。status code is 200, but response body is emptyに一致させるログの監視は、新しい行も見えるように、response body is empty. return NGX_HTTP_INTERNAL_SERVER_ERRORに一致させてください。
  • このリリースで変わらない挙動:出力なしのNginx::HTTP_OKは、前と同じく500です。201、204、300以上のステータスは、nginx自身が応答します。出力のあるハンドラ、Nginx.redirect、ほかの種類のハンドラ、サブリクエストも変わりません。Nginx::Async::HTTP.sub_request、SSIのinclude、auth_requestには、前と同じサブリクエストのステータスが見えます。出力を書いてから、200、201、204以外の300未満のステータスを設定するcontentハンドラは、これまでどおりレスポンスを送りません。たとえば、Nginx.rputs "x"の後にNginx.return Nginx::HTTP_ACCEPTEDを呼ぶ場合です。この件は、「既知の制限」の節に書きました。
  • テスト:test/conf/conf.d/54-content-empty-body.confとtest/t/cases/content_empty_body.rbの、ポート18136のテストです。

14. nginxがボディの読み込みを打ち切った後は、待っていたハンドラが動かなくなりました

mruby_enable_read_request_body onのとき、post-read、server rewrite、rewrite、access、contentのハンドラは、リクエストボディの残りを待ちます(項目6)。nginxは、ボディの残りを受け取らずに、その読み込みを打ち切ることがあります。それは、client_body_timeoutが切れたとき、クライアントが接続を閉じたとき、nginxがボディに400か413で応答したときです。400で応答する例は、不正なchunkedのボディです。この項目では、そのようなリクエストでその後に動く、mrubyのlogハンドラとmrubyの出力フィルタについて書きます。

  • 変更前:待っていたハンドラがpost-readハンドラかaccessハンドラのとき、そのようなlogハンドラやフィルタは、自分でボディの読み込みを始めました。その読み込みによって、待っていたハンドラのコードが、nginxが既に応答を決めた後に動きました。このコードは、それまで動いていませんでした。client_body_timeoutの後や、クライアントが接続を閉じた後は、accessハンドラのコードがlogフェーズの間に動きました。不正なchunkedのボディの後は、nginxが400エラーページを送る間にそのコードが動きました。Content-Lengthはページ1回分の長さなのに、レスポンスにはページが2回入りました。Content-Lengthは157バイトで、送ったのは314バイトでした。待っていたハンドラがserver rewrite、rewrite、contentのハンドラのときは、2.7.0ではリクエストがまったく終わりませんでした(項目6)。そのため、このlogハンドラやフィルタは動きませんでした。
  • 変更後:logハンドラやフィルタは、読み込みを始めずに、すぐに動きます。Nginx::Request#bodyは、ボディのうち、nginxが読み込みを打ち切る前に読んだ部分を返します。その部分がnginxのボディのバッファ(client_body_buffer_size)に収まらず、nginxが一時ファイルに書いていた場合は、nilを返します。error.logには、項目6のinfoの行が出ます。その行はthe request body is not complete and a log handler cannot wait for it, so it runs without the bodyで、フィルタでは、a log handlerの部分がa header filterかa body filterになります。待っていたハンドラのコードは動きません。client_body_timeoutの後は、nginxはレスポンスなしで接続を閉じ、アクセスログには408が記録されます。クライアントが接続を閉じた後は、アクセスログに400が記録されます。不正なchunkedのボディの後は、クライアントはnginxの400エラーページを1回だけ受け取り、nginxは接続を閉じます。
  • 変更の理由:
    • 不具合:リクエストボディの読み込みが既に始まっているとき、nginxは、新しい読み込みの完了ハンドラをすぐに呼びます。ngx_mrubyの完了ハンドラは、待っているハンドラのために、リクエストのフェーズを動かし直します。そのため、nginxが最初の読み込みを打ち切った後に読み込みを始めたlogハンドラやフィルタは、logフェーズから、またはレスポンスの途中から、それらのフェーズを動かし直しました。
    • 前の挙動を残せなかった理由:nginxが打ち切った読み込みは完了しないので、待っているハンドラには、動くためのボディがありません。また、nginxは既にリクエストに応答したか、リクエストを閉じています。そのときにそのハンドラのコードを動かすと、終わったリクエストのために、アクセスチェックやログの行のような処理をし、nginxのエラーページを2回目に送りました。logハンドラやフィルタはボディを待てないので(項目6)、自分で読み込みを始めずに、nginxが読んだもので動きます。
    • ドキュメントが示していた挙動:2.7.0のこのディレクティブのドキュメントには、ngx_mrubyが「reads a HTTP request body before calling mruby code」と書いてありました(mruby_enable_read_request_body)。nginxがボディ全体を読まずに打ち切る読み込みについては、何も書いてありませんでした。
  • 影響の範囲:mruby_enable_read_request_body onの設定のうち、post-readハンドラかaccessハンドラがボディを読み、同じリクエストでmrubyのlogハンドラかmrubyの出力フィルタも動くものです。対象は、nginxがボディの読み込みを早く打ち切るリクエストで、client_body_timeout、閉じた接続、ボディへの400か413の応答がこれに当たります。
  • 必要な対応:ありません。ボディを待つハンドラのコードは、ボディ全体を受け取って1回だけ動きます。ボディがそろう前にnginxが読み込みを打ち切ったときは、動きません。
  • テスト:test/t/cases/request_body_later.rbのポート18152のテストです。待っているrewriteハンドラについて、client_body_timeoutの後のlogハンドラと、不正なchunkedのボディを受けた後のヘッダフィルタとボディフィルタを試します。

Release notes