rubik 0.13.0 → 0.14.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 (101) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +34 -1
  4. data/lib/rubik/ast/c_extractor.rb +1 -1
  5. data/lib/rubik/ast/graph.rb +38 -57
  6. data/lib/rubik/ast/graph_extensions.rb +57 -15
  7. data/lib/rubik/ast/ruby_extractor.rb +4 -0
  8. data/lib/rubik/ast/treesitter/c_walker.rb +11 -3
  9. data/lib/rubik/buffer/manager.rb +33 -11
  10. data/lib/rubik/buffer/snapshot.rb +23 -3
  11. data/lib/rubik/cli/connect.rb +3 -5
  12. data/lib/rubik/config/defaults.rb +3 -7
  13. data/lib/rubik/config/env_guard.rb +43 -0
  14. data/lib/rubik/config/schema.rb +7 -1
  15. data/lib/rubik/config/secret_policy.rb +6 -5
  16. data/lib/rubik/config.rb +1 -1
  17. data/lib/rubik/connect/models_dev.rb +9 -0
  18. data/lib/rubik/connect/probes.rb +9 -2
  19. data/lib/rubik/connect/wizard.rb +108 -56
  20. data/lib/rubik/context/repo_context_reader.rb +8 -4
  21. data/lib/rubik/llm/chunk_assembler.rb +12 -1
  22. data/lib/rubik/llm/formatter.rb +14 -0
  23. data/lib/rubik/llm/provider_key.rb +32 -0
  24. data/lib/rubik/llm/registry.rb +18 -2
  25. data/lib/rubik/llm/router.rb +19 -1
  26. data/lib/rubik/llm/session_header.rb +128 -0
  27. data/lib/rubik/llm/sse_parser.rb +57 -10
  28. data/lib/rubik/lsp/client.rb +11 -5
  29. data/lib/rubik/lsp/transport.rb +17 -7
  30. data/lib/rubik/mcp/transport/stdio.rb +42 -4
  31. data/lib/rubik/orchestrator/continuation_manager.rb +14 -5
  32. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +18 -2
  33. data/lib/rubik/orchestrator/goal_ledger/observation_projection.rb +13 -4
  34. data/lib/rubik/orchestrator/goal_ledger/validator.rb +46 -7
  35. data/lib/rubik/orchestrator/goal_ledger/verifier.rb +8 -1
  36. data/lib/rubik/orchestrator/goal_session.rb +4 -4
  37. data/lib/rubik/orchestrator/loop.rb +8 -11
  38. data/lib/rubik/orchestrator/provider_resolver.rb +29 -6
  39. data/lib/rubik/orchestrator/step_executor.rb +17 -2
  40. data/lib/rubik/orchestrator/subagent/instance.rb +24 -1
  41. data/lib/rubik/orchestrator/subagent/notices.rb +1 -1
  42. data/lib/rubik/orchestrator/subagent/reaper.rb +21 -2
  43. data/lib/rubik/orchestrator/subagent/start_gate.rb +1 -1
  44. data/lib/rubik/orchestrator/subagent/step_runner.rb +7 -7
  45. data/lib/rubik/orchestrator/subagent/supervisor.rb +10 -3
  46. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +27 -5
  47. data/lib/rubik/orchestrator/turn_executor.rb +24 -8
  48. data/lib/rubik/platform/filesystem.rb +52 -24
  49. data/lib/rubik/plugin/storage.rb +20 -0
  50. data/lib/rubik/prompt/context_builder.rb +2 -1
  51. data/lib/rubik/repair/loop.rb +22 -2
  52. data/lib/rubik/repl/commands/agent_context.rb +1 -1
  53. data/lib/rubik/repl/commands/agent_execution.rb +20 -15
  54. data/lib/rubik/repl/commands/buffer.rb +15 -0
  55. data/lib/rubik/repl/commands/connect.rb +0 -1
  56. data/lib/rubik/repl/commands/lsp.rb +1 -1
  57. data/lib/rubik/repl/commands/plugins.rb +31 -31
  58. data/lib/rubik/repl/commands/session.rb +5 -5
  59. data/lib/rubik/repl/commands/workspace.rb +4 -4
  60. data/lib/rubik/repl/input_execution.rb +30 -29
  61. data/lib/rubik/repl/input_loop.rb +9 -4
  62. data/lib/rubik/repl/lifecycle.rb +1 -2
  63. data/lib/rubik/repl/notice_router.rb +11 -5
  64. data/lib/rubik/repl/paste_support.rb +1 -1
  65. data/lib/rubik/repl/prompt_grace.rb +3 -3
  66. data/lib/rubik/repl/shell.rb +10 -2
  67. data/lib/rubik/repl/turn_recorder.rb +14 -3
  68. data/lib/rubik/runtime/context.rb +33 -27
  69. data/lib/rubik/runtime/manager.rb +23 -15
  70. data/lib/rubik/sandbox/driver/bubblewrap.rb +58 -8
  71. data/lib/rubik/sandbox/driver/process.rb +32 -1
  72. data/lib/rubik/sandbox/runner.rb +9 -1
  73. data/lib/rubik/security/classifier/classifier.rb +147 -13
  74. data/lib/rubik/security/classifier/commands/docker.yaml +1 -1
  75. data/lib/rubik/security/classifier/commands/git.yaml +27 -1
  76. data/lib/rubik/security/classifier/commands/sed.yaml +3 -3
  77. data/lib/rubik/security/classifier/database.rb +2 -2
  78. data/lib/rubik/security/command_gate.rb +8 -1
  79. data/lib/rubik/security/redactor.rb +62 -19
  80. data/lib/rubik/session/recorder.rb +13 -18
  81. data/lib/rubik/session/replayer.rb +29 -7
  82. data/lib/rubik/storage/store.rb +19 -5
  83. data/lib/rubik/tools/builtins/exec.rb +1 -1
  84. data/lib/rubik/tools/builtins/files.rb +8 -12
  85. data/lib/rubik/tools/builtins/grep.rb +3 -2
  86. data/lib/rubik/tools/builtins/lsp.rb +31 -7
  87. data/lib/rubik/tools/builtins/show_file.rb +1 -1
  88. data/lib/rubik/tools/builtins/synthesis.rb +4 -4
  89. data/lib/rubik/tools/result_normalizer.rb +1 -1
  90. data/lib/rubik/ui/banner.rb +3 -3
  91. data/lib/rubik/ui/dialog.rb +10 -7
  92. data/lib/rubik/ui/diff_viewer.rb +4 -4
  93. data/lib/rubik/ui/frame.rb +13 -3
  94. data/lib/rubik/ui/markdown_stream.rb +8 -2
  95. data/lib/rubik/ui/panel.rb +11 -11
  96. data/lib/rubik/ui/renderer.rb +6 -6
  97. data/lib/rubik/ui/spinner.rb +1 -1
  98. data/lib/rubik/ui/statusline.rb +3 -3
  99. data/lib/rubik/ui/theme.rb +1 -1
  100. data/lib/rubik/version.rb +1 -1
  101. metadata +4 -1
@@ -11,7 +11,7 @@ module Rubik
11
11
  # effects and is pruned from its parent on every exit.
12
12
  class PromptGrace
13
13
  ESCAPE_TIMEOUT = 0.03
14
- STATUS = "Gönderiliyor… Esc: düzenlemeye dön"
14
+ STATUS = "Sending… Esc: return to editing"
15
15
 
16
16
  def initialize(input:, output:, context: nil, clock: nil, reader: nil)
17
17
  @input = input
@@ -42,7 +42,7 @@ module Rubik
42
42
  # the last processed key. Do not let its Enter submit a later turn.
43
43
  if @input.respond_to?(:nread) && @input.nread.positive?
44
44
  @input.iflush
45
- @output.print "\a\r\e[2K[Rubik] Bekleme sırasında gelen tuşlar yok sayıldı.\r\n"
45
+ @output.print "\a\r\e[2K[Rubik] Keys received while waiting were ignored.\r\n"
46
46
  end
47
47
  return :execute
48
48
  end
@@ -58,7 +58,7 @@ module Rubik
58
58
 
59
59
  # Other keys are intentionally rejected, with immediate feedback.
60
60
  # Enter never leaks into the next readline as an accidental submit.
61
- @output.print "\a\r\e[2K#{STATUS} · Tuş yok sayıldı"
61
+ @output.print "\a\r\e[2K#{STATUS} · Key ignored"
62
62
  @output.flush
63
63
  end
64
64
  rescue Interrupt
@@ -193,7 +193,12 @@ module Rubik
193
193
  # @return [void]
194
194
  def execute_input(input_text)
195
195
  parsed = CommandParser.parse(input_text)
196
- @recorder.record(parsed.type, input_text) if !@replaying && parsed.type != :empty && parsed.type != :prompt
196
+ # Redact at the record seam, BEFORE the transcript write: provider
197
+ # CLI forms (`--key=…`, `set <name> key <value>`) are accepted here and
198
+ # must never land in the JSONL even if a recorder wrapper changes
199
+ # (issue #542). The recorder masks again as defence in depth.
200
+ clean_input = Rubik::Security::Redactor.redact(input_text)
201
+ @recorder.record(parsed.type, clean_input) if !@replaying && parsed.type != :empty && parsed.type != :prompt
197
202
 
198
203
  case parsed.type
199
204
  when :empty
@@ -208,7 +213,10 @@ module Rubik
208
213
  if resume_intent?(parsed.raw)
209
214
  execute_resumed_turn!
210
215
  else
211
- execute_free_text(parsed.raw)
216
+ # The redacted form is the one that reaches the recorder, the
217
+ # conversation window and every downstream LLM request — a
218
+ # pasted credential must not become durable prompt memory (#542).
219
+ execute_free_text(clean_input)
212
220
  end
213
221
  end
214
222
 
@@ -135,9 +135,20 @@ module Rubik
135
135
  Rubik::Platform.debug_warn("input ceiling lookup failed (#{e.class}: #{e.message}); using nil budget")
136
136
  nil
137
137
  end
138
- @conversation_history = Rubik::Prompt::ContextCompactor.trim_history_to_budget(
139
- @conversation_history, ceiling: ceiling, max_entries: MAX_CONVERSATION_ENTRIES
140
- )
138
+ # Serialize the read-compute-replace of the history array with the
139
+ # bus-thread notice injection (issue #557). Both sides use the same
140
+ # mutex owned by NoticeRouter; bare EmitHost doubles skip the lock.
141
+ if respond_to?(:notice_router)
142
+ notice_router.subagent_notices_mutex.synchronize do
143
+ @conversation_history = Rubik::Prompt::ContextCompactor.trim_history_to_budget(
144
+ @conversation_history, ceiling: ceiling, max_entries: MAX_CONVERSATION_ENTRIES
145
+ )
146
+ end
147
+ else
148
+ @conversation_history = Rubik::Prompt::ContextCompactor.trim_history_to_budget(
149
+ @conversation_history, ceiling: ceiling, max_entries: MAX_CONVERSATION_ENTRIES
150
+ )
151
+ end
141
152
  rescue StandardError => e
142
153
  Rubik::Log.warn(:repl, "conversation trim failed (#{e.class}: #{e.message}); window may exceed token budget")
143
154
  nil
@@ -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)
@@ -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(
@@ -59,6 +82,33 @@ module Rubik
59
82
  driver: "bwrap"
60
83
  }
61
84
  end
85
+
86
+ # Probe the installed bwrap once. bubblewrap's --tmpfs has only ever
87
+ # taken a destination path; the ":rw,noexec,nosuid" suffix is a Docker
88
+ # extension. A future bwrap that gains mount-option support is picked
89
+ # up automatically, while current binaries keep a working plain /tmp.
90
+ # Public so tests can stub either branch deterministically.
91
+ def self.tmpfs_supports_options?
92
+ return @tmpfs_supports_options if defined?(@tmpfs_supports_options)
93
+
94
+ bwrap = Rubik::Platform.which("bwrap")
95
+ @tmpfs_supports_options = begin
96
+ !!(bwrap && system(bwrap, "--ro-bind", "/", "/", "--tmpfs", TMPFS_HARDENED, "/bin/true",
97
+ out: File::NULL, err: File::NULL))
98
+ rescue StandardError
99
+ false
100
+ end
101
+ end
102
+
103
+ private
104
+
105
+ # Resolved lazily so the capability probe runs at most once per process
106
+ # and only when a sandbox is actually executed.
107
+ def tmpfs_dest
108
+ return @tmpfs_dest if defined?(@tmpfs_dest)
109
+
110
+ @tmpfs_dest = self.class.tmpfs_supports_options? ? TMPFS_HARDENED : "/tmp"
111
+ end
62
112
  end
63
113
  end
64
114
  end
@@ -10,13 +10,29 @@ 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
+ CREDENTIAL_ENV_PATTERN = /
23
+ (?:_|\A)(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|PAT|CREDENTIALS?)(?:_|\z)
24
+ |\A(?:DATABASE|REDIS|MONGO|POSTGRES|MYSQL|AMQP)_URL\z
25
+ |_(?:DATABASE|CONNECTION)_URL\z
26
+ /ix
27
+ private_constant :CREDENTIAL_ENV_PATTERN
28
+
13
29
  def available?
14
30
  true
15
31
  end
16
32
 
17
33
  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
34
  resolved = ShellResolver.resolve(cmd, preference: @options[:shell] || "auto")
19
- env = {}
35
+ env = child_env
20
36
 
21
37
  res = Rubik::Platform.popen_capture(
22
38
  env,
@@ -44,6 +60,21 @@ 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 CREDENTIAL_ENV_PATTERN for the shape that is stripped.
70
+ def child_env
71
+ env = Rubik::Platform.sanitized_spawn_env
72
+ ENV.each_key do |key|
73
+ env[key] = nil if key.match?(CREDENTIAL_ENV_PATTERN)
74
+ end
75
+ env
76
+ end
77
+
47
78
  # cmd.exe parses its tail with its own quoting rules that standard
48
79
  # Windows argv quoting cannot express, so the command must reach it
49
80
  # 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
@@ -24,6 +24,25 @@ module Rubik
24
24
  READ_OPERATORS = ["<"].freeze
25
25
  # PERF: Hoist home token array to avoid per-path array allocations in system_path? check.
26
26
  HOME_TOKENS = ["~", "~/", "$HOME", "${HOME}"].freeze
27
+ # Variables whose VALUE the host command executes as a shell command
28
+ # (git ssh/editor/pager hooks, shell startup files, askpass helpers).
29
+ # An unclassifiable payload here must fail closed instead of hiding
30
+ # behind a clean outer allowlist entry (issue #540).
31
+ EXECUTED_ENV_VARS = [
32
+ "GIT_SSH_COMMAND", "GIT_EDITOR", "GIT_SEQUENCE_EDITOR", "GIT_EXTERNAL_DIFF",
33
+ "GIT_PAGER", "GIT_ASKPASS", "EDITOR", "VISUAL", "PAGER", "SHELL", "BASH_ENV", "ENV",
34
+ "SSH_ASKPASS", "SSH_COMMAND", "LESSOPEN"
35
+ ].freeze
36
+ EXECUTED_ENV_PREFIXES = ["GIT_CONFIG_"].freeze
37
+ # Pre-subcommand git config assignments that redirect execution
38
+ # (editors, hooks, pagers, ssh, aliases). Global-option stripping
39
+ # removes these before subcommand options are evaluated, so the
40
+ # Engine must gate them from the raw argv (#539 residual).
41
+ GIT_CONFIG_FLAGS = ["-c", "--config"].freeze
42
+ DANGEROUS_GIT_CONFIG_KEYS = [
43
+ "core.editor", "core.hookspath", "core.pager", "core.sshcommand",
44
+ "core.fsmonitor", "core.gitproxy", "diff.external"
45
+ ].freeze
27
46
 
28
47
  def self.default_database
29
48
  @default_database ||= CommandDatabase.new
@@ -82,6 +101,7 @@ module Rubik
82
101
  # as a sibling inner command BEFORE redirects/system-path checks
83
102
  # so the rest of the pipeline sees the elevation.
84
103
  result = apply_assignment_payloads(result, inv, parse_warnings)
104
+ result = apply_git_config_overrides(result, inv, parse_warnings)
85
105
 
86
106
  write_paths, read_paths, all_temp = extract_paths(inv.redirects)
87
107
  result = apply_redirects(result, inv.redirects, write_paths, all_temp)
@@ -101,25 +121,36 @@ module Rubik
101
121
  def apply_assignment_payloads(result, inv, parse_warnings)
102
122
  return result if inv.assignments.empty?
103
123
 
104
- inners = inv.assignments.filter_map do |assignment|
124
+ inners = inv.assignments.flat_map do |assignment|
105
125
  name, value = assignment.split("=", 2)
106
126
  value = Matcher::Delegation.strip_quotes(value.to_s)
107
- next nil if value.strip.empty?
127
+ next [] if value.strip.empty?
108
128
 
109
129
  inner_invs, warnings = Parser.parse(value, shell: @shell)
110
130
  Matcher::Delegation.record_warnings(parse_warnings, warnings)
111
- next nil unless command_shaped?(inner_invs)
131
+ next [] if inner_invs.empty?
132
+
133
+ executed = executed_env_var?(name)
134
+ shaped = command_shaped?(inner_invs)
135
+ # A host-executed variable whose payload we cannot classify is
136
+ # the #540 bypass: `GIT_SSH_COMMAND='nc ...' git push` used to
137
+ # read as a clean `git push`. Floor it to UNKNOWN so the gate
138
+ # fails closed instead of trusting the outer allowlist entry.
139
+ next [] if !shaped && !executed
140
+
141
+ floor = executed && !shaped ? Classification::UNKNOWN : nil
112
142
 
113
143
  inner_invs.map do |inner_inv|
114
144
  Matcher::Delegation.match_inner_command(
115
145
  inner_inv.argv, @database,
116
146
  delegation_mode: "env_assignment",
117
147
  delegation_source: name,
148
+ min_classification: floor,
118
149
  parse_warnings: parse_warnings,
119
150
  redirects: inner_inv.redirects
120
151
  ) { |i, db, w| Matcher.match_command(i, db, w, shell: @shell) }
121
152
  end
122
- end.flatten
153
+ end
123
154
  return result if inners.empty?
124
155
 
125
156
  classification = result.classification
@@ -136,15 +167,14 @@ module Rubik
136
167
  classification: classification, risk: risk, classification_reason: reason)
137
168
  end
138
169
 
139
- # False-positive firewall: env values are usually scalars (LANG=C)
140
- # or config blobs (CFLAGS="-O2 -Wall", PS1="\u@\h"). A value counts
141
- # as a command payload only when it parses into an invocation whose
142
- # binary the database KNOWS or that is invoked by path — the same
143
- # trust boundary the matcher applies to any other argv[0].
144
- # Known residual: unknown-binary payloads (a DB-less interpreter
145
- # spelled without a path) stay unclassified, at parity with typing
146
- # that binary directly (UNKNOWN). Closing that would need a
147
- # known-env-exec-binaries list (GIT_SSH_COMMAND, GIT_EDITOR, SHELL).
170
+ # False-positive firewall for ORDINARY env values: they are usually
171
+ # scalars (LANG=C) or config blobs (CFLAGS="-O2 -Wall", PS1="\u@\h").
172
+ # A value counts as a command payload only when it parses into an
173
+ # invocation whose binary the database KNOWS or that is invoked by
174
+ # path — the same trust boundary the matcher applies to any argv[0].
175
+ # Host-executed variables (EXECUTED_ENV_VARS / EXECUTED_ENV_PREFIXES)
176
+ # bypass this firewall in apply_assignment_payloads and fail closed
177
+ # with an UNKNOWN floor when their payload cannot be classified.
148
178
  def command_shaped?(inner_invs)
149
179
  inner_invs.any? do |inv|
150
180
  binary = inv.argv.first.to_s
@@ -153,6 +183,79 @@ module Rubik
153
183
  end
154
184
  end
155
185
 
186
+ def executed_env_var?(name)
187
+ n = name.to_s
188
+ EXECUTED_ENV_VARS.include?(n) || EXECUTED_ENV_PREFIXES.any? { |prefix| n.start_with?(prefix) }
189
+ end
190
+
191
+ def dangerous_git_config_key?(key)
192
+ k = key.to_s.downcase
193
+ DANGEROUS_GIT_CONFIG_KEYS.include?(k) || k.start_with?("alias.")
194
+ end
195
+
196
+ def dangerous_git_config_assignments(result, argv)
197
+ # Only the pre-subcommand region: global options are stripped there
198
+ # before subcommand options run (#539 residual). Post-subcommand
199
+ # -c/--config stays owned by the command definitions; restricting
200
+ # the scan also avoids flagging config-like text inside -m/--grep.
201
+ subcommand = result.command[1..].first
202
+ limit = subcommand ? (argv.index(subcommand) || argv.size) : argv.size
203
+ candidates = argv[1...limit] || []
204
+
205
+ assignments = []
206
+ candidates.each_with_index do |token, i|
207
+ if GIT_CONFIG_FLAGS.include?(token)
208
+ value = candidates[i + 1].to_s
209
+ next unless value.include?("=")
210
+
211
+ key, payload = value.split("=", 2)
212
+ assignments << [key, payload] if dangerous_git_config_key?(key)
213
+ elsif token.start_with?("--config=")
214
+ spec = token.delete_prefix("--config=")
215
+ next unless spec.include?("=")
216
+
217
+ key, payload = spec.split("=", 2)
218
+ assignments << [key, payload] if dangerous_git_config_key?(key)
219
+ end
220
+ end
221
+ assignments
222
+ end
223
+
224
+ # `git -c core.editor='curl ... | bash' clone ...` is stripped as a
225
+ # global option before subcommand options run, so the payload stayed
226
+ # invisible (#539 residual). Gate the dangerous key directly and
227
+ # surface its value through inner-command classification so the
228
+ # verdict is at least as strict as typing the payload itself.
229
+ def apply_git_config_overrides(result, inv, parse_warnings)
230
+ return result unless result.command.first.to_s == "git"
231
+
232
+ assignments = dangerous_git_config_assignments(result, inv.argv)
233
+ return result if assignments.empty?
234
+
235
+ inners = assignments.flat_map do |key, value|
236
+ inner_invs, warnings = Parser.parse(value, shell: @shell)
237
+ Matcher::Delegation.record_warnings(parse_warnings, warnings)
238
+ inner_invs.map do |inner_inv|
239
+ Matcher::Delegation.match_inner_command(
240
+ inner_inv.argv, @database,
241
+ delegation_mode: "git_config",
242
+ delegation_source: key,
243
+ parse_warnings: parse_warnings,
244
+ redirects: inner_inv.redirects
245
+ ) { |i, db, w| Matcher.match_command(i, db, w, shell: @shell) }
246
+ end
247
+ end
248
+
249
+ reason = append_reason(result.classification_reason,
250
+ "dangerous git config #{assignments.map(&:first).join(', ')}")
251
+ result.with(
252
+ inner_commands: result.inner_commands + inners,
253
+ classification: Classification::DANGEROUS,
254
+ risk: Risk::HIGH,
255
+ classification_reason: reason
256
+ )
257
+ end
258
+
156
259
  def extract_paths(redirects)
157
260
  write_paths = []
158
261
  read_paths = []
@@ -361,6 +464,13 @@ module Rubik
361
464
 
362
465
  p = p[1..-2] if (p.start_with?('"') && p.end_with?('"')) || (p.start_with?("'") && p.end_with?("'"))
363
466
  return false if p.empty? || p.start_with?("-")
467
+
468
+ # The current user's home is a system path however it is spelled —
469
+ # ~, $HOME/... and a literal /home/<user>/... must agree (#540).
470
+ # Checked before the temp exemption so a HOME under /tmp (test
471
+ # harnesses, containers) cannot slip through as a "temp path".
472
+ return true if home_path?(p)
473
+
364
474
  return false if !p.include?("..") && (temp_path?(p) || DEV_PATHS.any? { |dev| p == dev || p.start_with?(dev) })
365
475
 
366
476
  # Bare drive prefix without separator is NOT a drive root or system path
@@ -401,6 +511,30 @@ module Rubik
401
511
  end
402
512
  public :system_path?
403
513
 
514
+ # Prefix containment against the current user's home. HOME_TOKENS
515
+ # covers ~/$HOME spellings; this covers the literal absolute spelling
516
+ # that dangerous_system_roots only matched exactly (#540). Any
517
+ # expansion/containment failure (EACCES/EPERM, malformed HOME) is
518
+ # unprovable, so skip this elevation and let the other checks decide.
519
+ def home_path?(path)
520
+ p = path.to_s
521
+ # Only absolute spellings: ~/$HOME are covered by HOME_TOKENS, and
522
+ # expanding relative paths would flag every path under a home-rooted cwd.
523
+ return false unless p.start_with?("/") || p.match?(%r{\A[a-zA-Z]:[\\/]})
524
+
525
+ home = Rubik::Platform.home_dir
526
+ return false if home.nil? || home.to_s.empty?
527
+
528
+ home_abs = safe_expand_path(home.to_s)
529
+ return false unless home_abs.to_s.match?(%r{\A/}) || home_abs.to_s.match?(%r{\A[a-zA-Z]:[\\/]})
530
+
531
+ path_abs = safe_expand_path(path)
532
+ Rubik::Platform.path_under?(Rubik::Platform.normalize_path(path_abs),
533
+ Rubik::Platform.normalize_path(home_abs))
534
+ rescue StandardError
535
+ false
536
+ end
537
+
404
538
  def safe_expand_path(path)
405
539
  File.expand_path(path)
406
540
  rescue ArgumentError, TypeError
@@ -100,7 +100,7 @@ subcommands:
100
100
  classification: READONLY
101
101
  strict: false
102
102
  up:
103
- classification: EXTERNAL_EFFECTS
103
+ classification: DANGEROUS
104
104
  strict: false
105
105
  down:
106
106
  classification: EXTERNAL_EFFECTS