Ruby hook (Y1)
Ready
The hub proposes this hook for the containers it fits, and nothing changes until a player approves the proposal (Hook proposals). The cheat sheet has the steps by hand.
For Ruby web services: Rack servers (Puma, Unicorn, Falcon, Thin, WEBrick, Iodine, Agoo) and the frameworks on top of them (Rails, Sinatra, Roda, Hanami, Grape), plus any Ruby process the service starts. It gets in compose-only: a read-only mount of vulnboxd's hook directory and one -r added to RUBYOPT. The image, the Gemfile and the source stay untouched. The hook is plain Ruby with no dependencies outside the standard library. It reaches the core library through fiddle.
Covers
| Versions | |
|---|---|
| Ruby (MRI / CRuby) | 2.7–3.4 and 4.0, glibc and musl (Alpine), x86_64 and aarch64 |
| Puma | 5, 6, 7 (single and cluster mode, threads) |
| Unicorn | 5, 6 |
| Falcon (async-http, fiber scheduler) | 0.4x and later, HTTP/1 and HTTP/2 |
| Thin (EventMachine) | 1.8 |
WEBrick through Rack's handler (Rack::Handler::WEBrick, Rackup::Handler::WEBrick) | 1.x |
| Iodine, Agoo | current releases (context only, see Known gaps) |
| Rails | 6.1–8 (Rails::Application#call and config.ru) |
Sinatra (classic ruby app.rb and modular), Roda, Hanami (router + actions), Grape | current releases |
| Rack | 2.2 and 3.x |
Which servers the kernel already links exactly, without this hook:
- Unicorn (and Puma in cluster mode with one thread per worker): one worker process serves one client socket at a time, so the sensor's "unambiguous ownership" rule links everything the worker does. The hook only adds explicit request boundaries.
- Puma with threads, WEBrick: each request runs start to finish on one thread that owns one client socket, so the kernel's thread rule applies too. The hook adds request boundaries on keep-alive connections, and links work the request hands to threads it starts.
- Falcon, Thin, Iodine, Agoo: one thread (a fiber scheduler, an EventMachine reactor, or a C reactor with Ruby worker threads) serves many connections. The kernel cannot tell requests apart, so the hook is required.
How it gets in
From a registry (local development, or a build with network; the same release as the hook directory): gem install vbxtrace -v 1.0.0 (or gem "vbxtrace", "1.0.0", require: false), then RUBYOPT=-rvbxtrace; see Local development.
Compose-only (default). The hub proposes:
services:
<service>:
+ volumes:
+ - /usr/local/lib/vulnboxd/trace:/opt/vbxtrace:ro
+ environment:
+ RUBYOPT: "-r/opt/vbxtrace/ruby/vbxtrace.rb"If the service already sets RUBYOPT, the hook is appended with a space (RUBYOPT: "-W0 -r/opt/vbxtrace/ruby/vbxtrace.rb"). If the compose file uses the list form of environment, the same entry is added as - RUBYOPT=-r/opt/vbxtrace/ruby/vbxtrace.rb. To apply it by hand, add the two blocks and run docker compose up -d <service>.
The hub proposes this when it detects any of: a Gemfile, Gemfile.lock, gems.rb, config.ru or *.gemspec in the service directory; a ruby:*, bitnami/ruby, phusion/passenger-* or rails:* base image; puma, unicorn, falcon, thin, rackup, rails server, bundle exec, iodine, agoo or ruby in the command or entrypoint; or one of rack, puma, unicorn, falcon, thin, webrick, iodine, agoo, rails, sinatra, roda, hanami, grape in the lockfile. (Templates: hooks/ruby/y1/proposals/compose.toml.)
Source change (fallback). Some entrypoints reset RUBYOPT or start Ruby through a wrapper that drops the environment. For those, the hub offers the same mount plus one line at the top of config.ru:
+require "/opt/vbxtrace/ruby/vbxtrace" if File.exist?("/opt/vbxtrace/ruby/vbxtrace.rb")
require_relative "config/environment"Loaded this way, the hook misses whatever runs before config.ru (nothing that matters for requests). Rack::Builder is already defined at that point and gets wrapped straight away.
Bundler and load order
RUBYOPT=-r… loads the hook before the application, and usually before Bundler. Both orders work, and the samples check both:
bundle exec puma …: Bundler adds its own-rbundler/setupin front ofRUBYOPT, so Bundler sets up first and the hook loads second.- A binstub (
bin/puma),ruby -rbundler/setup,rails serverfrom a binstub, or a plainruby app.rbthat callsBundler.setupitself: the hook loads first.
Loading early used to be the risky case. If the hook had activated a gem before Bundler.setup and the application's Gemfile.lock pinned a different version, Bundler would refuse to boot ("You have already activated …"). The hook therefore activates no gems at all:
- It requires nothing but
fiddle, and loads it without RubyGems' activation. While fiddle loads, everyrequiregoes to RubyGems'gem_original_require(a plain$LOAD_PATHlookup), with fiddle's own directories put temporarily in front of$LOAD_PATH. Afterwards$LOAD_PATHis restored, andGem.loaded_specscontains nofiddle. Up to Ruby 3.4 those directories are the standard library directories, where fiddle is a default gem. From Ruby 4.0, fiddle is a bundled gem, so they are the installed gem'sliband extension directories, found through its gemspec. Bundler would hide that gem from an application whose Gemfile does not list it. - It never requires
socket,rackor any server itself. Their wrappers are installed when the application loads them. On Ruby ≥ 3.2 that is detected throughModule#const_added; on all versions, also whenrequirereturns. The lookup never triggers anautoload.
The unicorn sample pins a fiddle version different from Ruby's default gem, and starts through a binstub (hook first, then Bundler.setup). The alpine-ruby40 sample runs Ruby 4.0 under bundle exec with fiddle missing from the Gemfile.
What it records
| Event | Emitted from | Join key |
|---|---|---|
request_begin / request_end | a Rack middleware the hook wraps around the app: Rack::Builder#to_app (every config.ru, Sinatra's own stack, rails server, Falcon, Iodine, rackup) and Rails::Application#call. request_end fires when the app returns, with the response status (0 when the app raised). | the accepted socket's local port, peer address and port, and the request index on that connection |
spawned | Process.spawn, Kernel#spawn (and through it Open3.*), Kernel#system, backticks / %x{}, IO.popen (also with a block, before the block runs), fork, PTY.spawn | child pid (system and backticks: from $? after the call) |
connected | TCPSocket.new/open (net/http, most clients), Socket#connect and #connect_nonblock (Socket.tcp, Addrinfo#connect, async-io / io-endpoint), UDPSocket#connect, a UDPSocket's first send to an address | the socket's local port, from getsockname |
opened | File.new / File.open / Kernel#open on a path / Tempfile (all through File#initialize), IO.sysopen | pid + fd. Flags as Ruby passes them to open(2): the mode's flags plus O_CLOEXEC, so File.open(p, "w") reports 0x80241 |
context_enter / context_exit | around IO.read, IO.write, IO.binread, IO.binwrite, IO.readlines, IO.foreach, IO.copy_stream (and the File. forms). These open and close the file inside the call, so no fd is left to report; only when no fiber scheduler is set on the thread | the thread, between the two events |
handoff | VbxTrace.handoff (an API for code that moves work somewhere context does not follow) | the two context ids |
Events only fire while a request context is current; outside requests (boot, a Unicorn master forking workers) the wrappers do nothing beyond the check.
Which connection a request came on, per server:
| Server | Connection | Request index |
|---|---|---|
| Puma | env["puma.socket"] (TLS: the MiniSSL::Socket is unwrapped with #to_io) | counted per socket (keep-alive order) |
| Unicorn | env["unicorn.socket"] | always 0 (no keep-alive) |
| WEBrick | the request's socket, made current while the Rack handler's service runs | counted per socket |
| Thin | the Thin::Connection, made current while pre_process runs; endpoints from EventMachine's get_sockname / get_peername | counted per connection |
| Falcon | the peer socket of Async::HTTP::Server#accept, inherited by the connection's request fibers | HTTP/1: counted per connection; HTTP/2: (stream id - 1) / 2 (stream order) |
| Iodine, Agoo | none: neither gives Ruby the socket, its fd or the peer port | VBX_REQUEST_INDEX_UNKNOWN (request_index=unknown), with local_port=0 and no peer |
Endpoints are read once per connection (getsockname, getpeername), not per request. The per-connection state lives in an ObjectSpace::WeakKeyMap on Ruby ≥ 3.3, and in an instance variable on the socket or connection object before that.
Protocol: http1 / http2 / http3 from SERVER_PROTOCOL, grpc for HTTP/2 with an application/grpc content type, websocket when the request asks to upgrade to WebSocket.
Context following
The current request is kept in fiber storage (Fiber[]) on Ruby ≥ 3.2. Ruby copies fiber storage into every fiber and thread created from the request, so the context follows automatically:
Thread.new/Thread.startinside a request (the/threadendpoint of every sample);- Async tasks and fibers the request starts (Falcon's
/async), and the request's own fibers across scheduler switches: a request that sleeps or waits on I/O and resumes later still reports under its own context (Falcon's/sleepy); - HTTP/2 streams on Falcon, which run in child fibers of the connection.
A copy is per fiber, so a value set in a child never leaks back to the request or to another request on the same thread.
On Ruby 2.7–3.1 fiber storage does not exist. The context is fiber-local (Thread.current[]), and the hook wraps Thread.new / start / fork to carry the context into new threads (the puma-ruby27 sample checks this). Fibers a request creates on these versions start without context.
For work handed to something the runtime does not follow (a job queue, a thread pool fed from a queue), use the API (/opt/vbxtrace/ruby/vbxtrace.rb defines it once loaded; guard with defined?(VbxTrace)):
child = defined?(VbxTrace) ? VbxTrace.handoff : nil # in the request
# ... later, in the worker:
VbxTrace.with_context(child) { run_job } if child # events inside carry childKnown gaps
- Iodine and Agoo are C servers that pass Ruby neither the client socket, its fd nor the peer's port (only
REMOTE_ADDR). The hook still opens a context per request, sospawned/connected/openedcarry it and are grouped per request. Butrequest_beginhas no peer (local_port=0, request indexVBX_REQUEST_INDEX_UNKNOWN), so the sensor cannot join the context to the client connection. Their C reactor threads also defeat the kernel's thread rule. A fix needs the servers to expose the fd or peer port in the env. - Native extensions doing their own I/O bypass the Ruby wrappers:
pg,mysql2,hiredis,curb,grpcandtyphoeusconnect from C. On thread-per-request servers the kernel's thread rule still links them; on Falcon/Thin they stay unlinked. (net/http,redis-clientin pure-Ruby mode,httpx,async-httpandfaradayon net/http go throughTCPSocket/Socket#connectand are covered.) IO.read& co. under a fiber scheduler: no fd survives these calls, andcontext_enter/context_exitis not exact when another fiber may run in between. So on Falcon, files read or written withFile.read/File.writeare not linked.File.openis.- Streaming bodies:
request_endfires when the app returns. Work done while the server iterates the body afterwards runs with the previous context restored, so it is not attributed to the request. Kernel#open("|cmd"),IO.read("|cmd")and other pipe forms of the file methods start a process without reportingspawned. With no fiber scheduler,IO.read("|cmd")still falls betweencontext_enterandcontext_exit, so the sensor links the fork by thread.- Fibers created by a request on Ruby < 3.2 (see above).
- If an application loads a different fiddle version from its own bundle after the hook (an app that uses fiddle itself and pins it), Ruby loads that fiddle's files over the hook's. That prints "already initialized constant" warnings. Behaviour is otherwise unchanged.
- JRuby and TruffleRuby are not supported (no MRI fiddle). The hook loads there but stays off.
Safety
- What is wrapped: every method listed under What it records, through
prepend(method lookup stays standard;Kernelinstance methods through a module prepended toObjectwith private copies, sorespond_to?(:system)is unchanged), plusKernel#require(to notice classes appearing),Module#const_added(Ruby ≥ 3.2) andRack::Builder#to_app. Every wrapper calls the original first, with the original arguments (keyword flags preserved withruby2_keywords) and block, and returns its result or lets its exception through unchanged. The hook's own work runs afterwards, inside a guard. - The guard catches only errors the hook's own code can raise (
NoMethodError,TypeError,SystemCallError,Fiddle::DLError, …). Anything else that arrives inside it is re-raised untouched, for example aTimeout::Erroror a rack-timeout exception delivered byThread#raise. Internal errors are counted; the fifth switches the hook off for the process.VBXTRACE_DEBUG=1reports them on stderr. - Nothing happens while no tracer is attached beyond one check per request, spawn, connect or open. The check reads the core's 16 bytes of probe semaphores straight from memory, which is cheaper than a call through fiddle. That is exactly what
vbx_v1_enabled()computes, and the kernel bumps a semaphore while a uprobe is attached. At load, the hook locates them from the library's ELF section headers and checks that the read agrees withvbx_v1_enabled(); otherwise it calls the function through fiddle (GVL kept). Wrappers other than the middleware skip even the check when no request context is current. - The env is never modified. The middleware does not add keys or callbacks to the Rack env, and does not wrap the response body: Puma's and others' fast paths for Array bodies stay untouched.
- What the application can observe: the hook's modules in
ancestors; one extra frame per wrapped call in backtraces (/opt/vbxtrace/ruby/vbxtrace/…). Therequireandconst_addedhooks are compiled under the file name<internal:vbxtrace/…>, so libraries that look for "the file that required me" skip them like RubyGems' own require frame. Without this, classic Sinatra took the hook for the application file and never started its server; thesinatrasample checks it. Also observable:Rack::Builder#to_appreturns the middleware, which forwards every other method to the app; and the instance variable@__vbxtrace_connon accepted sockets (Ruby < 3.3). VBXTRACE=0in the environment: the hook returns at once when required, before loading anything.- Tests: every sample runs with the core forced to fail (
VBXTRACE_CHAOS=1) and without the hook, and its responses must be byte-identical to the run with the hook. The driver drops only headers that change between runs by design (Date,X-Request-Id,X-Runtime,ETag,Set-Cookie). For Iodine it also sorts the headers, because Iodine's header order changes from run to run without any hook.
Overhead will be measured in the performance phase; no numbers are published for this hook yet.
Turning it off
Set VBXTRACE=0 in the service's environment and restart it, or revert the change that added the hook; vulnboxd's rollback covers a hook that breaks a service.
To remove it by hand, delete -r/opt/vbxtrace/ruby/vbxtrace.rb from RUBYOPT (and the variable if nothing else is left in it) and the /opt/vbxtrace mount. For the source-change variant, delete the require line from config.ru.
Troubleshooting
- Are the probes there?
readelf -n /usr/local/lib/vulnboxd/trace/libvbxtrace-x86_64.solists them;sudo bpftrace -l 'usdt:/usr/local/lib/vulnboxd/trace/libvbxtrace-x86_64.so:*'too. - Is the hook loaded?
grep vbxtrace /proc/<pid>/mapsinside the container showslibvbxtrace-<arch>.somapped. Thendocker compose exec <service> ruby -e 'p defined?(VbxTrace) && VbxTrace.on?'printstrue, since the exec'd process inheritsRUBYOPT. Run that withVBXTRACE_DEBUG=1to see why it is off, if it is. - Which links did a flow get? The hub shows each link's method; this package's are
hook:Y1. RUBYOPTis ignored: some entrypoints runruby --disable-gems, clear the environment, or useenv -i. Use theconfig.ruvariant. With--disable-gemsthe hook still works on Ruby ≤ 3.4 (fiddle is in the standard library there); on Ruby 4.0 it cannot find the fiddle gem and stays off.- Nothing for requests, but spawns from boot work: the app is not built through
Rack::Builder(a server started with an app object in code, e.g.Puma::Server.new(app)). Wrap it yourself:app = VbxTrace::Middleware.wrap(app) if defined?(VbxTrace). peer=-on every request: the server is not one of those in the table above (or is Iodine/Agoo). Requests are still grouped, but not joined to connections.- "already initialized constant Fiddle::…" warnings: see the fiddle note under Known gaps.