rubik 0.15.1 → 0.15.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +67 -2
  4. data/lib/rubik/ast/cache_store.rb +22 -4
  5. data/lib/rubik/ast/extractor.rb +1 -4
  6. data/lib/rubik/ast/ruby_extractor.rb +23 -1
  7. data/lib/rubik/ast/symbol.rb +9 -4
  8. data/lib/rubik/ast/treesitter/python_walker.rb +5 -4
  9. data/lib/rubik/ast/treesitter_extractor.rb +10 -3
  10. data/lib/rubik/buffer/diff.rb +34 -2
  11. data/lib/rubik/buffer/manager.rb +18 -15
  12. data/lib/rubik/buffer/path_validator.rb +18 -2
  13. data/lib/rubik/buffer/snapshot.rb +144 -9
  14. data/lib/rubik/concurrency/timers.rb +7 -0
  15. data/lib/rubik/config/scoped.rb +18 -7
  16. data/lib/rubik/config/secret_policy.rb +22 -1
  17. data/lib/rubik/config.rb +24 -26
  18. data/lib/rubik/context/ignore_rules.rb +7 -2
  19. data/lib/rubik/diagnostics/parser.rb +19 -8
  20. data/lib/rubik/kernel/dispatcher.rb +11 -5
  21. data/lib/rubik/llm/client.rb +24 -3
  22. data/lib/rubik/llm/connection_pool.rb +51 -30
  23. data/lib/rubik/llm/message_sanitizer.rb +20 -1
  24. data/lib/rubik/llm/sse_parser.rb +10 -1
  25. data/lib/rubik/lsp/client.rb +9 -2
  26. data/lib/rubik/lsp/manager.rb +43 -40
  27. data/lib/rubik/lsp/transport.rb +61 -1
  28. data/lib/rubik/mcp/transport/stdio.rb +143 -131
  29. data/lib/rubik/orchestrator/activity_log.rb +3 -2
  30. data/lib/rubik/orchestrator/goal_session.rb +14 -14
  31. data/lib/rubik/orchestrator/loop.rb +11 -12
  32. data/lib/rubik/orchestrator/subagent/completion.rb +18 -8
  33. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +5 -1
  34. data/lib/rubik/platform/process.rb +74 -19
  35. data/lib/rubik/platform.rb +16 -16
  36. data/lib/rubik/plugin/manager.rb +5 -6
  37. data/lib/rubik/repl/service_catalog.rb +1 -1
  38. data/lib/rubik/repl/terminal_guard.rb +29 -23
  39. data/lib/rubik/repl/turn_recorder.rb +35 -11
  40. data/lib/rubik/sandbox/driver/base.rb +26 -3
  41. data/lib/rubik/sandbox/driver/bubblewrap.rb +6 -11
  42. data/lib/rubik/sandbox/driver/docker.rb +1 -11
  43. data/lib/rubik/sandbox/driver/podman.rb +26 -18
  44. data/lib/rubik/sandbox/driver/process.rb +16 -35
  45. data/lib/rubik/security/blocked_guidance.rb +4 -2
  46. data/lib/rubik/security/command_gate.rb +27 -14
  47. data/lib/rubik/security/errors.rb +13 -0
  48. data/lib/rubik/security/guard.rb +11 -2
  49. data/lib/rubik/security/path_policy.rb +9 -6
  50. data/lib/rubik/storage/store.rb +31 -11
  51. data/lib/rubik/tools/builtins/exec.rb +5 -1
  52. data/lib/rubik/tools/builtins/files.rb +2 -0
  53. data/lib/rubik/tools/uri_resolver.rb +23 -3
  54. data/lib/rubik/version.rb +1 -1
  55. metadata +1 -1
@@ -48,6 +48,7 @@ module Rubik
48
48
  stderr_str = ""
49
49
  exit_code = 127
50
50
  pid = nil
51
+ child_identity = nil
51
52
  watchdog = nil
52
53
  deadline_hit = false
53
54
  timed_out = false
@@ -55,6 +56,12 @@ module Rubik
55
56
  begin
56
57
  Open3.popen3(*, chdir: chdir) do |stdin, stdout, stderr, wait_thr|
57
58
  pid = wait_thr.pid if wait_thr.respond_to?(:pid)
59
+ # Snapshot identity on the spawning thread, before either kill
60
+ # path can run. The watchdog used to snapshot it itself, but the
61
+ # outer Timeout rescue called kill_tree(pid) without identity —
62
+ # which re-snapshotted the CURRENT occupant and signaled an
63
+ # unrelated process after a PID reuse.
64
+ child_identity = process_identity(pid)
58
65
  # Deadline watchdog (issue #479): kill the tree from a separate
59
66
  # thread the moment the deadline fires, so a hung child never
60
67
  # outlives `timeout`. The kill must NOT ride Timeout.timeout's
@@ -65,7 +72,7 @@ module Rubik
65
72
  # Timeout::Error is raised only after the block has returned.
66
73
  # Cancelled in the inner ensure to keep the watchdog from firing
67
74
  # into a recycled pid after normal exit.
68
- watchdog = Thread.new(pid, timeout.to_f) do |w_pid, w_deadline|
75
+ watchdog = Thread.new(pid, timeout.to_f, child_identity) do |w_pid, w_deadline, w_identity|
69
76
  slept = false
70
77
  begin
71
78
  sleep w_deadline
@@ -74,8 +81,10 @@ module Rubik
74
81
  # actually targets a still-live process — a child that completes
75
82
  # exactly as the deadline fires keeps its real exit status
76
83
  # instead of being relabeled exit 124.
77
- deadline_hit = true if process_alive?(w_pid)
78
- kill_tree(w_pid)
84
+ # A recycled PID is "alive" but is not our child: do not
85
+ # relabel its success as a timeout and do not signal it.
86
+ deadline_hit = true if identity_unchanged?(w_pid, w_identity) && process_alive?(w_pid)
87
+ kill_tree(w_pid, identity: w_identity)
79
88
  rescue StandardError => e
80
89
  # Issue #597-2 follow-up: a kill-path failure at the deadline
81
90
  # must never silently drop the timeout — the deadline has
@@ -135,7 +144,7 @@ module Rubik
135
144
  raise Timeout::Error, "execution expired" if deadline_hit
136
145
  rescue Timeout::Error
137
146
  timed_out = true
138
- kill_tree(pid) if pid
147
+ kill_tree(pid, identity: child_identity) if pid
139
148
  stderr_str = timeout_message || "Execution timed out after #{timeout} seconds"
140
149
  exit_code = 124
141
150
  rescue Errno::ENOENT => e
@@ -163,7 +172,7 @@ module Rubik
163
172
  }
164
173
  end
165
174
 
166
- def kill_tree(pid)
175
+ def kill_tree(pid, identity: nil)
167
176
  return unless pid&.positive?
168
177
 
169
178
  if windows?
@@ -175,13 +184,20 @@ module Rubik
175
184
  nil
176
185
  end
177
186
  else
187
+ # PID reuse guard: the deadline watchdog snapshots this identity
188
+ # before sleeping. A mismatch means the PID now names a different
189
+ # process — signal nothing rather than kill an unrelated process.
190
+ expected = identity || process_identity(pid)
191
+ return unless identity_unchanged?(pid, expected)
192
+
178
193
  # On Unix/Linux, collect descendant PIDs so child processes are not
179
194
  # orphaned when the parent process is killed. TERM gets a short
180
195
  # grace window before KILL escalates: back-to-back TERM→KILL gave
181
196
  # graceful shutdown no scheduling window, so lock/file/socket
182
197
  # holders were always hard-killed.
183
198
  targets = (descendant_pids(pid) + [pid]).uniq
184
- signal_all(targets, "TERM")
199
+ identities = targets.to_h { |tpid| [tpid, process_identity(tpid)] }
200
+ signal_all(targets, "TERM", identities)
185
201
 
186
202
  # Escalate to KILL for whatever is still alive once the grace
187
203
  # window lapses (or the loop observes all targets gone early).
@@ -190,17 +206,27 @@ module Rubik
190
206
  deadline = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) + KILL_TREE_GRACE_SECONDS
191
207
  still_alive = targets
192
208
  until ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) >= deadline
193
- still_alive = targets.select { |tpid| process_alive?(tpid) }
209
+ still_alive = targets.select { |tpid| process_alive?(tpid) && identity_unchanged?(tpid, identities[tpid]) }
194
210
  break if still_alive.empty?
195
211
 
196
212
  sleep 0.01
197
213
  end
198
- signal_all(still_alive, "KILL")
214
+ signal_all(still_alive, "KILL", identities)
199
215
  end
200
216
  end
201
217
 
202
218
  KILL_TREE_GRACE_SECONDS = 0.2
203
219
 
220
+ # PATH-resolved process helpers are a trust boundary: a poisoned PATH
221
+ # could make `pgrep`/`ps` print attacker-chosen PIDs into the kill list.
222
+ # The /proc path below is primary; these absolute locations are the only
223
+ # fallback, and every capture is deadline-bounded.
224
+ HELPER_LOCATIONS = {
225
+ "pgrep" => ["/usr/bin/pgrep", "/bin/pgrep", "/usr/sbin/pgrep", "/sbin/pgrep"],
226
+ "ps" => ["/usr/bin/ps", "/bin/ps", "/usr/sbin/ps", "/sbin/ps"]
227
+ }.freeze
228
+ HELPER_CAPTURE_TIMEOUT_SECONDS = 0.5
229
+
204
230
  # Collect all descendant process IDs recursively (leaves first).
205
231
  def descendant_pids(pid)
206
232
  return [] unless pid&.positive?
@@ -247,8 +273,12 @@ module Rubik
247
273
 
248
274
  private
249
275
 
250
- def signal_all(pids, sig)
276
+ def signal_all(pids, sig, identities = {})
251
277
  pids.each do |tpid|
278
+ # Last-moment re-check: a PID recycled after the grace window must
279
+ # never receive a signal meant for the original child.
280
+ next unless identity_unchanged?(tpid, identities[tpid])
281
+
252
282
  ::Process.kill(sig, tpid)
253
283
  rescue StandardError
254
284
  nil
@@ -262,6 +292,39 @@ module Rubik
262
292
  false
263
293
  end
264
294
 
295
+ # /proc/<pid>/stat field 22 (starttime) is fixed for a process's whole
296
+ # lifetime, so it distinguishes the original child from a recycled PID.
297
+ # nil (no /proc, or an already-reaped pid) means there is no identity to
298
+ # compare — the liveness check remains the best available guard.
299
+ def process_identity(pid)
300
+ return nil unless pid&.positive?
301
+
302
+ stat = File.read("/proc/#{pid}/stat")
303
+ stat.rpartition(")")[2].to_s.split[19]
304
+ rescue StandardError
305
+ nil
306
+ end
307
+
308
+ def identity_unchanged?(pid, identity)
309
+ identity.nil? || process_identity(pid) == identity
310
+ end
311
+
312
+ # Never resolve a process helper through PATH: a poisoned PATH would let
313
+ # a fake `pgrep` inject arbitrary PIDs into the kill list. Only known
314
+ # absolute locations are eligible, and each capture is bounded so a
315
+ # hung helper cannot stall teardown.
316
+ def capture_helper(name, *)
317
+ helper = HELPER_LOCATIONS.fetch(name, []).find { |path| File.executable?(path) }
318
+ return nil unless helper
319
+
320
+ Timeout.timeout(HELPER_CAPTURE_TIMEOUT_SECONDS) do
321
+ out, = Open3.capture2(helper, *, err: File::NULL)
322
+ out
323
+ end
324
+ rescue StandardError
325
+ nil
326
+ end
327
+
265
328
  def direct_child_pids(pid)
266
329
  task_dir = "/proc/#{pid}/task"
267
330
  if File.directory?(task_dir)
@@ -277,18 +340,10 @@ module Rubik
277
340
  return pids.reject(&:zero?) unless pids.empty?
278
341
  end
279
342
 
280
- out, = begin
281
- Open3.capture2("pgrep", "-P", pid.to_s, err: File::NULL)
282
- rescue StandardError
283
- [nil, nil]
284
- end
343
+ out = capture_helper("pgrep", "-P", pid.to_s)
285
344
  return out.lines.map(&:to_i).reject(&:zero?) if out && !out.empty?
286
345
 
287
- out, = begin
288
- Open3.capture2("ps", "--ppid", pid.to_s, "-o", "pid=", err: File::NULL)
289
- rescue StandardError
290
- [nil, nil]
291
- end
346
+ out = capture_helper("ps", "--ppid", pid.to_s, "-o", "pid=")
292
347
  return out.lines.map(&:to_i).reject(&:zero?) if out && !out.empty?
293
348
 
294
349
  []
@@ -20,6 +20,19 @@ module Rubik
20
20
  "echo", "dir", "cd", "cls", "set", "type", "copy", "move", "del", "md", "rd", "exit", "rem", "ver", "vol"
21
21
  ].freeze
22
22
 
23
+ # Credential-shaped variable names stripped from child-process
24
+ # environments (issue #586). Matching is by underscore-delimited
25
+ # segment (case-insensitive) so OPENAI_API_KEY, MY_SECRET and
26
+ # AWS_ACCESS_KEY_ID are covered without matching words like
27
+ # "tokenizer". NOTE: integrity hygiene, NOT a confinement boundary.
28
+ # Defined at module level (not inside class << self) so every spawn
29
+ # path can reference Rubik::Platform::CREDENTIAL_ENV_PATTERN directly.
30
+ CREDENTIAL_ENV_PATTERN = /
31
+ (?:_|\A)(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|PAT|CREDENTIALS?)(?:_|\z)
32
+ |\A(?:DATABASE|REDIS|MONGO|POSTGRES|MYSQL|AMQP)_URL\z
33
+ |_(?:DATABASE|REDIS|CONNECTION)_URL\z
34
+ /ix
35
+
23
36
  class << self
24
37
  # Audit 1: gated debug logging for the platform layer's many intentional
25
38
  # rescue-and-fallback paths (UTF-8 sanitation, atomic writes). Follows
@@ -61,25 +74,12 @@ module Rubik
61
74
  env
62
75
  end
63
76
 
64
- # Credential-shaped variable names stripped from child-process
65
- # environments (issue #586). Matching is by underscore-delimited
66
- # segment (case-insensitive) so OPENAI_API_KEY, MY_SECRET and
67
- # AWS_ACCESS_KEY_ID are covered without matching words like
68
- # "tokenizer". NOTE: integrity hygiene, NOT a confinement boundary.
69
- CREDENTIAL_ENV_PATTERN = /
70
- (?:_|\A)(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|PAT|CREDENTIALS?)(?:_|\z)
71
- |\A(?:DATABASE|REDIS|MONGO|POSTGRES|MYSQL|AMQP)_URL\z
72
- |_(?:DATABASE|CONNECTION)_URL\z
73
- /ix
74
-
75
77
  # sanitized_spawn_env plus an explicit nil for every credential-shaped
76
78
  # host variable (spawn semantics: nil UNSETs it; benign variables stay
77
79
  # out of the hash and remain normally inheritable). Consumers:
78
- # TaskManager#start (issue #586) and Driver::ProcessDriver#child_env
79
- # (both now delegate here — single shared CREDENTIAL_ENV_PATTERN).
80
- # The MCP stdio transport keeps its own narrower pattern on purpose:
81
- # it matches _REDIS_URL, which this pattern's underscore-URL branch
82
- # does not, so this pattern is not a safe superset for that path.
80
+ # TaskManager#start (issue #586), Driver::ProcessDriver#child_env, and
81
+ # the MCP stdio transport's inherit_env: false path — one shared
82
+ # CREDENTIAL_ENV_PATTERN for every spawn path.
83
83
  def credential_free_env
84
84
  env = sanitized_spawn_env
85
85
  ENV.each_key do |key|
@@ -58,9 +58,8 @@ module Rubik
58
58
  end
59
59
 
60
60
  def load_plugin_gem(gem_name, runtime_manager: nil, _context: nil)
61
+ component_name = "plugin_#{gem_name}"
61
62
  if runtime_manager
62
- component_name = "plugin_#{gem_name}"
63
-
64
63
  if runtime_manager.fibers.key?(component_name)
65
64
  runtime_manager.unregister_component(component_name)
66
65
  @registered_plugins.delete(gem_name)
@@ -75,15 +74,11 @@ module Rubik
75
74
  end
76
75
  @registered_plugins << gem_name unless @registered_plugins.include?(gem_name)
77
76
  true
78
- rescue LoadError => e
79
- @logger.error("Failed to load plugin '#{gem_name}': #{e.message}")
80
- raise e.message
81
77
  rescue StandardError => e
82
78
  @logger.error("Plugin '#{gem_name}' raised an error during initialization: #{e.message}")
83
79
  raise e
84
80
  end
85
81
 
86
- # Optionally wait for component to be active
87
82
  return true
88
83
  end
89
84
 
@@ -92,6 +87,10 @@ module Rubik
92
87
  true
93
88
  rescue LoadError => e
94
89
  @logger.error("Failed to load plugin '#{gem_name}': #{e.message}")
90
+ # ComponentFiber re-raises LoadError after rollback; the fiber holds
91
+ # the original exception, so registration itself still succeeded.
92
+ return true if runtime_manager&.fibers&.key?(component_name)
93
+
95
94
  false
96
95
  rescue StandardError => e
97
96
  @logger.error("Plugin '#{gem_name}' raised an error during initialization: #{e.message}")
@@ -143,7 +143,7 @@ module Rubik
143
143
  Rubik::Buffer::SnapshotStore.new(
144
144
  storage_dir: File.join(s.home_dir, ".rubik", "snapshots", File.basename(s.root_dir)),
145
145
  min_interval: 1.0, max_snapshots: 200
146
- )
146
+ ).tap(&:load_snapshots)
147
147
  end,
148
148
  provide: Rubik::Coeffects::SNAPSHOT_STORE
149
149
  ),
@@ -21,6 +21,7 @@ module Rubik
21
21
  @reading = false
22
22
  @collecting = false
23
23
  @inbox = []
24
+ @write_monitor = Monitor.new
24
25
  end
25
26
 
26
27
  def reading?
@@ -38,23 +39,18 @@ module Rubik
38
39
  return false if text.nil? || text.to_s.empty?
39
40
 
40
41
  clean_text = text.to_s.sub(/\A\n+/, "")
41
-
42
- synchronize do
42
+ buffered, reading = synchronize do
43
43
  if @quiet && !force
44
44
  @inbox << clean_text
45
- return false
46
- end
47
-
48
- if @reading
49
- @output.print "\r\e[2K"
50
- @output.puts clean_text
51
- redisplay_cleanly
45
+ [true, false]
52
46
  else
53
- @output.puts clean_text
47
+ [false, @reading]
54
48
  end
55
- @output.flush if @output.respond_to?(:flush)
56
- true
57
49
  end
50
+ return false if buffered
51
+
52
+ write_notices([clean_text], reading: reading)
53
+ true
58
54
  end
59
55
 
60
56
  def quiet?
@@ -74,19 +70,16 @@ module Rubik
74
70
  end
75
71
 
76
72
  def flush_notices!
77
- items = flush_inbox!
78
- return false if items.empty?
73
+ items, reading = synchronize do
74
+ next [nil, false] if @inbox.empty?
79
75
 
80
- synchronize do
81
- if @reading
82
- @output.print "\r\e[2K"
83
- items.each { |item| @output.puts item }
84
- redisplay_cleanly
85
- else
86
- items.each { |item| @output.puts item }
87
- end
88
- @output.flush if @output.respond_to?(:flush)
76
+ drained = @inbox.dup
77
+ @inbox.clear
78
+ [drained, @reading]
89
79
  end
80
+ return false if items.nil?
81
+
82
+ write_notices(items, reading: reading)
90
83
  true
91
84
  end
92
85
 
@@ -147,6 +140,19 @@ module Rubik
147
140
 
148
141
  private
149
142
 
143
+ # Terminal writes happen outside the monitor (issue #635): a blocked
144
+ # stdout must not stall every thread waiting on guard state.
145
+ def write_notices(items, reading:)
146
+ # Re-check under the guard monitor: with_reading does not hold it across the user's read, so the caller's flag can be stale (#635).
147
+ effective_reading = reading && synchronize { @reading }
148
+ @write_monitor.synchronize do
149
+ @output.print "\r\e[2K" if effective_reading
150
+ items.each { |item| @output.puts item }
151
+ redisplay_cleanly if effective_reading
152
+ @output.flush if @output.respond_to?(:flush)
153
+ end
154
+ end
155
+
150
156
  def redisplay_cleanly
151
157
  if @reline.respond_to?(:line_editor) && @reline.line_editor
152
158
  le = @reline.line_editor
@@ -138,20 +138,30 @@ module Rubik
138
138
  Rubik::Platform.debug_warn("input ceiling lookup failed (#{e.class}: #{e.message}); using nil budget")
139
139
  nil
140
140
  end
141
- # Serialize the read-compute-replace of the history array with the
142
- # bus-thread notice injection (issue #557). Both sides use the same
143
- # mutex owned by NoticeRouter; bare EmitHost doubles skip the lock.
144
- if respond_to?(:notice_router)
145
- notice_router.subagent_notices_mutex.synchronize do
146
- @conversation_history = Rubik::Prompt::ContextCompactor.trim_history_to_budget(
147
- @conversation_history, ceiling: ceiling, max_entries: MAX_CONVERSATION_ENTRIES
148
- )
141
+ # Merge provenance markers from every compaction path (this trim,
142
+ # !context compact, emergency compaction) into ONE growing summary
143
+ # at the head (issue #635).
144
+ recompute = lambda do
145
+ summary_count = @conversation_history.sum do |row|
146
+ compacted_summary_row?(row) ? compacted_summary_count(row) : 0
149
147
  end
150
- else
151
- @conversation_history = Rubik::Prompt::ContextCompactor.trim_history_to_budget(
152
- @conversation_history, ceiling: ceiling, max_entries: MAX_CONVERSATION_ENTRIES
148
+ body = @conversation_history.reject { |row| compacted_summary_row?(row) }
149
+ trimmed = Rubik::Prompt::ContextCompactor.trim_history_to_budget(
150
+ body, ceiling: ceiling, max_entries: MAX_CONVERSATION_ENTRIES
153
151
  )
152
+ dropped = body.size - trimmed.size + summary_count
153
+ dropped.positive? ? [Rubik::Prompt::ContextCompactor.summary_message(dropped), *trimmed] : trimmed
154
154
  end
155
+
156
+ # The read-compute-replace must be atomic with the bus-thread notice
157
+ # injection (issue #557): a stale snapshot would silently drop a
158
+ # notice appended while the trim was running. Both sides use the same
159
+ # mutex owned by NoticeRouter; bare EmitHost doubles skip the lock.
160
+ @conversation_history = if respond_to?(:notice_router)
161
+ notice_router.subagent_notices_mutex.synchronize(&recompute)
162
+ else
163
+ recompute.call
164
+ end
155
165
  rescue StandardError => e
156
166
  Rubik::Log.warn(:repl, "conversation trim failed (#{e.class}: #{e.message}); window may exceed token budget")
157
167
  nil
@@ -248,6 +258,20 @@ module Rubik
248
258
  @output.puts "[Rubik::Session] Resumed session: #{File.basename(target_file)} (#{res[:turns_hydrated]} dialogue turns hydrated, 0 API tokens used)" if res[:ok]
249
259
  res
250
260
  end
261
+
262
+ private
263
+
264
+ def compacted_summary_row?(row)
265
+ row.is_a?(Hash) && compacted_summary_content(row).start_with?("<compacted_summary ")
266
+ end
267
+
268
+ def compacted_summary_count(row)
269
+ compacted_summary_content(row)[/count="(\d+)"/, 1].to_i
270
+ end
271
+
272
+ def compacted_summary_content(row)
273
+ (row[:content] || row["content"]).to_s
274
+ end
251
275
  end
252
276
  end
253
277
  end
@@ -40,9 +40,8 @@ module Rubik
40
40
  # shared session guard via driver_opts (options[:guard]) so operator
41
41
  # policy — the live command allowlist above all — applies to every
42
42
  # driver; the lazy local fallback (silent audit, zero policy) serves
43
- # only standalone / test-constructed drivers. ProcessDriver keeps its
44
- # own copy with cmd.exe refinements; container drivers re-verify the
45
- # raw command through this shared helper before spawning.
43
+ # only standalone / test-constructed drivers. Every driver re-verifies
44
+ # the raw command through this shared helper before spawning.
46
45
  def guard
47
46
  @options[:guard] || (@guard ||= Rubik::Security::Guard.new(audit_log_path: nil))
48
47
  end
@@ -54,6 +53,30 @@ module Rubik
54
53
  true
55
54
  end
56
55
 
56
+ # Assemble the driver result with output hygiene applied uniformly:
57
+ # stdout/stderr are redacted and `output` is recomputed from the
58
+ # redacted parts, so a credential a command prints can never reach
59
+ # model-visible output through any driver. Every driver funnels its
60
+ # result through this one home.
61
+ # NOTE: integrity hygiene, NOT a secret-confinement boundary.
62
+ def finalize_result(res, driver: name, stderr: nil, extra: {})
63
+ require_relative "../../security/redactor" unless defined?(Rubik::Security::Redactor)
64
+ stdout = Rubik::Security::Redactor.redact(res[:stdout])
65
+ stderr = Rubik::Security::Redactor.redact(stderr || res[:stderr])
66
+ {
67
+ ok: res[:ok],
68
+ exit_code: res[:exit_code],
69
+ # Explicit timeout flag plumbed to the tool layer (#597-3).
70
+ timed_out: res[:timed_out] == true,
71
+ stdout: stdout,
72
+ stderr: stderr,
73
+ output: [stdout, stderr].reject(&:empty?).join("\n"),
74
+ duration: res[:duration],
75
+ driver: driver,
76
+ **extra
77
+ }
78
+ end
79
+
57
80
  # Issue #591: bind-mount every configured allowed dir read-write,
58
81
  # mirroring BubblewrapDriver's loop, so commands legitimately touching
59
82
  # an allowed external dir work identically across drivers.
@@ -38,6 +38,11 @@ module Rubik
38
38
  end
39
39
 
40
40
  def run(cmd, timeout: 15, chdir: Dir.pwd, allow_network: false, memory_limit_mb: 512, cpus: "1.0") # rubocop:disable Lint/UnusedMethodArgument
41
+ # Defense-in-depth: re-run the shared session guard before spawning,
42
+ # the same way the docker/podman/process drivers do, so a caller
43
+ # that forgot its own pre-check is still gated by operator policy.
44
+ verify_command_safety!(cmd)
45
+
41
46
  workspace = File.expand_path(chdir)
42
47
 
43
48
  bwrap_cmd = ["bwrap"]
@@ -72,17 +77,7 @@ module Rubik
72
77
  error_message: "Bubblewrap execution error"
73
78
  )
74
79
 
75
- {
76
- ok: res[:ok],
77
- exit_code: res[:exit_code],
78
- # Explicit timeout flag plumbed to the tool layer (#597-3).
79
- timed_out: res[:timed_out] == true,
80
- stdout: res[:stdout],
81
- stderr: res[:stderr],
82
- output: res[:output],
83
- duration: res[:duration],
84
- driver: "bwrap"
85
- }
80
+ finalize_result(res)
86
81
  end
87
82
 
88
83
  # Probe the installed bwrap once. bubblewrap's --tmpfs has only ever
@@ -58,17 +58,7 @@ module Rubik
58
58
  Rubik::Log.warn(:sandbox, "docker container '#{container_name}' could not be removed") unless removed
59
59
  end
60
60
 
61
- {
62
- ok: res[:ok],
63
- exit_code: res[:exit_code],
64
- # Explicit timeout flag plumbed to the tool layer (#597-3).
65
- timed_out: res[:timed_out] == true,
66
- stdout: res[:stdout],
67
- stderr: res[:stderr],
68
- output: res[:output],
69
- duration: res[:duration],
70
- driver: "docker"
71
- }
61
+ finalize_result(res, driver: "docker")
72
62
  end
73
63
  end
74
64
  end
@@ -2,8 +2,10 @@
2
2
 
3
3
  require_relative "base"
4
4
  require_relative "../../platform"
5
+ require_relative "../../log"
5
6
  require "open3"
6
7
  require "timeout"
8
+ require "securerandom"
7
9
 
8
10
  module Rubik
9
11
  module Sandbox
@@ -23,9 +25,11 @@ module Rubik
23
25
 
24
26
  image = @options[:image] || DEFAULT_IMAGE
25
27
  workspace = File.expand_path(chdir)
28
+ container_name = "rubik-box-#{SecureRandom.hex(6)}"
26
29
 
27
30
  podman_args = [
28
31
  "podman", "run", "--rm",
32
+ "--name", container_name,
29
33
  *CONTAINER_HARDENING_FLAGS,
30
34
  "-w", "/workspace",
31
35
  "-v", "#{workspace}:/workspace:rw",
@@ -38,25 +42,29 @@ module Rubik
38
42
  podman_args.push("--network", "none") unless allow_network
39
43
  podman_args.push(image, "sh", "-c", cmd)
40
44
 
41
- res = Rubik::Platform.popen_capture(
42
- *podman_args,
43
- timeout: timeout,
44
- chdir: workspace,
45
- timeout_message: "Podman sandbox execution timed out after #{timeout} seconds",
46
- error_message: "Podman sandbox error"
47
- )
45
+ res = begin
46
+ Rubik::Platform.popen_capture(
47
+ *podman_args,
48
+ timeout: timeout,
49
+ chdir: workspace,
50
+ timeout_message: "Podman sandbox execution timed out after #{timeout} seconds",
51
+ error_message: "Podman sandbox error"
52
+ )
53
+ ensure
54
+ # Mirror DockerDriver: the watchdog kills the podman client process
55
+ # tree on timeout, and --rm removal is performed by that client, so
56
+ # a timed-out run would otherwise orphan the container. Only a
57
+ # killed run needs the force-remove — a completed run (any exit
58
+ # code) already removed itself via --rm, and rm-ing a missing
59
+ # container would just warn noise. Best-effort cleanup; a failed
60
+ # `podman rm -f` leaves a trace.
61
+ if res.nil? || res[:timed_out] == true
62
+ removed = system("podman", "rm", "-f", container_name, out: File::NULL, err: File::NULL)
63
+ Rubik::Log.warn(:sandbox, "podman container '#{container_name}' could not be removed") unless removed
64
+ end
65
+ end
48
66
 
49
- {
50
- ok: res[:ok],
51
- exit_code: res[:exit_code],
52
- # Explicit timeout flag plumbed to the tool layer (#597-3).
53
- timed_out: res[:timed_out] == true,
54
- stdout: res[:stdout],
55
- stderr: res[:stderr],
56
- output: res[:output],
57
- duration: res[:duration],
58
- driver: "podman"
59
- }
67
+ finalize_result(res, driver: "podman")
60
68
  end
61
69
  end
62
70
  end