rubik 0.15.2 → 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.
- checksums.yaml +4 -4
- data/ATTRIBUTION.md +1 -1
- data/CHANGELOG.md +40 -3
- data/lib/rubik/ast/cache_store.rb +22 -4
- data/lib/rubik/ast/extractor.rb +1 -4
- data/lib/rubik/ast/ruby_extractor.rb +23 -1
- data/lib/rubik/ast/symbol.rb +9 -4
- data/lib/rubik/ast/treesitter/python_walker.rb +5 -4
- data/lib/rubik/ast/treesitter_extractor.rb +10 -3
- data/lib/rubik/buffer/diff.rb +34 -2
- data/lib/rubik/buffer/manager.rb +18 -15
- data/lib/rubik/buffer/path_validator.rb +18 -2
- data/lib/rubik/buffer/snapshot.rb +144 -9
- data/lib/rubik/concurrency/timers.rb +7 -0
- data/lib/rubik/config/scoped.rb +18 -7
- data/lib/rubik/config/secret_policy.rb +22 -1
- data/lib/rubik/config.rb +24 -26
- data/lib/rubik/context/ignore_rules.rb +7 -2
- data/lib/rubik/diagnostics/parser.rb +19 -8
- data/lib/rubik/kernel/dispatcher.rb +11 -5
- data/lib/rubik/llm/client.rb +24 -3
- data/lib/rubik/llm/connection_pool.rb +51 -30
- data/lib/rubik/llm/message_sanitizer.rb +20 -1
- data/lib/rubik/llm/sse_parser.rb +10 -1
- data/lib/rubik/lsp/transport.rb +61 -1
- data/lib/rubik/mcp/transport/stdio.rb +139 -122
- data/lib/rubik/orchestrator/activity_log.rb +3 -2
- data/lib/rubik/orchestrator/subagent/completion.rb +18 -8
- data/lib/rubik/platform/process.rb +74 -19
- data/lib/rubik/plugin/manager.rb +5 -6
- data/lib/rubik/repl/service_catalog.rb +1 -1
- data/lib/rubik/repl/terminal_guard.rb +29 -23
- data/lib/rubik/repl/turn_recorder.rb +35 -11
- data/lib/rubik/sandbox/driver/process.rb +11 -2
- data/lib/rubik/security/blocked_guidance.rb +4 -2
- data/lib/rubik/security/command_gate.rb +27 -14
- data/lib/rubik/security/errors.rb +13 -0
- data/lib/rubik/security/guard.rb +11 -2
- data/lib/rubik/security/path_policy.rb +9 -6
- data/lib/rubik/storage/store.rb +31 -11
- data/lib/rubik/tools/builtins/exec.rb +5 -1
- data/lib/rubik/tools/builtins/files.rb +2 -0
- data/lib/rubik/tools/uri_resolver.rb +23 -3
- data/lib/rubik/version.rb +1 -1
- 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
|
-
|
|
78
|
-
|
|
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
|
-
|
|
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
|
|
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, =
|
|
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
|
[]
|
data/lib/rubik/plugin/manager.rb
CHANGED
|
@@ -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
|
-
|
|
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
|
-
@
|
|
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 =
|
|
78
|
-
|
|
73
|
+
items, reading = synchronize do
|
|
74
|
+
next [nil, false] if @inbox.empty?
|
|
79
75
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
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
|
-
#
|
|
142
|
-
#
|
|
143
|
-
#
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
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
|
-
|
|
151
|
-
|
|
152
|
-
|
|
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
|
|
@@ -29,6 +29,14 @@ module Rubik
|
|
|
29
29
|
|
|
30
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
|
|
31
31
|
resolved = ShellResolver.resolve(cmd, preference: @options[:shell] || "auto")
|
|
32
|
+
# Defense in depth: the POSIX argv path used to reach spawn with no
|
|
33
|
+
# gate at all (only the cmd.exe branch re-verified). Gate it here.
|
|
34
|
+
# cmd is already gated inside verify_cmd_safe with cmd semantics.
|
|
35
|
+
# PowerShell cmdlets use a different vocabulary the POSIX classifier
|
|
36
|
+
# cannot classify. pwsh routing therefore relies on the upstream
|
|
37
|
+
# RunCommandTool gate; direct Sandbox::Runner callers must gate first.
|
|
38
|
+
# A PowerShell-aware classifier is tracked as a follow-up.
|
|
39
|
+
verify_command_safety!(cmd) unless ["cmd", "pwsh"].include?(resolved[:shell])
|
|
32
40
|
env = child_env
|
|
33
41
|
|
|
34
42
|
res = Rubik::Platform.popen_capture(
|
|
@@ -125,10 +133,11 @@ module Rubik
|
|
|
125
133
|
# Raise the standard BlockedWriteError used throughout the guard
|
|
126
134
|
# surface for an explicitly detected dangerous construct.
|
|
127
135
|
def raise_dangerous(cmd, rule_name:)
|
|
136
|
+
display = Rubik::Security.display_command(cmd)
|
|
128
137
|
raise Rubik::Security::BlockedWriteError.new(
|
|
129
|
-
"Dangerous command execution blocked: #{
|
|
138
|
+
"Dangerous command execution blocked: #{display}",
|
|
130
139
|
kind: :cmd_construct,
|
|
131
|
-
blocked_command:
|
|
140
|
+
blocked_command: display,
|
|
132
141
|
rule_name: rule_name
|
|
133
142
|
)
|
|
134
143
|
end
|
|
@@ -24,12 +24,14 @@ module Rubik
|
|
|
24
24
|
# one-liner: `!allow-cmd add "<command>"`.
|
|
25
25
|
def self.render(err)
|
|
26
26
|
cmd = err.respond_to?(:blocked_command) ? err.blocked_command : nil
|
|
27
|
+
cmd = Rubik::Security.display_command(cmd) if cmd
|
|
27
28
|
rule = err.respond_to?(:rule_name) ? err.rule_name : nil
|
|
28
29
|
kind = err.respond_to?(:kind) ? err.kind : nil
|
|
29
30
|
quoted = cmd ? "\"#{cmd}\"" : nil
|
|
30
31
|
# Unstructured raises (critical-write) carry all their context in
|
|
31
|
-
# #message — never discard it behind "rule: unknown".
|
|
32
|
-
|
|
32
|
+
# #message — never discard it behind "rule: unknown". Defense in depth:
|
|
33
|
+
# escape control chars even if a raise site forgets to.
|
|
34
|
+
message = Rubik::Security.display_command(err.message)
|
|
33
35
|
structural = cmd || rule
|
|
34
36
|
|
|
35
37
|
lines = if kind == :chdir_outside_root
|
|
@@ -63,6 +63,8 @@ module Rubik
|
|
|
63
63
|
# whose ONLY arguments are these flags is read-only by construction.
|
|
64
64
|
SAFE_PROBE_FLAGS = ["--version", "-v", "--help", "-h"].freeze
|
|
65
65
|
|
|
66
|
+
SHELL_METACHAR_PATTERN = /[;&|`$<>(){}\n\r]/
|
|
67
|
+
|
|
66
68
|
attr_accessor :shell, :root_dir
|
|
67
69
|
|
|
68
70
|
def initialize(allowlist:, audit:, path_policy:, allow_safe_probes: true,
|
|
@@ -123,6 +125,11 @@ module Rubik
|
|
|
123
125
|
def probe_shape?(cmd_str)
|
|
124
126
|
str = cmd_str.to_s
|
|
125
127
|
return false if str.match?(/[\r\n]/)
|
|
128
|
+
# ShellResolver passes the raw string to `sh -c`/`bash -c`, while this
|
|
129
|
+
# detector tokenizes with Shellwords. Exact-flag allowlisting already
|
|
130
|
+
# excludes metacharacters; keep the explicit check so a future flag
|
|
131
|
+
# addition cannot reopen the gap.
|
|
132
|
+
return false if str.match?(SHELL_METACHAR_PATTERN)
|
|
126
133
|
|
|
127
134
|
tokens = shell_tokens(str)
|
|
128
135
|
return false unless tokens
|
|
@@ -216,11 +223,11 @@ module Rubik
|
|
|
216
223
|
# today) keeps flowing into its own deny layers
|
|
217
224
|
# (DANGEROUS_SYNTHESIS_PATTERNS + RubyVM walk) after this gate.
|
|
218
225
|
if allow_unknown
|
|
219
|
-
Rubik::Log.warn(:security, "[WARN] AST classification error on non-shell input, continuing to synthesis deny layers: #{e.message}")
|
|
226
|
+
Rubik::Log.warn(:security, "[WARN] AST classification error on non-shell input, continuing to synthesis deny layers: #{display_command(e.message)}")
|
|
220
227
|
@audit.log_audit("classifier_error", command: cmd_str, reason: "#{e.class}: #{e.message}",
|
|
221
228
|
decision: "synthesis_layers")
|
|
222
229
|
else
|
|
223
|
-
Rubik::Log.warn(:security, "[WARN] AST classification error, failing closed: #{e.class}: #{e.message}")
|
|
230
|
+
Rubik::Log.warn(:security, "[WARN] AST classification error, failing closed: #{e.class}: #{display_command(e.message)}")
|
|
224
231
|
block_on_classifier_failure!(cmd_str, e)
|
|
225
232
|
end
|
|
226
233
|
end
|
|
@@ -233,15 +240,21 @@ module Rubik
|
|
|
233
240
|
|
|
234
241
|
@audit.log_audit("blocked_command", command: cmd_str, reason: "dangerous_pattern")
|
|
235
242
|
raise BlockedWriteError.new(
|
|
236
|
-
"Dangerous command execution blocked: #{cmd_str}",
|
|
243
|
+
"Dangerous command execution blocked: #{display_command(cmd_str)}",
|
|
237
244
|
kind: :dangerous_pattern,
|
|
238
|
-
blocked_command: cmd_str,
|
|
245
|
+
blocked_command: display_command(cmd_str),
|
|
239
246
|
rule_name: "dangerous_pattern"
|
|
240
247
|
)
|
|
241
248
|
end
|
|
242
249
|
|
|
243
250
|
private
|
|
244
251
|
|
|
252
|
+
# Human-facing rendering only; the shared helper keeps every block-error
|
|
253
|
+
# raise site consistent. Raw bytes still drive execution and the audit.
|
|
254
|
+
def display_command(value)
|
|
255
|
+
Rubik::Security.display_command(value)
|
|
256
|
+
end
|
|
257
|
+
|
|
245
258
|
# Shellword tokenization for probe-shape detection; nil when the string
|
|
246
259
|
# has none (unbalanced quotes). The caller fails closed on nil rather
|
|
247
260
|
# than guessing with whitespace splitting — a quote-corrupted command
|
|
@@ -304,7 +317,7 @@ module Rubik
|
|
|
304
317
|
def dangerous_segment_report_or_nil(commands)
|
|
305
318
|
SegmentReport.build(commands)
|
|
306
319
|
rescue StandardError => e
|
|
307
|
-
Rubik::Log.warn(:security, "[Guard] segment report failed: #{e.class}: #{e.message}")
|
|
320
|
+
Rubik::Log.warn(:security, "[Guard] segment report failed: #{e.class}: #{display_command(e.message)}")
|
|
308
321
|
nil
|
|
309
322
|
end
|
|
310
323
|
|
|
@@ -318,9 +331,9 @@ module Rubik
|
|
|
318
331
|
# the exemption is disabled, so safe_probe? would be constantly
|
|
319
332
|
# false and the variant-(a) probe guidance would be dead code.
|
|
320
333
|
raise BlockedWriteError.new(
|
|
321
|
-
"Dangerous command execution blocked: #{cmd_str} (reason: #{reason})",
|
|
334
|
+
"Dangerous command execution blocked: #{display_command(cmd_str)} (reason: #{reason})",
|
|
322
335
|
kind: :dangerous_command,
|
|
323
|
-
blocked_command: cmd_str,
|
|
336
|
+
blocked_command: display_command(cmd_str),
|
|
324
337
|
rule_name: dangerous_rule_name(ast.commands) || (expression_reason ? "expression_level" : "dangerous_pattern"),
|
|
325
338
|
probe_like: probe_shape?(cmd_str),
|
|
326
339
|
segment_report: report,
|
|
@@ -341,7 +354,7 @@ module Rubik
|
|
|
341
354
|
theme = (effective_shell.respond_to?(:ui_theme) && effective_shell.ui_theme) ||
|
|
342
355
|
(defined?(Rubik::UI::Theme) ? Rubik::UI::Theme.new : nil)
|
|
343
356
|
|
|
344
|
-
question = "Allow unclassified command execution: '#{cmd_str}'?"
|
|
357
|
+
question = "Allow unclassified command execution: '#{display_command(cmd_str)}'?"
|
|
345
358
|
answer = if defined?(Rubik::UI::Approvals)
|
|
346
359
|
Rubik::UI::Approvals.keypress_yes_no(effective_shell, question, theme: theme, default: "n")
|
|
347
360
|
else
|
|
@@ -357,11 +370,11 @@ module Rubik
|
|
|
357
370
|
def block_unknown_command!(cmd_str)
|
|
358
371
|
@audit.log_audit("blocked_command", command: cmd_str, reason: "unknown_command")
|
|
359
372
|
raise BlockedWriteError.new(
|
|
360
|
-
"Unknown command execution blocked (fail-closed): #{cmd_str}. The binary is not in the " \
|
|
373
|
+
"Unknown command execution blocked (fail-closed): #{display_command(cmd_str)}. The binary is not in the " \
|
|
361
374
|
"command database, so its effects cannot be classified. If it is genuinely safe, the " \
|
|
362
375
|
"operator can allowlist the exact prefix: !allow-cmd add \"<binary> [args]\"",
|
|
363
376
|
kind: :unknown_command,
|
|
364
|
-
blocked_command: cmd_str,
|
|
377
|
+
blocked_command: display_command(cmd_str),
|
|
365
378
|
rule_name: "unknown_command",
|
|
366
379
|
probe_like: probe_shape?(cmd_str),
|
|
367
380
|
segment_report: nil
|
|
@@ -372,9 +385,9 @@ module Rubik
|
|
|
372
385
|
@audit.log_audit("blocked_command", command: cmd_str, reason: "parse_ambiguous",
|
|
373
386
|
parse_warnings: ast.parse_warnings.to_a.size)
|
|
374
387
|
raise BlockedWriteError.new(
|
|
375
|
-
"Command AST could not be fully parsed (tree-sitter syntax error); execution blocked (fail-closed): #{cmd_str}",
|
|
388
|
+
"Command AST could not be fully parsed (tree-sitter syntax error); execution blocked (fail-closed): #{display_command(cmd_str)}",
|
|
376
389
|
kind: :parse_ambiguous,
|
|
377
|
-
blocked_command: cmd_str,
|
|
390
|
+
blocked_command: display_command(cmd_str),
|
|
378
391
|
rule_name: "parse_ambiguous",
|
|
379
392
|
probe_like: probe_shape?(cmd_str),
|
|
380
393
|
segment_report: nil
|
|
@@ -444,9 +457,9 @@ module Rubik
|
|
|
444
457
|
verify_command_fallback_regex!(cmd_str)
|
|
445
458
|
@audit.log_audit("blocked_command", command: cmd_str, reason: "classifier_error")
|
|
446
459
|
raise BlockedWriteError.new(
|
|
447
|
-
"AST evaluation failed, so the command could not be classified; execution blocked (fail-closed): #{cmd_str}",
|
|
460
|
+
"AST evaluation failed, so the command could not be classified; execution blocked (fail-closed): #{display_command(cmd_str)}",
|
|
448
461
|
kind: :classifier_error,
|
|
449
|
-
blocked_command: cmd_str,
|
|
462
|
+
blocked_command: display_command(cmd_str),
|
|
450
463
|
rule_name: "classifier_error",
|
|
451
464
|
probe_like: probe_shape?(cmd_str),
|
|
452
465
|
segment_report: nil
|
|
@@ -2,6 +2,19 @@
|
|
|
2
2
|
|
|
3
3
|
module Rubik
|
|
4
4
|
module Security
|
|
5
|
+
CONTROL_ESCAPES = { "\n" => "\\n", "\r" => "\\r", "\t" => "\\t", "\0" => "\\0", "\e" => "\\e" }.freeze
|
|
6
|
+
CONTROL_CHAR_PATTERN = /[\x00-\x1F\x7F\u0080-\u009F]/
|
|
7
|
+
|
|
8
|
+
# Escape control characters before command text reaches human- or
|
|
9
|
+
# model-facing output (errors, warnings, approval prompts). Raw bytes still
|
|
10
|
+
# drive classification, execution and the JSONL audit record. Shared so
|
|
11
|
+
# every BlockedWriteError raise site renders identically (#638).
|
|
12
|
+
def self.display_command(value)
|
|
13
|
+
value.to_s.scrub.gsub(CONTROL_CHAR_PATTERN) do |ch|
|
|
14
|
+
CONTROL_ESCAPES.fetch(ch) { format("\\x%02X", ch.ord) }
|
|
15
|
+
end
|
|
16
|
+
end
|
|
17
|
+
|
|
5
18
|
# Carries structured context (command, rule name, probe-ness, block kind,
|
|
6
19
|
# offending path) so callers can render situation-specific guidance
|
|
7
20
|
# instead of regex-munging #message. Kept in its own file: consumers that
|
data/lib/rubik/security/guard.rb
CHANGED
|
@@ -174,8 +174,17 @@ module Rubik
|
|
|
174
174
|
@command_gate.allow_safe_probes = val
|
|
175
175
|
end
|
|
176
176
|
|
|
177
|
-
def verify_command_safety!(cmd, shell: nil
|
|
178
|
-
@command_gate.verify_command_safety!(cmd, shell: shell
|
|
177
|
+
def verify_command_safety!(cmd, shell: nil)
|
|
178
|
+
@command_gate.verify_command_safety!(cmd, shell: shell)
|
|
179
|
+
end
|
|
180
|
+
|
|
181
|
+
# Restricted seam for non-shell source (synthesis): the permissive
|
|
182
|
+
# allow_unknown path is NOT reachable from the general shell gate, so a
|
|
183
|
+
# future caller cannot accidentally let an unclassified binary through
|
|
184
|
+
# by forwarding an option. Synthesis keeps its own regex + RubyVM deny
|
|
185
|
+
# layers; this gate only supplies classifier-crash diagnostics.
|
|
186
|
+
def verify_synthesis_source!(source)
|
|
187
|
+
@command_gate.verify_command_safety!(source, allow_unknown: true)
|
|
179
188
|
end
|
|
180
189
|
|
|
181
190
|
def verify_command_fallback_regex!(cmd_str)
|
|
@@ -103,10 +103,11 @@ module Rubik
|
|
|
103
103
|
write_targets.uniq.each do |wp|
|
|
104
104
|
if critical_path?(wp)
|
|
105
105
|
@audit.log_audit("blocked_command", command: cmd_str, reason: "critical_path_write", path: wp)
|
|
106
|
+
display = Rubik::Security.display_command(cmd_str)
|
|
106
107
|
raise BlockedWriteError.new(
|
|
107
|
-
"Command write to critical path blocked: #{wp} in `#{
|
|
108
|
+
"Command write to critical path blocked: #{wp} in `#{display}`",
|
|
108
109
|
kind: :critical_path_write,
|
|
109
|
-
blocked_command:
|
|
110
|
+
blocked_command: display,
|
|
110
111
|
path: wp
|
|
111
112
|
)
|
|
112
113
|
end
|
|
@@ -119,20 +120,22 @@ module Rubik
|
|
|
119
120
|
resolved = Rubik::Platform.resolved_path(wp, strict: true)
|
|
120
121
|
if resolved.nil?
|
|
121
122
|
@audit.log_audit("blocked_command", command: cmd_str, reason: "path_resolution_failed", path: wp)
|
|
123
|
+
display = Rubik::Security.display_command(cmd_str)
|
|
122
124
|
raise BlockedWriteError.new(
|
|
123
|
-
"Command write blocked: path could not be safely resolved: #{wp} in `#{
|
|
125
|
+
"Command write blocked: path could not be safely resolved: #{wp} in `#{display}`",
|
|
124
126
|
kind: :critical_path_write,
|
|
125
|
-
blocked_command:
|
|
127
|
+
blocked_command: display,
|
|
126
128
|
path: wp
|
|
127
129
|
)
|
|
128
130
|
end
|
|
129
131
|
next unless critical_path?(resolved)
|
|
130
132
|
|
|
131
133
|
@audit.log_audit("blocked_command", command: cmd_str, reason: "critical_path_write_symlink", path: wp, resolved: resolved)
|
|
134
|
+
display = Rubik::Security.display_command(cmd_str)
|
|
132
135
|
raise BlockedWriteError.new(
|
|
133
|
-
"Command write to critical path blocked (symlink-resolved): #{wp} -> #{resolved} in `#{
|
|
136
|
+
"Command write to critical path blocked (symlink-resolved): #{wp} -> #{resolved} in `#{display}`",
|
|
134
137
|
kind: :critical_path_write,
|
|
135
|
-
blocked_command:
|
|
138
|
+
blocked_command: display,
|
|
136
139
|
path: wp
|
|
137
140
|
)
|
|
138
141
|
end
|