rubik 0.13.0 → 0.15.0

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 (131) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +122 -1
  4. data/lib/rubik/adapter/node.rb +4 -1
  5. data/lib/rubik/ast/c_extractor.rb +1 -1
  6. data/lib/rubik/ast/fallback_cleaner.rb +6 -1
  7. data/lib/rubik/ast/graph.rb +38 -57
  8. data/lib/rubik/ast/graph_extensions.rb +57 -15
  9. data/lib/rubik/ast/ruby_extractor.rb +16 -6
  10. data/lib/rubik/ast/treesitter/c_walker.rb +11 -3
  11. data/lib/rubik/buffer/manager.rb +38 -11
  12. data/lib/rubik/buffer/snapshot.rb +116 -28
  13. data/lib/rubik/cli/connect.rb +3 -5
  14. data/lib/rubik/config/defaults.rb +3 -7
  15. data/lib/rubik/config/env_guard.rb +43 -0
  16. data/lib/rubik/config/schema.rb +7 -1
  17. data/lib/rubik/config/scoped.rb +12 -5
  18. data/lib/rubik/config/secret_policy.rb +6 -5
  19. data/lib/rubik/config.rb +1 -1
  20. data/lib/rubik/connect/models_dev.rb +11 -0
  21. data/lib/rubik/connect/probes.rb +9 -2
  22. data/lib/rubik/connect/wizard.rb +117 -57
  23. data/lib/rubik/context/repo_context_reader.rb +8 -4
  24. data/lib/rubik/diagnostics/collector.rb +25 -2
  25. data/lib/rubik/llm/chunk_assembler.rb +12 -1
  26. data/lib/rubik/llm/client.rb +19 -0
  27. data/lib/rubik/llm/connection_pool.rb +7 -1
  28. data/lib/rubik/llm/formatter.rb +22 -2
  29. data/lib/rubik/llm/provider_key.rb +32 -0
  30. data/lib/rubik/llm/registry.rb +18 -2
  31. data/lib/rubik/llm/router.rb +27 -1
  32. data/lib/rubik/llm/session_header.rb +128 -0
  33. data/lib/rubik/llm/sse_parser.rb +57 -10
  34. data/lib/rubik/lsp/client.rb +244 -23
  35. data/lib/rubik/lsp/document_store.rb +6 -0
  36. data/lib/rubik/lsp/manager.rb +14 -0
  37. data/lib/rubik/lsp/transport.rb +34 -7
  38. data/lib/rubik/mcp/transport/stdio.rb +42 -4
  39. data/lib/rubik/orchestrator/continuation_manager.rb +68 -7
  40. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +18 -2
  41. data/lib/rubik/orchestrator/goal_ledger/observation_projection.rb +13 -4
  42. data/lib/rubik/orchestrator/goal_ledger/validator.rb +46 -7
  43. data/lib/rubik/orchestrator/goal_ledger/verifier.rb +8 -1
  44. data/lib/rubik/orchestrator/goal_session.rb +14 -14
  45. data/lib/rubik/orchestrator/goal_wait.rb +15 -9
  46. data/lib/rubik/orchestrator/loop.rb +39 -39
  47. data/lib/rubik/orchestrator/provider_resolver.rb +29 -6
  48. data/lib/rubik/orchestrator/step_executor.rb +17 -2
  49. data/lib/rubik/orchestrator/subagent/instance.rb +46 -5
  50. data/lib/rubik/orchestrator/subagent/lifecycle.rb +25 -25
  51. data/lib/rubik/orchestrator/subagent/messaging.rb +5 -1
  52. data/lib/rubik/orchestrator/subagent/narration.rb +2 -1
  53. data/lib/rubik/orchestrator/subagent/notices.rb +7 -3
  54. data/lib/rubik/orchestrator/subagent/questioner.rb +42 -4
  55. data/lib/rubik/orchestrator/subagent/reaper.rb +70 -20
  56. data/lib/rubik/orchestrator/subagent/start_gate.rb +1 -1
  57. data/lib/rubik/orchestrator/subagent/step_runner.rb +7 -7
  58. data/lib/rubik/orchestrator/subagent/supervisor.rb +21 -3
  59. data/lib/rubik/orchestrator/tool_call_id.rb +8 -4
  60. data/lib/rubik/orchestrator/turn_executor/subagent_channel.rb +21 -5
  61. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +40 -5
  62. data/lib/rubik/orchestrator/turn_executor.rb +24 -8
  63. data/lib/rubik/platform/filesystem.rb +52 -24
  64. data/lib/rubik/platform/process.rb +32 -7
  65. data/lib/rubik/platform/sanitize.rb +17 -18
  66. data/lib/rubik/platform.rb +27 -0
  67. data/lib/rubik/plugin/storage.rb +34 -8
  68. data/lib/rubik/prompt/context_builder.rb +2 -1
  69. data/lib/rubik/prompt/doctrine.rb +3 -2
  70. data/lib/rubik/repair/loop.rb +22 -2
  71. data/lib/rubik/repl/commands/agent_context.rb +1 -1
  72. data/lib/rubik/repl/commands/agent_execution.rb +20 -15
  73. data/lib/rubik/repl/commands/base.rb +7 -3
  74. data/lib/rubik/repl/commands/buffer.rb +21 -2
  75. data/lib/rubik/repl/commands/connect.rb +0 -1
  76. data/lib/rubik/repl/commands/lsp.rb +1 -1
  77. data/lib/rubik/repl/commands/plugins.rb +31 -31
  78. data/lib/rubik/repl/commands/session.rb +16 -6
  79. data/lib/rubik/repl/commands/workspace.rb +4 -4
  80. data/lib/rubik/repl/input_execution.rb +33 -32
  81. data/lib/rubik/repl/input_loop.rb +9 -4
  82. data/lib/rubik/repl/lifecycle.rb +1 -2
  83. data/lib/rubik/repl/notice_router.rb +11 -5
  84. data/lib/rubik/repl/paste_support.rb +1 -1
  85. data/lib/rubik/repl/prompt_grace.rb +3 -3
  86. data/lib/rubik/repl/service_catalog.rb +6 -2
  87. data/lib/rubik/repl/shell.rb +10 -2
  88. data/lib/rubik/repl/turn_recorder.rb +18 -4
  89. data/lib/rubik/runtime/context.rb +33 -27
  90. data/lib/rubik/runtime/manager.rb +23 -15
  91. data/lib/rubik/runtime/manifest_store.rb +7 -2
  92. data/lib/rubik/runtime/task_manager.rb +13 -10
  93. data/lib/rubik/sandbox/driver/base.rb +34 -0
  94. data/lib/rubik/sandbox/driver/bubblewrap.rb +60 -8
  95. data/lib/rubik/sandbox/driver/docker.rb +8 -0
  96. data/lib/rubik/sandbox/driver/podman.rb +8 -0
  97. data/lib/rubik/sandbox/driver/process.rb +29 -1
  98. data/lib/rubik/sandbox/runner.rb +9 -1
  99. data/lib/rubik/security/classifier/classifier.rb +147 -13
  100. data/lib/rubik/security/classifier/commands/docker.yaml +1 -1
  101. data/lib/rubik/security/classifier/commands/git.yaml +27 -1
  102. data/lib/rubik/security/classifier/commands/sed.yaml +3 -3
  103. data/lib/rubik/security/classifier/database.rb +2 -2
  104. data/lib/rubik/security/command_gate.rb +8 -1
  105. data/lib/rubik/security/path_policy.rb +28 -3
  106. data/lib/rubik/security/redactor.rb +62 -19
  107. data/lib/rubik/session/recorder.rb +27 -20
  108. data/lib/rubik/session/replayer.rb +29 -7
  109. data/lib/rubik/storage/store.rb +26 -5
  110. data/lib/rubik/tools/builtins/exec.rb +8 -2
  111. data/lib/rubik/tools/builtins/files.rb +8 -12
  112. data/lib/rubik/tools/builtins/grep.rb +3 -2
  113. data/lib/rubik/tools/builtins/interactive.rb +5 -2
  114. data/lib/rubik/tools/builtins/lsp.rb +59 -9
  115. data/lib/rubik/tools/builtins/send_message.rb +7 -2
  116. data/lib/rubik/tools/builtins/show_file.rb +1 -1
  117. data/lib/rubik/tools/builtins/synthesis.rb +4 -4
  118. data/lib/rubik/tools/preflight_runner.rb +4 -1
  119. data/lib/rubik/tools/result_normalizer.rb +1 -1
  120. data/lib/rubik/ui/banner.rb +3 -3
  121. data/lib/rubik/ui/dialog.rb +15 -8
  122. data/lib/rubik/ui/diff_viewer.rb +4 -4
  123. data/lib/rubik/ui/frame.rb +13 -3
  124. data/lib/rubik/ui/markdown_stream.rb +8 -2
  125. data/lib/rubik/ui/panel.rb +11 -11
  126. data/lib/rubik/ui/renderer.rb +10 -7
  127. data/lib/rubik/ui/spinner.rb +1 -1
  128. data/lib/rubik/ui/statusline.rb +3 -3
  129. data/lib/rubik/ui/theme.rb +1 -1
  130. data/lib/rubik/version.rb +1 -1
  131. metadata +4 -1
@@ -46,12 +46,14 @@ module Rubik
46
46
  inverse = cleanup_fn || block
47
47
  return unless inverse
48
48
 
49
+ # Resolve dmesg before the monitor: walking to the parent while held is a child→parent inversion (#552).
50
+ dmesg = disposed? ? resolve_dmesg : nil
49
51
  @monitor.synchronize do
50
52
  if @disposed
51
53
  # Ω is sealed: the context is already torn down, so there is no
52
54
  # later drain that would run this inverse. Execute it now instead
53
55
  # of silently storing it in a dead accumulator (leaked cleanup).
54
- run_inverse(inverse)
56
+ run_inverse(inverse, dmesg: dmesg)
55
57
  else
56
58
  @disposables << inverse
57
59
  end
@@ -231,8 +233,7 @@ module Rubik
231
233
  # Resolve dmesg outside monitor to preserve parent→child lock order (F3).
232
234
  dmesg = resolve_dmesg
233
235
  parent = nil
234
- deferred_interrupt = nil
235
- @monitor.synchronize do
236
+ children, inverses = @monitor.synchronize do
236
237
  return if @disposed
237
238
 
238
239
  @disposed = true
@@ -246,12 +247,24 @@ module Rubik
246
247
  # "beginning" log reports).
247
248
  dmesg&.log(:context, :info, "Beginning context dispose with #{@disposables.size} inverse(s)")
248
249
 
249
- deferred_interrupt = dispose_children
250
- drained, drain_signal = drain_inverses(dmesg: dmesg)
251
- deferred_interrupt ||= drain_signal
250
+ # Detach under the monitor, then drain UNLOCKED so a teardown inverse may re-enter this context (#552).
251
+ detached = [@children.dup, @disposables.dup]
252
+ @children.clear
253
+ @disposables.clear
254
+ detached
255
+ end
256
+
257
+ deferred_interrupt = dispose_children(children)
258
+ drained, drain_signal = drain_inverses(inverses, dmesg: dmesg)
259
+ deferred_interrupt ||= drain_signal
252
260
 
253
- dmesg&.log(:context, :info, "Context dispose complete; #{drained} inverse(s) executed")
261
+ @monitor.synchronize do
262
+ @services.clear
263
+ @service_inverses.clear
264
+ @child_inverses.clear
254
265
  end
266
+
267
+ dmesg&.log(:context, :info, "Context dispose complete; #{drained} inverse(s) executed")
255
268
  # Release the child's monitor before reaching the parent (lock
256
269
  # order), then prune the parent's record of this child.
257
270
  parent&.prune_child(self)
@@ -271,15 +284,14 @@ module Rubik
271
284
  # so the descending iteration never observes mutation. A child's
272
285
  # deferred Interrupt/SystemExit is adopted as (possibly) the FIRST
273
286
  # signal of this cascade; returns the first deferred child signal.
274
- def dispose_children
287
+ def dispose_children(children)
275
288
  deferred = nil
276
- @children.reverse_each do |child|
289
+ children.reverse_each do |child|
277
290
  child.dispose unless child.disposed?
278
291
  rescue Interrupt, SystemExit => e
279
292
  record_deferred_signal(e)
280
293
  deferred ||= e
281
294
  end
282
- @children.clear
283
295
  deferred
284
296
  end
285
297
 
@@ -291,23 +303,17 @@ module Rubik
291
303
  # by dispose after bookkeeping and the parent prune. Late registration
292
304
  # racing the drain is monitor-serialized (pop loop, or the sealed
293
305
  # immediate-run path). Returns [drained, first_signal].
294
- def drain_inverses(dmesg:)
306
+ def drain_inverses(inverses, dmesg:)
295
307
  drained = 0
296
308
  deferred = nil
297
- begin
298
- while (inverse = @disposables.pop)
299
- begin
300
- run_inverse(inverse, dmesg: dmesg)
301
- drained += 1
302
- rescue Interrupt, SystemExit => e
303
- record_deferred_signal(e)
304
- deferred ||= e
305
- end
309
+ while (inverse = inverses.pop)
310
+ begin
311
+ run_inverse(inverse, dmesg: dmesg)
312
+ drained += 1
313
+ rescue Interrupt, SystemExit => e
314
+ record_deferred_signal(e)
315
+ deferred ||= e
306
316
  end
307
- ensure
308
- @services.clear
309
- @service_inverses.clear
310
- @child_inverses.clear
311
317
  end
312
318
  [drained, deferred]
313
319
  end
@@ -320,7 +326,7 @@ module Rubik
320
326
  end
321
327
 
322
328
  def record_deferred_signal(exception)
323
- @last_dispose_errors << exception
329
+ @monitor.synchronize { @last_dispose_errors << exception }
324
330
  Rubik::Log.warn(:runtime, "dispose inverse raised #{exception.class} (deferred until drain completes): #{exception.message}")
325
331
  end
326
332
 
@@ -333,9 +339,9 @@ module Rubik
333
339
  def run_inverse(inverse, dmesg: nil)
334
340
  inverse.call
335
341
  rescue StandardError => e
336
- @last_dispose_errors << e
342
+ @monitor.synchronize { @last_dispose_errors << e }
337
343
  Rubik::Log.warn(:runtime, "dispose inverse failed: #{e.class}: #{e.message}")
338
- dmesg ||= resolve_dmesg
344
+ # dmesg is pre-resolved by the caller; resolving here would re-walk the parent (#552).
339
345
  dmesg&.log(:context, :err, "Dispose inverse failed: #{e.class}: #{e.message}")
340
346
  end
341
347
  end
@@ -72,13 +72,16 @@ module Rubik
72
72
  end
73
73
 
74
74
  def unregister_component(name)
75
- @monitor.synchronize do
76
- name_str = name.to_s
77
- fiber = @fibers.delete(name_str)
78
- @fiber_deps.delete(name_str)
79
- @retry_gate.clear(name_str) # fresh-eye R2: disposed fibers must not leak their retry budget
80
- fiber&.dispose!
81
- end
75
+ name_str = name.to_s
76
+ fiber = detach_fiber(name_str)
77
+ return unless fiber
78
+ return if @monitor.synchronize { @fibers[name_str].equal?(fiber) }
79
+
80
+ fiber.dispose!
81
+ nil
82
+ rescue StandardError => e
83
+ Rubik::Log.warn(:runtime, "fiber '#{fiber&.name}' dispose failed: #{e.class}: #{e.message}")
84
+ nil
82
85
  end
83
86
 
84
87
  # Reactive retraction (AGENTS.md §5, Finding B): unlike Context#unprovide
@@ -111,15 +114,11 @@ module Rubik
111
114
  reconcile_all(changed_service: service_name)
112
115
  end
113
116
 
114
- # Reentrant lock safety: Monitor#synchronize is explicitly reentrant (recursive),
115
- # allowing swap_component to safely invoke unregister_component and register_component
116
- # from within the same thread without deadlocking.
117
+ # Detach under the monitor; tear down outside it so a factory inverse cannot invert the lock order.
117
118
  def swap_component(name, inject: [], requires: [], provides: [], config: {}, &new_factory)
118
- @monitor.synchronize do
119
- name_str = name.to_s
120
- unregister_component(name_str)
121
- register_component(name_str, inject: inject, requires: requires, provides: provides, config: config, &new_factory)
122
- end
119
+ name_str = name.to_s
120
+ unregister_component(name_str)
121
+ register_component(name_str, inject: inject, requires: requires, provides: provides, config: config, &new_factory)
123
122
  end
124
123
 
125
124
  def reconcile_all(changed_service: nil)
@@ -227,6 +226,15 @@ module Rubik
227
226
 
228
227
  private
229
228
 
229
+ # Detach a fiber + bookkeeping under the monitor; teardown is deferred.
230
+ def detach_fiber(name_str)
231
+ @monitor.synchronize do
232
+ @fiber_deps.delete(name_str)
233
+ @retry_gate.clear(name_str)
234
+ @fibers.delete(name_str)
235
+ end
236
+ end
237
+
230
238
  # Marks the fiber while its factory runs so nested reconciles skip it;
231
239
  # ensure-based so a raising factory (→ :failed) never wedges the marker.
232
240
  def with_activation_marker(fiber)
@@ -59,8 +59,11 @@ module Rubik
59
59
 
60
60
  # Per-basename hash record: load → merge → save. The caller owns hash
61
61
  # computation (file vs normalized content) and pre-write guards; the
62
- # store owns the entry shape and the manifest mutation.
62
+ # store owns the entry shape and the manifest mutation. Fail-closed on
63
+ # a corrupt manifest — recording would rewrite it with only the new
64
+ # entry and evict the other consented records (issue #596).
63
65
  def record_hash(dir, filename, hash, scope:)
66
+ refuse_corrupt_manifest!(dir, :record, filename)
64
67
  manifest = load_manifest(dir)
65
68
  manifest[filename] = {
66
69
  "sha256" => hash,
@@ -71,8 +74,10 @@ module Rubik
71
74
  end
72
75
 
73
76
  # Symmetric retraction: remove a basename and persist. Returns whether
74
- # the key existed (mirrors Hash#delete's semantics).
77
+ # the key existed (mirrors Hash#delete's semantics). Fail-closed on a
78
+ # corrupt manifest for the same eviction reason as record_hash.
75
79
  def remove_entry(dir, filename)
80
+ refuse_corrupt_manifest!(dir, :delete, filename)
76
81
  manifest = load_manifest(dir)
77
82
  existed = manifest.delete(filename)
78
83
  save_manifest(dir, manifest) if existed
@@ -6,12 +6,14 @@ require "time"
6
6
  require_relative "../log"
7
7
  require_relative "../platform"
8
8
  require_relative "../security/guard" unless defined?(Rubik::Security::Guard)
9
+ require_relative "../security/redactor" unless defined?(Rubik::Security::Redactor)
9
10
 
10
11
  module Rubik
11
12
  module Runtime
12
- # Bounded thread-safe ring buffer for capturing child process stdout/stderr
13
- # without risk of unbounded memory growth (Plan 93).
13
+ # Bounded ring buffer for child stdout/stderr (Plan 93): bounded by entry
14
+ # count AND per-line bytes; lines are Redactor-redacted at push time (#586).
14
15
  class RingBuffer
16
+ MAX_LINE_BYTES = 64 * 1024 # byte cap per line (scrub re-validates cut chars)
15
17
  attr_reader :capacity
16
18
 
17
19
  def initialize(capacity = 500)
@@ -21,8 +23,11 @@ module Rubik
21
23
  end
22
24
 
23
25
  def push(line)
26
+ text = line.to_s
27
+ text = text.byteslice(0, MAX_LINE_BYTES).scrub if text.bytesize > MAX_LINE_BYTES
28
+ clean = Rubik::Security::Redactor.redact(text)
24
29
  @monitor.synchronize do
25
- @buffer << line.to_s
30
+ @buffer << clean
26
31
  @buffer.shift while @buffer.size > @capacity
27
32
  end
28
33
  self
@@ -76,9 +81,8 @@ module Rubik
76
81
  end
77
82
  end
78
83
 
79
- # Manages asynchronous long-running background processes (servers, builders,
80
- # watchers) with deadlock-immune streaming, AST guard verification, and
81
- # context-mediated LIFO rollback (AGENTS.md §1.A/B, Plan 93).
84
+ # Manages asynchronous long-running background processes with
85
+ # deadlock-immune streaming, AST guard verification and LIFO rollback.
82
86
  class TaskManager
83
87
  attr_reader :guard, :context, :root_dir, :max_buffer_lines
84
88
  attr_accessor :init
@@ -151,11 +155,10 @@ module Rubik
151
155
  # #444): that core is the synchronous drain-to-string capture shape
152
156
  # (Timeout-wrapped, stdin closed immediately, whole-output strings).
153
157
  # This spawn is the async/interactive shape — stdin stays open for
154
- # send_input, the readers stream chomped lines into the per-task
155
- # RingBuffer, and completion is watched by a dedicated thread with
156
- # no Timeout — so parameterizing the sink alone cannot unify them.
158
+ # send_input, readers stream chomped lines into the per-task
159
+ # RingBuffer, completion is watched by a dedicated thread.
157
160
  begin
158
- stdin, stdout, stderr, wait_thr = Open3.popen3(cmd_str, chdir: chdir)
161
+ stdin, stdout, stderr, wait_thr = Open3.popen3(Rubik::Platform.credential_free_env, cmd_str, chdir: chdir)
159
162
  rescue StandardError => e
160
163
  rollback_failed_start(target_ctx, nil, e)
161
164
  raise e
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../../security/guard" unless defined?(Rubik::Security::Guard)
4
+
3
5
  module Rubik
4
6
  module Sandbox
5
7
  module Driver
@@ -31,6 +33,38 @@ module Rubik
31
33
  def run(cmd, timeout: 15, chdir: Dir.pwd, allow_network: false, memory_limit_mb: 512, cpus: "1.0")
32
34
  raise NotImplementedError
33
35
  end
36
+
37
+ private
38
+
39
+ # Security guard gating spawns (issue #591). The Runner injects the
40
+ # shared session guard via driver_opts (options[:guard]) so operator
41
+ # policy — the live command allowlist above all — applies to every
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.
46
+ def guard
47
+ @options[:guard] || (@guard ||= Rubik::Security::Guard.new(audit_log_path: nil))
48
+ end
49
+
50
+ # Re-run the security guard's classification before spawning. Blocks
51
+ # a command the operator policy / catastrophic fallback regex rejects.
52
+ def verify_command_safety!(cmd, shell: nil)
53
+ guard.verify_command_safety!(cmd, shell: shell)
54
+ true
55
+ end
56
+
57
+ # Issue #591: bind-mount every configured allowed dir read-write,
58
+ # mirroring BubblewrapDriver's loop, so commands legitimately touching
59
+ # an allowed external dir work identically across drivers.
60
+ def allowed_dir_mounts
61
+ Array(@options[:allowed_dirs]).filter_map do |dir|
62
+ expanded = File.expand_path(dir.to_s)
63
+ next unless File.directory?(expanded)
64
+
65
+ ["-v", "#{expanded}:#{expanded}:rw"]
66
+ end.flatten
67
+ end
34
68
  end
35
69
  end
36
70
  end
@@ -9,6 +9,26 @@ module Rubik
9
9
  module Sandbox
10
10
  module Driver
11
11
  class BubblewrapDriver < Base
12
+ # Minimal read-only system trees needed to run a shell and common
13
+ # tools. The host root is deliberately NOT mounted: binding only these
14
+ # trees keeps ~/.ssh, ~/.aws/credentials and ~/.rubik/secrets.yml out
15
+ # of the sandbox, so READONLY cat/less/strings cannot leak them into
16
+ # model-visible output. Workspace and explicitly allowed dirs are
17
+ # bind-mounted read-write below; everything else is absent.
18
+ # NOTE: this provides integrity/isolation, NOT secret confinement —
19
+ # the sandbox is not a confidentiality boundary for host credentials.
20
+ MINIMAL_RO_BINDS = ["/usr", "/bin", "/sbin", "/lib", "/lib64", "/etc"].freeze
21
+ private_constant :MINIMAL_RO_BINDS
22
+
23
+ # Docker-style --tmpfs mount options. bubblewrap has never accepted a
24
+ # colon-suffixed DEST, so this is used only when a one-time capability
25
+ # probe confirms the installed binary supports it (see
26
+ # .tmpfs_supports_options?). Passing it to an unsupported bwrap makes
27
+ # bwrap try to create a literal directory by that name and fail the
28
+ # command, so older binaries fall back to a plain /tmp mount.
29
+ TMPFS_HARDENED = "/tmp:rw,noexec,nosuid"
30
+ private_constant :TMPFS_HARDENED
31
+
12
32
  def name
13
33
  "bwrap"
14
34
  end
@@ -20,14 +40,16 @@ module Rubik
20
40
  def run(cmd, timeout: 15, chdir: Dir.pwd, allow_network: false, memory_limit_mb: 512, cpus: "1.0") # rubocop:disable Lint/UnusedMethodArgument
21
41
  workspace = File.expand_path(chdir)
22
42
 
23
- bwrap_cmd = [
24
- "bwrap",
25
- "--ro-bind", "/", "/",
26
- "--dev", "/dev",
27
- "--proc", "/proc",
28
- "--tmpfs", "/tmp",
29
- "--bind", workspace, workspace
30
- ]
43
+ bwrap_cmd = ["bwrap"]
44
+
45
+ MINIMAL_RO_BINDS.each do |path|
46
+ bwrap_cmd.push("--ro-bind", path, path) if File.directory?(path)
47
+ end
48
+
49
+ bwrap_cmd.push("--dev", "/dev")
50
+ bwrap_cmd.push("--proc", "/proc")
51
+ bwrap_cmd.push("--tmpfs", tmpfs_dest)
52
+ bwrap_cmd.push("--bind", workspace, workspace)
31
53
 
32
54
  if @options[:allowed_dirs]
33
55
  Array(@options[:allowed_dirs]).each do |dir|
@@ -39,6 +61,7 @@ module Rubik
39
61
  bwrap_cmd.push("--chdir", workspace)
40
62
  bwrap_cmd.push("--unshare-net") unless allow_network
41
63
  bwrap_cmd.push("--unshare-pid", "--die-with-parent")
64
+ bwrap_cmd.push("--new-session", "--unshare-ipc", "--unshare-uts")
42
65
  bwrap_cmd.push("sh", "-c", cmd)
43
66
 
44
67
  res = Rubik::Platform.popen_capture(
@@ -52,6 +75,8 @@ module Rubik
52
75
  {
53
76
  ok: res[:ok],
54
77
  exit_code: res[:exit_code],
78
+ # Explicit timeout flag plumbed to the tool layer (#597-3).
79
+ timed_out: res[:timed_out] == true,
55
80
  stdout: res[:stdout],
56
81
  stderr: res[:stderr],
57
82
  output: res[:output],
@@ -59,6 +84,33 @@ module Rubik
59
84
  driver: "bwrap"
60
85
  }
61
86
  end
87
+
88
+ # Probe the installed bwrap once. bubblewrap's --tmpfs has only ever
89
+ # taken a destination path; the ":rw,noexec,nosuid" suffix is a Docker
90
+ # extension. A future bwrap that gains mount-option support is picked
91
+ # up automatically, while current binaries keep a working plain /tmp.
92
+ # Public so tests can stub either branch deterministically.
93
+ def self.tmpfs_supports_options?
94
+ return @tmpfs_supports_options if defined?(@tmpfs_supports_options)
95
+
96
+ bwrap = Rubik::Platform.which("bwrap")
97
+ @tmpfs_supports_options = begin
98
+ !!(bwrap && system(bwrap, "--ro-bind", "/", "/", "--tmpfs", TMPFS_HARDENED, "/bin/true",
99
+ out: File::NULL, err: File::NULL))
100
+ rescue StandardError
101
+ false
102
+ end
103
+ end
104
+
105
+ private
106
+
107
+ # Resolved lazily so the capability probe runs at most once per process
108
+ # and only when a sandbox is actually executed.
109
+ def tmpfs_dest
110
+ return @tmpfs_dest if defined?(@tmpfs_dest)
111
+
112
+ @tmpfs_dest = self.class.tmpfs_supports_options? ? TMPFS_HARDENED : "/tmp"
113
+ end
62
114
  end
63
115
  end
64
116
  end
@@ -19,6 +19,11 @@ module Rubik
19
19
  end
20
20
 
21
21
  def run(cmd, timeout: 15, chdir: Dir.pwd, allow_network: false, memory_limit_mb: 512, cpus: "1.0")
22
+ # Defense-in-depth (issue #591): re-run the shared session guard
23
+ # before spawning, the same way ProcessDriver does, so a caller
24
+ # that forgot its own pre-check is still gated by operator policy.
25
+ verify_command_safety!(cmd)
26
+
22
27
  image = @options[:image] || DEFAULT_IMAGE
23
28
  workspace = File.expand_path(chdir)
24
29
  container_name = "rubik-box-#{SecureRandom.hex(6)}"
@@ -29,6 +34,7 @@ module Rubik
29
34
  *CONTAINER_HARDENING_FLAGS,
30
35
  "-w", "/workspace",
31
36
  "-v", "#{workspace}:/workspace:rw",
37
+ *allowed_dir_mounts,
32
38
  "--memory", "#{memory_limit_mb}m",
33
39
  "--cpus", cpus.to_s,
34
40
  "--pids-limit", "100"
@@ -55,6 +61,8 @@ module Rubik
55
61
  {
56
62
  ok: res[:ok],
57
63
  exit_code: res[:exit_code],
64
+ # Explicit timeout flag plumbed to the tool layer (#597-3).
65
+ timed_out: res[:timed_out] == true,
58
66
  stdout: res[:stdout],
59
67
  stderr: res[:stderr],
60
68
  output: res[:output],
@@ -16,6 +16,11 @@ module Rubik
16
16
  end
17
17
 
18
18
  def run(cmd, timeout: 15, chdir: Dir.pwd, allow_network: false, memory_limit_mb: 512, cpus: "1.0")
19
+ # Defense-in-depth (issue #591): re-run the shared session guard
20
+ # before spawning, the same way ProcessDriver does, so a caller
21
+ # that forgot its own pre-check is still gated by operator policy.
22
+ verify_command_safety!(cmd)
23
+
19
24
  image = @options[:image] || DEFAULT_IMAGE
20
25
  workspace = File.expand_path(chdir)
21
26
 
@@ -24,6 +29,7 @@ module Rubik
24
29
  *CONTAINER_HARDENING_FLAGS,
25
30
  "-w", "/workspace",
26
31
  "-v", "#{workspace}:/workspace:rw",
32
+ *allowed_dir_mounts,
27
33
  "--memory", "#{memory_limit_mb}m",
28
34
  "--cpus", cpus.to_s,
29
35
  "--pids-limit", "100"
@@ -43,6 +49,8 @@ module Rubik
43
49
  {
44
50
  ok: res[:ok],
45
51
  exit_code: res[:exit_code],
52
+ # Explicit timeout flag plumbed to the tool layer (#597-3).
53
+ timed_out: res[:timed_out] == true,
46
54
  stdout: res[:stdout],
47
55
  stderr: res[:stderr],
48
56
  output: res[:output],
@@ -10,13 +10,26 @@ module Rubik
10
10
  module Sandbox
11
11
  module Driver
12
12
  class ProcessDriver < Base
13
+ # Credential-shaped variable names stripped from the child environment.
14
+ # Spawn semantics require an explicit nil to UNSET an inherited variable;
15
+ # the previous `env = {}` inherited the entire host environment, and the
16
+ # READONLY `env`/`printenv` commands could dump it into model-visible
17
+ # output. Matching is by underscore-delimited segment (case-insensitive)
18
+ # so SCREAMING_SNAKE names such as OPENAI_API_KEY, MY_SECRET and
19
+ # AWS_ACCESS_KEY_ID are covered without matching words like "tokenizer".
20
+ # NOTE: this is integrity hygiene, NOT a secret-confinement boundary —
21
+ # the child still inherits non-credential host variables by design.
22
+ # The credential pattern and the env construction live once in
23
+ # Rubik::Platform.credential_free_env (issue #586); this driver is a
24
+ # pure consumer of that shared implementation.
25
+
13
26
  def available?
14
27
  true
15
28
  end
16
29
 
17
30
  def run(cmd, timeout: 15, chdir: Dir.pwd, allow_network: false, memory_limit_mb: 512, cpus: "1.0") # rubocop:disable Lint/UnusedMethodArgument -- sürücü arayüzü kwarg'leri korunuyor
18
31
  resolved = ShellResolver.resolve(cmd, preference: @options[:shell] || "auto")
19
- env = {}
32
+ env = child_env
20
33
 
21
34
  res = Rubik::Platform.popen_capture(
22
35
  env,
@@ -33,6 +46,9 @@ module Rubik
33
46
  {
34
47
  ok: res[:ok],
35
48
  exit_code: res[:exit_code],
49
+ # Explicit timeout flag plumbed to the tool layer (#597-3): a
50
+ # legitimate timeout(1) exit 124 must not read as a runner kill.
51
+ timed_out: res[:timed_out] == true,
36
52
  stdout: clean_stdout,
37
53
  stderr: clean_stderr,
38
54
  output: [clean_stdout, clean_stderr].reject(&:empty?).join("\n"),
@@ -44,6 +60,18 @@ module Rubik
44
60
 
45
61
  private
46
62
 
63
+ # Environment handed to Open3.popen3. Start from the shared sanitized
64
+ # spawn env (bundler/Ruby runtime vars already nil'd), then explicitly
65
+ # nil every credential-shaped variable present in the host ENV so the
66
+ # child cannot observe or dump them. Benign variables are left out of
67
+ # the hash entirely and therefore remain normally inheritable, which
68
+ # keeps legitimate command execution (PATH, HOME, locale, proxies…)
69
+ # working. See Rubik::Platform::CREDENTIAL_ENV_PATTERN for the shape
70
+ # that is stripped.
71
+ def child_env
72
+ Rubik::Platform.credential_free_env
73
+ end
74
+
47
75
  # cmd.exe parses its tail with its own quoting rules that standard
48
76
  # Windows argv quoting cannot express, so the command must reach it
49
77
  # as a bare string (Ruby's string spawn form routes exactly there).
@@ -12,6 +12,14 @@ module Rubik
12
12
  class Runner
13
13
  attr_reader :root_dir, :driver, :allowed_external_dirs, :config, :guard, :context
14
14
 
15
+ # Honest description of what sandboxing actually guarantees. The drivers
16
+ # restrict writes/network and strip credential-shaped env vars, but they
17
+ # are NOT a confidentiality boundary: bubblewrap still exposes the
18
+ # workspace and any explicitly allowed read-only binds, and the process
19
+ # driver runs on the host with only command-level guardrails.
20
+ INTEGRITY_ONLY_NOTE = "integrity only, NOT a secret-confinement boundary " \
21
+ "(only credential-shaped env vars are stripped; allowed read-only binds can still expose host files)"
22
+
15
23
  def initialize(root_dir: Dir.pwd, allow_network: false, driver: nil, config: nil, allowed_external_dirs: [], guard: nil, context: nil)
16
24
  @root_dir = File.expand_path(root_dir)
17
25
  @config = config
@@ -219,7 +227,7 @@ module Rubik
219
227
  def isolation_disclosure
220
228
  if sandbox_enabled? && @driver
221
229
  net_status = allow_network? ? "allowed" : "none"
222
- "🔍 Isolation: sandbox (#{@driver.name}, network=#{net_status}) — strong"
230
+ "🔍 Isolation: sandbox (#{@driver.name}, network=#{net_status}) — #{INTEGRITY_ONLY_NOTE}"
223
231
  else
224
232
  "🔍 Execution: direct (safe execution guardrails active; sandbox disabled)"
225
233
  end