rubik 0.9.0 → 0.9.1

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 (57) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +108 -43
  4. data/README.md +5 -1
  5. data/lib/rubik/adapter/base.rb +19 -0
  6. data/lib/rubik/adapter/generic.rb +0 -14
  7. data/lib/rubik/adapter/node.rb +2 -0
  8. data/lib/rubik/ast/treesitter/zig_walker.rb +15 -2
  9. data/lib/rubik/cli/workspace_trust.rb +16 -0
  10. data/lib/rubik/config/defaults.rb +23 -0
  11. data/lib/rubik/config/store.rb +14 -0
  12. data/lib/rubik/kernel/dispatcher.rb +4 -4
  13. data/lib/rubik/log.rb +2 -1
  14. data/lib/rubik/lsp/client.rb +83 -180
  15. data/lib/rubik/lsp/document_store.rb +209 -0
  16. data/lib/rubik/mcp/client.rb +4 -3
  17. data/lib/rubik/mcp/manager.rb +6 -2
  18. data/lib/rubik/mcp/transport/stdio.rb +51 -9
  19. data/lib/rubik/orchestrator/goal_session.rb +505 -0
  20. data/lib/rubik/orchestrator/subagent/instance.rb +4 -0
  21. data/lib/rubik/orchestrator/subagent/journal.rb +2 -1
  22. data/lib/rubik/orchestrator/subagent/questioner.rb +21 -6
  23. data/lib/rubik/orchestrator/subagent/step_runner.rb +1 -1
  24. data/lib/rubik/orchestrator/subagent/teardown.rb +4 -0
  25. data/lib/rubik/orchestrator/subagent/transcript_formatter.rb +2 -1
  26. data/lib/rubik/orchestrator.rb +1 -0
  27. data/lib/rubik/platform.rb +15 -0
  28. data/lib/rubik/plugin/storage.rb +20 -29
  29. data/lib/rubik/repl/commands/agent_context.rb +1 -1
  30. data/lib/rubik/repl/commands/agent_execution.rb +7 -470
  31. data/lib/rubik/repl/commands/buffer.rb +1 -1
  32. data/lib/rubik/repl/commands/lsp.rb +1 -1
  33. data/lib/rubik/repl/input_loop.rb +1 -1
  34. data/lib/rubik/repl/lifecycle.rb +28 -0
  35. data/lib/rubik/runtime/manifest_store.rb +116 -0
  36. data/lib/rubik/runtime/overlay_storage.rb +247 -196
  37. data/lib/rubik/runtime/task_manager.rb +7 -2
  38. data/lib/rubik/runtime.rb +1 -0
  39. data/lib/rubik/security/allowlist.rb +167 -0
  40. data/lib/rubik/security/audit_log.rb +72 -0
  41. data/lib/rubik/security/classifier/classifier.rb +8 -0
  42. data/lib/rubik/security/command_gate.rb +567 -0
  43. data/lib/rubik/security/guard.rb +88 -1075
  44. data/lib/rubik/security/path_policy.rb +117 -0
  45. data/lib/rubik/security/synthesis_gate.rb +300 -0
  46. data/lib/rubik/security.rb +5 -0
  47. data/lib/rubik/storage/ranking.rb +113 -0
  48. data/lib/rubik/storage/store.rb +2 -92
  49. data/lib/rubik/storage/transcript_indexer.rb +2 -3
  50. data/lib/rubik/tools/builtins/grep.rb +2 -3
  51. data/lib/rubik/tools/builtins/lifecycle.rb +90 -87
  52. data/lib/rubik/tools/builtins/synthesis.rb +3 -0
  53. data/lib/rubik/tools/lifecycle_rollbacks.rb +87 -0
  54. data/lib/rubik/tools/native_search.rb +2 -1
  55. data/lib/rubik/tools/truncator.rb +25 -0
  56. data/lib/rubik/version.rb +1 -1
  57. metadata +11 -1
@@ -1,141 +1,39 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "json"
4
- require "time"
5
- require "fileutils"
6
- require "shellwords"
7
- require_relative "../platform"
8
- require_relative "classifier"
9
- require_relative "errors"
10
- require_relative "redactor"
3
+ require_relative "audit_log"
4
+ require_relative "allowlist"
5
+ require_relative "command_gate"
6
+ require_relative "path_policy"
7
+ require_relative "synthesis_gate"
11
8
 
12
9
  module Rubik
13
10
  module Security
11
+ # Guard is now the delegating facade of the security stack (#403): it
12
+ # composes the five deep modules (AuditLog → Allowlist / PathPolicy /
13
+ # SynthesisGate / CommandGate) and preserves the historical one-object
14
+ # contract for every caller — explicit delegating defs, spelled-out
15
+ # kwargs, no method_missing — so duck-typed respond_to? checks
16
+ # (config_wiring.rb, run_synthesis_gate) keep working on real methods.
17
+ # The security-relevant bodies live in the modules; this file only
18
+ # routes and holds the composition root (initialize + for_config).
14
19
  class Guard
15
- DEFAULT_CRITICAL_PATTERNS = [
16
- ".git/**",
17
- ".rubik/**",
18
- "**/.rubik/**",
19
- ".env*",
20
- "secrets.*",
21
- "*.pem",
22
- "*.key",
23
- "id_rsa*"
24
- ].freeze
20
+ # Historical Guard:: constant surface, aliased to the module that now
21
+ # owns each table — zero churn for tests and callers (the constants
22
+ # are the same frozen objects, not copies).
23
+ SYNTHESIS_CAPABILITIES = SynthesisGate::SYNTHESIS_CAPABILITIES
24
+ FORBIDDEN_SYNTHESIS_NODES = SynthesisGate::FORBIDDEN_SYNTHESIS_NODES
25
+ FORBIDDEN_SYNTHESIS_CALLS = SynthesisGate::FORBIDDEN_SYNTHESIS_CALLS
26
+ FORBIDDEN_SYNTHESIS_BARE_CALLS = SynthesisGate::FORBIDDEN_SYNTHESIS_BARE_CALLS
27
+ FORBIDDEN_SYNTHESIS_CONSTS = SynthesisGate::FORBIDDEN_SYNTHESIS_CONSTS
28
+ FORBIDDEN_SYNTHESIS_NETWORK_CONSTS = SynthesisGate::FORBIDDEN_SYNTHESIS_NETWORK_CONSTS
29
+ DANGEROUS_SYNTHESIS_PATTERNS = SynthesisGate::DANGEROUS_SYNTHESIS_PATTERNS
30
+ DEFAULT_CRITICAL_PATTERNS = PathPolicy::DEFAULT_CRITICAL_PATTERNS
31
+ DANGEROUS_COMMAND_PATTERNS = CommandGate::DANGEROUS_COMMAND_PATTERNS
32
+ RAW_ALLOWLIST_UNSAFE_PATTERN = Allowlist::RAW_ALLOWLIST_UNSAFE_PATTERN
33
+ MASK_PATTERNS = AuditLog::MASK_PATTERNS
25
34
 
26
- # Pipe-to-interpreter (the curl|bash RCE shape). This pattern lives in
27
- # the UN-BYPASSABLE fallback gate: verify_command_fallback_regex! runs
28
- # even on allowlisted and safe-probe commands, so anything it matches
29
- # cannot be allowlisted away — keep any widening surgical. The
30
- # intermediaries between the pipe and the interpreter are flag-less
31
- # (sudo bash, env sh); flag-bearing forms (sudo -u root bash) are
32
- # already blocked earlier by the AST classifier's delegation rules
33
- # when it is healthy, so the fallback does not need to cover them.
34
- # Word boundaries on both ends also stop substring matches like
35
- # "mycurl ... | sh" or "| shadowtool".
36
- PIPE_TO_INTERPRETER_PATTERN = /
37
- \b(?:curl|wget)\b.*\|\s*
38
- (?:(?:sudo|doas|env|nohup|nice|stdbuf|xargs)\s+)*
39
- (?:bash|zsh|dash|ksh|fish|sh|pwsh|python\d?|ruby|perl|node|php|lua)\b
40
- /xi
41
-
42
- DANGEROUS_COMMAND_PATTERNS = [
43
- Regexp.new(
44
- 'rm\s+(?:-[a-z0-9-]+\s+)*(?:-[a-z0-9]*r[a-z0-9]*f[a-z0-9]*|-[a-z0-9]*f[a-z0-9]*r[a-z0-9]*|' \
45
- '(?:(?:-[a-z0-9]*r[a-z0-9]*|--recursive)\s+(?:-[a-z0-9]*f[a-z0-9]*|--force))|' \
46
- '(?:(?:-[a-z0-9]*f[a-z0-9]*|--force)\s+(?:-[a-z0-9]*r[a-z0-9]*|--recursive)))' \
47
- '\s+(?:-[a-z0-9-]+\s+)*(?:--\s+)?/(?:\*|\.+(?![a-zA-Z0-9_-])|(?![a-zA-Z0-9_.-]))',
48
- Regexp::IGNORECASE
49
- ),
50
- PIPE_TO_INTERPRETER_PATTERN,
51
- /:\(\)\{\s*:\|:&\s*\};:/, # fork bomb
52
- %r{\bdd\s+.*(?:if=|of=/dev/)}i,
53
- /\bmkfs(?:\.\w+)?\b/i,
54
- /\b(?:shutdown|reboot|poweroff|halt)\b(?:\s+.*)?/i,
55
- /\b(?:Format-Volume|Clear-Disk|Initialize-Disk|Remove-Partition|Stop-Computer|Restart-Computer)\b/i,
56
- /\bdiskpart\b/i,
57
- /\brm\s+.*--no-preserve-root/i,
58
- %r{del\s+.*/s.*[a-z]:\\}i,
59
- %r{erase\s+.*/s.*[a-z]:\\}i,
60
- %r{rmdir\s+.*/s.*[a-z]:\\}i,
61
- %r{rd\s+.*/s.*[a-z]:\\}i,
62
- /format\s+[a-z]:/i,
63
- /Remove-Item\s+.*-Recurse.*[a-z]:\\/i,
64
- /%0\|%0/
65
- ].freeze
66
-
67
- # Display caps for the blocked-segment report (guidance rendering, not
68
- # gate semantics): one segment's argv rendering and the one-line
69
- # wrapper preview never exceed these.
70
- SEGMENT_DISPLAY_CAP = 120
71
- WRAPPER_PREVIEW_CAP = 60
72
-
73
- # Synth-unsafe patterns. These catch RCE-y escapes a synthesis step might
74
- # smuggle past the classifier (tuned for shell commands, not Ruby):
75
- # `method(:x).call`, variable send/public_send/__send__, eval/binding.eval,
76
- # and backticks/%x. The interpreter/eval lines precede the backtick and %x
77
- # patterns so strings merely *mentioning* backticks aren't mislabelled.
78
- # Symbol-level denials live in SYNTHESIS_CAPABILITIES below; the two
79
- # layers are equivalence-locked by test_synthesis_capability_coverage.rb.
80
- DANGEROUS_SYNTHESIS_PATTERNS = [
81
- /\b(?:send|public_send|__send__)\s*[( \s]/,
82
- /\.(?:send|public_send|__send__)\b/,
83
- /\b(?:method|public_method|singleton_method)\s*(?:\(\s*[:"']|\s+[:"'])/i,
84
- /\beval\s*[( \s]/,
85
- /\bbinding\s*\.\s*eval\b/i,
86
- /\b(?:instance_eval|class_eval|module_eval)\b/,
87
- /\b(?:instance_variable_get|instance_variable_set)\b/,
88
- /\b(?:const_set|const_get|remove_const)\b/,
89
- /(?:^|[;{\n\r])\s*(?:system|exec|spawn)\b|\b(?:system|exec|spawn)\s*\(/,
90
- /(?:^|[;{\n\r])\s*fork\b|\bfork\s*(?:do|\{|\()/,
91
- /\bsyscall\s*\(/,
92
- /\bexit!/,
93
- /\bIO\s*\.\s*popen\b/,
94
- /\bOpen3\s*\.\s*(?:capture2|capture2e|capture3|popen2|popen2e|popen3|pipeline)\b/,
95
- /\bProcess\s*\.\s*(?:kill|fork|daemon|spawn|exec)\b/,
96
- /\bKernel\s*\.\s*(?:exec|system|fork|spawn|syscall|exit!)\b/,
97
- # Unmanaged background threads survive context disposal — the exact
98
- # "Leaked Side Effects" anti-pattern (AGENTS.md §5).
99
- /\bThread\s*\.\s*(?:new|fork|start)\b/,
100
- /\bPathname\s*\(/,
101
- /`[^`]*`/,
102
- Regexp.new('%x\s*[({\[<|/]', Regexp::IGNORECASE)
103
- ].freeze
104
-
105
- DANGEROUS_SYSTEM_ROOTS = [
106
- "/", "/root", "/home", "/etc", "/usr", "/var", "/bin", "/sbin", "/lib", "/lib64", "/opt", "/boot", "/dev", "/proc", "/sys"
107
- ].freeze
108
-
109
- MASK_PATTERNS = Rubik::Security::Redactor::PATTERNS
110
-
111
- # Salt version/help probe'ları (Plan: safe-probe muafiyeti): a command
112
- # whose ONLY arguments are these flags is read-only by construction.
113
- SAFE_PROBE_FLAGS = ["--version", "-v", "--help", "-h"].freeze
114
-
115
- # Shell metacharacters that make a raw (AST-less) token-prefix allowlist
116
- # match dishonest: they can join, redirect, substitute, or line-split
117
- # the string, so "the first tokens match" would not mean "the whole
118
- # simple command matches". The classifier-crash rescue only accepts a
119
- # single simple command; anything else fails closed.
120
- RAW_ALLOWLIST_UNSAFE_PATTERN = /[;&|<>`$(){}\[\]\\\n\r]/
121
-
122
- attr_reader :audit_log_path
123
- attr_accessor :shell, :root_dir
124
-
125
- # Live-reconfigurable audit destination (ConfigWiring applies config
126
- # changes in place — zero restart). Same blank-means-disabled semantics
127
- # as for_config; non-string values pass through and surface loudly in
128
- # log_audit's unconditional warn.
129
- def audit_log_path=(val)
130
- @audit_log_path = val.is_a?(String) && val.strip.empty? ? nil : val
131
- end
132
-
133
- # Default audit location, resolved at call time (not a load-time
134
- # constant) so Platform.home_dir stubs in tests and runtime HOME
135
- # changes are honored. Single source shared by the constructor
136
- # default and for_config.
137
35
  def self.default_audit_log_path
138
- File.join(Rubik::Platform.home_dir, ".rubik", "audit.log")
36
+ AuditLog.default_audit_log_path
139
37
  end
140
38
 
141
39
  # The one sanctioned way to build a policy-carrying Guard from operator
@@ -177,1001 +75,116 @@ module Rubik
177
75
  )
178
76
  end
179
77
 
180
- def initialize(custom_patterns: [], command_allowlist: [], allow_safe_probes: true,
181
- audit_log_path: Guard.default_audit_log_path, root_dir: nil, shell: nil)
182
- @critical_patterns = (DEFAULT_CRITICAL_PATTERNS + custom_patterns).uniq
183
- @command_allowlist = normalize_allowlist(command_allowlist)
184
- @allow_safe_probes = allow_safe_probes == true
185
- @audit_log_path = audit_log_path
186
- @root_dir = root_dir
187
- @shell = shell
78
+ # Spawn-boundary entry: delegate to the module implementation with the
79
+ # caller's guard injected — the duck-type check runs on it (facade
80
+ # instances answer verify_synthesis_safety! through a real method).
81
+ def self.run_synthesis_gate(guard, code)
82
+ SynthesisGate.run_synthesis_gate(guard, code)
188
83
  end
189
84
 
190
- def workspace_trust_candidate_allowed?(cmd_str, ast = nil)
191
- return false if cmd_str.to_s.match?(RAW_ALLOWLIST_UNSAFE_PATTERN)
192
-
193
- ast ||= begin
194
- Rubik::Security::Classifier.classify(cmd_str.to_s)
195
- rescue StandardError
196
- nil
197
- end
198
- return false unless ast
199
- return false if ast.respond_to?(:parse_warnings) && ast.parse_warnings.to_a.any?
200
- return false unless ast.respond_to?(:commands) && ast.commands.to_a.size == 1
201
-
202
- cmd = ast.commands.first
203
- return false if cmd.respond_to?(:inner_commands) && cmd.inner_commands && !cmd.inner_commands.empty?
204
-
205
- effective_root = @root_dir || Dir.pwd
206
- return false unless defined?(Rubik::CLI::WorkspaceTrust) && Rubik::CLI::WorkspaceTrust.trusted?(effective_root)
207
- return false unless defined?(Rubik::Runtime::Discovery)
208
-
209
- Rubik::Runtime::Discovery.recognized_candidate?(cmd_str, root_dir: effective_root)
85
+ def self.synthesis_capability_layer(field)
86
+ SynthesisGate.synthesis_capability_layer(field)
210
87
  end
211
88
 
212
- # security.allow_safe_probes — operator-managed toggle (live-reconfigurable
213
- # via ConfigWiring, zero restart). Default ON.
214
- def allow_safe_probes?
215
- @allow_safe_probes
89
+ # Composition root: one shared AuditLog leaf, one Allowlist, one
90
+ # PathPolicy, and the gates that consume them. The kwarg surface is
91
+ # frozen (8 call sites + for_config).
92
+ def initialize(custom_patterns: [], command_allowlist: [], allow_safe_probes: true,
93
+ audit_log_path: Guard.default_audit_log_path, root_dir: nil, shell: nil)
94
+ @audit = AuditLog.new(audit_log_path)
95
+ @allowlist = Allowlist.new(command_allowlist)
96
+ @path_policy = PathPolicy.new(custom_patterns: custom_patterns, audit: @audit)
97
+ @command_gate = CommandGate.new(
98
+ allowlist: @allowlist,
99
+ audit: @audit,
100
+ path_policy: @path_policy,
101
+ allow_safe_probes: allow_safe_probes,
102
+ root_dir: root_dir,
103
+ shell: shell
104
+ )
105
+ @synthesis_gate = SynthesisGate.new(audit: @audit)
216
106
  end
217
107
 
218
- def allow_safe_probes=(val)
219
- # Accept both booleans and stringy config values ("true"/"false").
220
- @allow_safe_probes = val == true || val.to_s.downcase == "true"
108
+ # ── AuditLog (shared leaf) ──────────────────────────────────────────
109
+ def audit_log_path
110
+ @audit.audit_log_path
221
111
  end
222
112
 
223
- # True when the command's arguments are exclusively version/help flags
224
- # (e.g. `bash --version`, `node -v`, `git --help`); no other arguments.
225
- # Gate is the operator toggle; shape detection lives in probe_shape? so
226
- # blocked-error annotation can label probe-shaped commands even when the
227
- # exemption is disabled — otherwise the variant-(a) probe guidance would
228
- # be unreachable (a probe only reaches the block path when disabled).
229
- def safe_probe?(cmd_str)
230
- return false unless @allow_safe_probes
231
-
232
- probe_shape?(cmd_str)
113
+ def audit_log_path=(val)
114
+ @audit.audit_log_path = val
233
115
  end
234
116
 
235
- def probe_shape?(cmd_str)
236
- str = cmd_str.to_s
237
- return false if str.match?(/[\r\n]/)
238
-
239
- tokens = begin
240
- Shellwords.split(str)
241
- rescue ArgumentError
242
- str.split(/\s+/)
243
- end
244
- return false if tokens.size < 2
117
+ def mask_text(text)
118
+ @audit.mask_text(text)
119
+ end
245
120
 
246
- tokens[1..].all? { |t| SAFE_PROBE_FLAGS.include?(t) }
121
+ def log_audit(action, details = {})
122
+ @audit.log_audit(action, details)
247
123
  end
248
124
 
249
- # Operator-controlled command allowlist (Plan: komut-allowlist-güvenlik-kapısı).
250
- # Entries are token-prefixes: "node" allows every node invocation (broad);
251
- # "node .gitnexus/run.cjs" allows only that script (narrow — preferred).
252
- # Applied AFTER classifier verdict, BEFORE the raise, and the catastrophic
253
- # fallback regex still runs afterwards (defense-in-depth is never skipped).
125
+ # ── Allowlist ────────────────────────────────────────────────────────
254
126
  def command_allowlist
255
- @command_allowlist.dup
127
+ @allowlist.command_allowlist
256
128
  end
257
129
 
258
130
  def allowed_commands=(entries)
259
- @command_allowlist = normalize_allowlist(entries)
131
+ @allowlist.allowed_commands = entries
260
132
  end
261
133
  alias set_allowed_commands allowed_commands=
262
134
 
263
135
  def command_allowlisted?(ast, cmd_str: nil)
264
- _ = cmd_str
265
- return false if @command_allowlist.empty?
266
- return false unless ast.respond_to?(:commands)
267
-
268
- ast_commands = ast.commands.to_a
269
- return false if ast_commands.empty?
270
-
271
- # EVERY dangerous segment (recursively incl. pipeline inner commands)
272
- # must match an entry — a single allowlisted prefix cannot rescue
273
- # `allowlisted-cmd && rm -rf /` chains.
274
- ast_commands.all? { |c| command_matches_allowlist?(c) }
275
- end
276
-
277
- private
278
-
279
- def normalize_allowlist(entries)
280
- Array(entries).filter_map do |e|
281
- tokens = e.to_s.strip.split(/\s+/).reject(&:empty?)
282
- tokens unless tokens.empty?
283
- end
284
- end
285
-
286
- def canonical_binary_path(bin)
287
- return nil if bin.nil? || bin.to_s.empty?
288
-
289
- str = bin.to_s
290
- if str.include?("/") || str.include?("\\") || File.exist?(str)
291
- Rubik::Platform.normalize_path(File.expand_path(str))
292
- else
293
- resolved = Rubik::Platform.which(str)
294
- resolved ? Rubik::Platform.normalize_path(resolved) : nil
295
- end
296
- end
297
-
298
- def binary_allowlist_match?(arg, token)
299
- return true if arg == token
300
- # Windows exe-alias fast path (#103): on a windows host "node.exe"
301
- # IS the allowlisted "node" — a lexical alias, no filesystem probe.
302
- # The canonical-path probe below resolves through Platform.which +
303
- # File.file?, a second host seam the windows? stub cannot cover (a
304
- # linux host has no node.exe on disk, so the probe fails and the
305
- # allowlist would dead-close). On a posix host the alias is FALSE:
306
- # node.exe is a different binary than node there.
307
- return true if windows_executable_alias?(arg, token)
308
-
309
- c_arg = canonical_binary_path(arg)
310
- c_token = canonical_binary_path(token)
311
-
312
- return true if c_arg && c_token && Rubik::Platform.path_equal?(c_arg, c_token)
313
-
314
- false
136
+ @allowlist.command_allowlisted?(ast, cmd_str: cmd_str)
315
137
  end
316
138
 
317
- # True when arg carries an executable extension from PATHEXT and its
318
- # stem equals the token (case-insensitive — windows path semantics).
319
- # Bare stems only: a path-form arg ("C:/x/node.exe") keeps going
320
- # through the canonical-path probe, which resolves both sides.
321
- def windows_executable_alias?(arg, token)
322
- return false unless Rubik::Platform.windows?
323
-
324
- ext = ::File.extname(arg)
325
- return false if ext.empty? || !Rubik::Platform.pathext.include?(ext.downcase)
326
-
327
- arg.delete_suffix(ext).casecmp?(token)
328
- end
329
-
330
- def command_matches_allowlist?(result)
331
- # Missing argv (e.g. empty invocation) can never be allowlisted.
332
- argv = result.respond_to?(:argv) ? result.argv : nil
333
- return false if argv.nil? || argv.empty?
334
-
335
- # Dangerous shell builtins (`source`, `.`) are never rescuable by
336
- # allowlist: they execute arbitrary file content by design.
337
- binary = argv[0].to_s
338
- return false if Rubik::Security::Classifier::Matcher::BUILTIN_DANGEROUS_CMDS.include?(binary)
339
-
340
- # W6: If this command wraps inner commands, EVERY inner command must also match allowlist
341
- if result.respond_to?(:inner_commands) && result.inner_commands && !result.inner_commands.empty? && !result.inner_commands.all? do |inner|
342
- command_matches_allowlist?(inner)
343
- end
344
- return false
345
- end
346
-
347
- @command_allowlist.any? do |entry|
348
- next false if entry.length > argv.length
349
-
350
- entry.each_with_index.all? do |token, i|
351
- arg = argv[i]
352
- if i.zero?
353
- binary_allowlist_match?(arg, token)
354
- else
355
- arg == token
356
- end
357
- end
358
- end
359
- end
360
-
361
- public
362
-
139
+ # ── PathPolicy ───────────────────────────────────────────────────────
363
140
  def verify_path_write!(path)
364
- return true if path.nil? || path.to_s.strip.empty?
365
-
366
- raw = Rubik::Platform.normalize_path_raw(path.to_s)
367
- expanded = Rubik::Platform.normalize_path_raw(File.expand_path(path.to_s))
368
-
369
- # Check raw relative path, expanded path, and relative-from-pwd
370
- candidates = [raw, expanded]
371
- begin
372
- pwd_raw = Rubik::Platform.normalize_path_raw(Dir.pwd)
373
- candidates << expanded.delete_prefix("#{pwd_raw}/") if expanded.start_with?("#{pwd_raw}/")
374
- rescue SystemCallError, ArgumentError
375
- nil
376
- end
377
-
378
- candidates.uniq.each do |c|
379
- if critical_path?(c)
380
- log_audit("blocked_write", path: path.to_s, reason: "critical_path")
381
- raise BlockedWriteError, "Write blocked on critical path: #{path}"
382
- end
383
- end
384
-
385
- # Symlink re-check (fail-closed): the lexical candidates above cannot
386
- # see `foo -> .git/config`. Resolve the deepest EXISTING ancestor and
387
- # re-check; a missing tail is reattached lexically so ordinary
388
- # new-file writes resolve to their lexical equivalent. A nil here
389
- # means containment is unprovable (symlink loop / permission wall).
390
- resolved = Rubik::Platform.resolved_path(path.to_s, strict: true)
391
- if resolved.nil?
392
- log_audit("blocked_write", path: path.to_s, reason: "path_resolution_failed")
393
- raise BlockedWriteError, "Write blocked: path could not be safely resolved: #{path}"
394
- end
395
- if critical_path?(resolved)
396
- log_audit("blocked_write", path: path.to_s, reason: "critical_path_symlink", resolved: resolved)
397
- raise BlockedWriteError, "Write blocked on critical path (symlink-resolved): #{path} -> #{resolved}"
398
- end
399
- true
141
+ @path_policy.verify_path_write!(path)
400
142
  end
401
143
 
402
144
  def verify_root_safety!(path)
403
- return true if path.nil? || path.to_s.strip.empty?
404
-
405
- expanded = File.expand_path(path.to_s)
406
- normalized = Rubik::Platform.normalize_path(expanded)
407
- dangerous_roots = Rubik::Platform.dangerous_system_roots
408
-
409
- if dangerous_roots.include?(normalized) ||
410
- Rubik::Platform.drive_root?(expanded) ||
411
- Rubik::Platform.path_equal?(expanded, Rubik::Platform.home_dir)
412
- log_audit("blocked_root_addition", path: expanded, reason: "dangerous_system_root")
413
- raise BlockedWriteError, "Adding dangerous system root as workspace is blocked: #{path} (#{expanded})"
414
- end
415
- true
416
- end
417
-
418
- def critical_path?(path)
419
- norm_path = path.to_s.tr("\\", "/").gsub(%r{^\./}, "")
420
- @critical_patterns.any? do |pattern|
421
- File.fnmatch?(pattern, norm_path, File::FNM_PATHNAME | File::FNM_DOTMATCH) ||
422
- File.fnmatch?("**/#{pattern}", norm_path, File::FNM_PATHNAME | File::FNM_DOTMATCH)
423
- end
424
- end
425
-
426
- def check_critical_path_writes!(ast, cmd_str)
427
- ast_commands = ast.respond_to?(:commands) ? ast.commands.to_a : []
428
- write_targets = ast_commands.flat_map do |c|
429
- targets = Array(c.respond_to?(:write_paths) ? c.write_paths : nil)
430
- cmd_name = c.respond_to?(:command) ? c.command.to_a.first.to_s : ""
431
- targets.concat(c.positionals.to_a) if ["cp", "mv", "tee", "touch", "ln", "install"].include?(cmd_name) && c.respond_to?(:positionals)
432
- targets
433
- end.compact.reject(&:empty?)
434
-
435
- write_targets.concat(ast.write_paths.to_a) if ast.respond_to?(:write_paths)
436
-
437
- write_targets.uniq.each do |wp|
438
- next unless critical_path?(wp)
439
-
440
- log_audit("blocked_command", command: cmd_str, reason: "critical_path_write", path: wp)
441
- raise BlockedWriteError.new(
442
- "Command write to critical path blocked: #{wp} in `#{cmd_str}`",
443
- kind: :critical_path_write,
444
- blocked_command: cmd_str,
445
- path: wp
446
- )
447
- end
448
- end
449
-
450
- # allow_unknown: synthesis verification no longer routes through the
451
- # shell gate (it has its own deny layers: DANGEROUS_SYNTHESIS_PATTERNS
452
- # + AST walk), so no production caller passes true today. The flag
453
- # remains a tested seam for future in-gate verifiers of non-shell
454
- # source; shell-gate callers must keep the default: an UNKNOWN verdict
455
- # means an unvetted binary, and a binary the database cannot classify
456
- # is exactly the one that must not run without operator approval.
457
- def verify_command_safety!(cmd, shell: nil, allow_unknown: false)
458
- cmd_str = cmd.to_s
459
- begin
460
- ast = Rubik::Security::Classifier.classify(cmd_str, shell: shell)
461
- check_critical_path_writes!(ast, cmd_str)
462
- if ast.classification == :dangerous
463
- # Safe-probe exemption (highest-priority friction fix): run the
464
- # catastrophic fallback regex first — it never loosens.
465
- # Strictly single, isolated command without inner commands or chains.
466
- single_cmd = ast.respond_to?(:commands) && ast.commands.to_a.size == 1 &&
467
- ast.respond_to?(:parse_warnings) && ast.parse_warnings.to_a.empty? &&
468
- (!ast.commands.first.respond_to?(:inner_commands) || ast.commands.first.inner_commands.nil? || ast.commands.first.inner_commands.empty?)
469
- if single_cmd && safe_probe?(cmd_str)
470
- verify_command_fallback_regex!(cmd_str)
471
- log_audit("safe_probe", command: cmd_str, reason: "safe_probe_exemption")
472
- return true
473
- end
474
- walk_reason = dangerous_reason(ast.commands)
475
- # Expression-level elevation marks no single command dangerous —
476
- # the per-command walk bottoms out at its sentinel while the
477
- # composed evidence travels on the ExpressionResult itself.
478
- expression_reason = walk_reason == "dangerous_ast" ? expression_level_reason(ast) : nil
479
- reason = expression_reason || walk_reason
480
- # Operator allowlist gate (fail-closed default): the entry must
481
- # cover EVERY dangerous segment recursively; catastrophic fallback
482
- # regex still runs afterwards — allowlisting never bypasses it.
483
- # A bug in the gate itself must fail closed, not fall through to
484
- # the regex-only downgrade below.
485
- allowlisted = begin
486
- command_allowlisted?(ast, cmd_str: cmd_str)
487
- rescue StandardError => e
488
- warn "[Guard] allowlist evaluation failed, failing closed: #{e.class}: #{e.message}"
489
- false
490
- end
491
- if allowlisted
492
- log_audit("allowed_command", command: cmd_str, reason: "operator_allowlist")
493
- verify_command_fallback_regex!(cmd_str)
494
- return true
495
- end
496
- # Enrichment must never be able to un-block: a bug in the report
497
- # walk downgrades to nil here, the raise below still fires.
498
- report = begin
499
- dangerous_segment_report(ast.commands)
500
- rescue StandardError => e
501
- warn "[Guard] segment report failed: #{e.class}: #{e.message}"
502
- nil
503
- end
504
- log_audit("blocked_command", command: cmd_str, reason: reason,
505
- dangerous_segments: segment_count(report))
506
- # probe_shape? (not safe_probe?): probes only reach this raise when
507
- # the exemption is disabled, so safe_probe? would be constantly
508
- # false and the variant-(a) guidance dead code.
509
- raise BlockedWriteError.new(
510
- "Dangerous command execution blocked: #{cmd_str} (reason: #{reason})",
511
- kind: :dangerous_command,
512
- blocked_command: cmd_str,
513
- rule_name: dangerous_rule_name(ast.commands) || (expression_reason ? "expression_level" : "dangerous_pattern"),
514
- probe_like: probe_shape?(cmd_str),
515
- segment_report: report,
516
- classification_reason: expression_reason
517
- )
518
- end
519
-
520
- # UNKNOWN is fail-closed, not pass-through: the matcher rates every
521
- # database-less binary unknown/high, so letting it fall through to
522
- # the catastrophic-only regex would run `socat`/`nmap`/any unlisted
523
- # tool with zero approval while the tool copy advertises fail-closed.
524
- # Allowlist rescue unchanged (every top-level segment must match).
525
- # No safe-probe exemption: an unknown binary's --version still
526
- # executes an unvetted binary — the allowlist is the valve.
527
- if ast.classification == :unknown && !allow_unknown
528
- # Same fail-closed discipline as the dangerous branch: gate
529
- # trouble must never convert this block into a pass.
530
- allowlisted = begin
531
- command_allowlisted?(ast, cmd_str: cmd_str)
532
- rescue StandardError => e
533
- warn "[Guard] allowlist evaluation failed, failing closed: #{e.class}: #{e.message}"
534
- false
535
- end
536
- if allowlisted
537
- log_audit("allowed_command", command: cmd_str, reason: "operator_allowlist")
538
- verify_command_fallback_regex!(cmd_str)
539
- return true
540
- end
541
-
542
- # Workspace Trust Discovery Recognition Gate:
543
- if workspace_trust_candidate_allowed?(cmd_str, ast)
544
- log_audit("allowed_command", command: cmd_str, reason: "workspace_trust_discovery")
545
- verify_command_fallback_regex!(cmd_str)
546
- return true
547
- end
548
-
549
- # Interactive operator approval gate (Antigravity-style single keypress)
550
- effective_shell = shell || @shell
551
- if effective_shell.respond_to?(:interactive_input?) && effective_shell.interactive_input?
552
- # Defense-in-depth: Un-bypassable catastrophic fallback regex MUST pass before prompt
553
- verify_command_fallback_regex!(cmd_str)
554
-
555
- theme = (effective_shell.respond_to?(:ui_theme) && effective_shell.ui_theme) ||
556
- (defined?(Rubik::UI::Theme) ? Rubik::UI::Theme.new : nil)
557
-
558
- question = "Allow unclassified command execution: '#{cmd_str}'?"
559
- answer = if defined?(Rubik::UI::Approvals)
560
- Rubik::UI::Approvals.keypress_yes_no(effective_shell, question, theme: theme, default: "n")
561
- else
562
- "n"
563
- end
564
-
565
- if ["y", "yes"].include?(answer.to_s.downcase)
566
- log_audit("allowed_command", command: cmd_str, reason: "operator_interactive_approval")
567
- return true
568
- end
569
- end
570
-
571
- log_audit("blocked_command", command: cmd_str, reason: "unknown_command")
572
- raise BlockedWriteError.new(
573
- "Unknown command execution blocked (fail-closed): #{cmd_str}. The binary is not in the " \
574
- "command database, so its effects cannot be classified. If it is genuinely safe, the " \
575
- "operator can allowlist the exact prefix: !allow-cmd add \"<binary> [args]\"",
576
- kind: :unknown_command,
577
- blocked_command: cmd_str,
578
- rule_name: "unknown_command",
579
- probe_like: probe_shape?(cmd_str),
580
- segment_report: nil
581
- )
582
- end
583
-
584
- # Ambiguous parse (tree-sitter syntax errors) is a classification
585
- # failure, not a pass: the walk cannot vouch for the whole
586
- # expression, so a safe-looking partial verdict must not fall
587
- # through to the catastrophic-only regex gate. The allowlist stays
588
- # the valve because a real AST exists — every segment is checked
589
- # against the operator entries.
590
- if !allow_unknown && ast.parse_warnings.to_a.any?
591
- allowlisted = begin
592
- command_allowlisted?(ast, cmd_str: cmd_str)
593
- rescue StandardError => e
594
- warn "[Guard] allowlist evaluation failed, failing closed: #{e.class}: #{e.message}"
595
- false
596
- end
597
- if allowlisted
598
- log_audit("allowed_command", command: cmd_str, reason: "operator_allowlist")
599
- verify_command_fallback_regex!(cmd_str)
600
- return true
601
- end
602
- log_audit("blocked_command", command: cmd_str, reason: "parse_ambiguous",
603
- parse_warnings: ast.parse_warnings.to_a.size)
604
- raise BlockedWriteError.new(
605
- "Command AST could not be fully parsed (tree-sitter syntax error); execution blocked (fail-closed): #{cmd_str}",
606
- kind: :parse_ambiguous,
607
- blocked_command: cmd_str,
608
- rule_name: "parse_ambiguous",
609
- probe_like: probe_shape?(cmd_str),
610
- segment_report: nil
611
- )
612
- end
613
-
614
- return true if [:readonly, :local_effects, :external_effects].include?(ast.classification) && ast.parse_warnings.empty?
615
- rescue BlockedWriteError
616
- raise
617
- rescue StandardError => e
618
- # Unconditional warn + audit trail: a classifier crash is a
619
- # security-observable downgrade nobody should need RUBIK_DEBUG to
620
- # notice. The shell gate fails closed — an exception must never
621
- # mint execution permission; the operator allowlist is the one
622
- # sanctioned valve. The allow_unknown seam (no production caller
623
- # today) keeps flowing into its own deny layers
624
- # (DANGEROUS_SYNTHESIS_PATTERNS + RubyVM walk) after this gate.
625
- if allow_unknown
626
- warn "[WARN] AST classification error on non-shell input, continuing to synthesis deny layers: #{e.message}"
627
- log_audit("classifier_error", command: cmd_str, reason: "#{e.class}: #{e.message}",
628
- decision: "synthesis_layers")
629
- else
630
- warn "[WARN] AST classification error, failing closed: #{e.class}: #{e.message}"
631
- block_on_classifier_failure!(cmd_str, e)
632
- end
633
- end
634
-
635
- verify_command_fallback_regex!(cmd_str)
145
+ @path_policy.verify_root_safety!(path)
636
146
  end
637
147
 
638
- def dangerous_reason(commands)
639
- commands.each do |c|
640
- next unless c.classification == :dangerous
641
-
642
- # Dangerous INNERS only: recursing into safe inners would shadow
643
- # the command's own reason with the "dangerous_ast" sentinel —
644
- # which must stay exclusive to expression-level elevations (the
645
- # raise site uses it as the expression-case signal).
646
- inner = nil
647
- inner = dangerous_reason(c.inner_commands) if c.respond_to?(:inner_commands) && c.inner_commands&.any? { |i| i.classification == :dangerous }
648
- return inner || (c.respond_to?(:classification_reason) && c.classification_reason) || "dangerous_command"
649
- end
650
- "dangerous_ast"
148
+ # ── CommandGate (owns probe/root/shell state) ───────────────────────
149
+ def shell
150
+ @command_gate.shell
651
151
  end
652
152
 
653
- # Innermost dangerous segment's rule name — surfaced in blocked-command
654
- # guidance so the operator knows exactly which rule matched and what
655
- # prefix to allowlist (e.g. rule: bash, rule: rm).
656
- def dangerous_rule_name(commands)
657
- commands.each do |c|
658
- next unless c.classification == :dangerous
659
-
660
- inner = dangerous_rule_name(c.inner_commands) if c.respond_to?(:inner_commands) && c.inner_commands&.any?
661
- return inner || (c.respond_to?(:matched_rule) && c.matched_rule)
662
- end
663
- nil
153
+ def shell=(val)
154
+ @command_gate.shell = val
664
155
  end
665
156
 
666
- # Expression-level elevations (Engine#build_expression_result) are
667
- # dangerous with no dangerous command to name — the composed evidence
668
- # rides on the ExpressionResult itself. Presence (non-nil) is the
669
- # expression-case signal.
670
- def expression_level_reason(ast)
671
- return nil unless ast.respond_to?(:classification_reason)
672
-
673
- reason = ast.classification_reason.to_s.strip
674
- reason.empty? ? nil : reason
157
+ def root_dir
158
+ @command_gate.root_dir
675
159
  end
676
160
 
677
- # Structured report for wrapper/multi-segment blocked-command guidance:
678
- # every innermost dangerous segment with its trigger, the sibling
679
- # commands that passed, a one-line wrapper preview, and the allowlist
680
- # entries that would actually open the gate. Plain data only —
681
- # BlockedWriteError must stay loadable without the classifier stack.
682
- # nil when no single command is dangerous (expression-level elevations
683
- # keep the scalar rule_name guidance path).
684
- def dangerous_segment_report(commands)
685
- segments = []
686
- safe = []
687
- safe_top_argv = []
688
- wrappers = []
689
- collect_dangerous_units(commands, 0, segments, safe, safe_top_argv, wrappers)
690
- return nil if segments.empty?
691
-
692
- # The gate (command_allowlisted?) matches EVERY top-level command,
693
- # safe ones included — the entry set must cover them all to be
694
- # honest: wrapper prefix + top-level dangerous segments + top-level
695
- # safe units.
696
- entries = wrappers.map { |w| wrapper_allowlist_entry(w) }
697
- entries += segments.select { |s| s[:depth].zero? }.map { |s| allowlist_entry_for_argv(s[:argv]) }
698
- entries += safe_top_argv.map { |argv| allowlist_entry_for_argv(argv) }
699
-
700
- {
701
- segments: segments,
702
- safe: safe.uniq,
703
- wrapper_preview: wrappers.empty? ? nil : wrapper_preview(wrappers.first),
704
- allowlist_entries: entries.uniq
705
- }.freeze
706
- end
707
-
708
- # Depth-first walk over the classified command tree. A dangerous
709
- # command whose danger comes from dangerous inners contributes those
710
- # inner leaves instead of itself (bash -c "rm -rf /" reports the inner
711
- # rm, not the wrapper); a dangerous leaf is a segment; non-dangerous
712
- # leaves join the passed roll call. Top-level wrappers (dangerous only
713
- # through their inners) are tracked separately for preview + hint;
714
- # top-level safe units keep their argv for the gate-honest entry set.
715
- def collect_dangerous_units(commands, depth, segments, safe, safe_top_argv, wrappers)
716
- Array(commands).each do |c|
717
- inners = Array(c.inner_commands)
718
- before = segments.size
719
- collect_dangerous_units(inners, depth + 1, segments, safe, safe_top_argv, wrappers)
720
- added = segments.size - before
721
-
722
- if c.classification == :dangerous
723
- if added.positive?
724
- wrappers << c if depth.zero?
725
- else
726
- segments << dangerous_segment_data(c, depth)
727
- end
728
- elsif inners.empty?
729
- safe << safe_segment_name(c)
730
- safe_top_argv << c.argv.dup if depth.zero?
731
- end
732
- end
161
+ def root_dir=(val)
162
+ @command_gate.root_dir = val
733
163
  end
734
164
 
735
- def dangerous_segment_data(result, depth)
736
- argv = Array(result.argv)
737
- {
738
- display: segment_display(display_tokens(argv, result)),
739
- argv: argv.dup.freeze,
740
- rule: result.matched_rule,
741
- option: result.overriding_option,
742
- reason: result.classification_reason,
743
- depth: depth
744
- }
745
- end
746
-
747
- # Redirect-bearing segments (delegated inners) render their effects,
748
- # not just their argv: `echo pwned > /etc/shadow`, not `echo pwned`.
749
- # Flat operator/target tokens keep segment_display's quoting correct;
750
- # argv itself stays pure — allowlist entries derive from it.
751
- def display_tokens(argv, result)
752
- reds = result.respond_to?(:redirects) ? Array(result.redirects) : []
753
- reds.empty? ? argv : argv + reds.flat_map { |r| [r.operator, r.target] }
754
- end
755
-
756
- # Subcommand-aware roll call of the units that passed ("git checkout",
757
- # not just "git") — matches the operator's mental model of the script.
758
- def safe_segment_name(result)
759
- result.command.join(" ")
760
- end
761
-
762
- # One-line wrapper preview for the guidance first line. The delegated
763
- # payload (the whole -c script) is the argv token that contains
764
- # whitespace — elide it so the full script is never re-embedded in the
765
- # message (the defect this report exists to fix).
766
- def wrapper_preview(result)
767
- argv = Array(result.argv)
768
- tokens = argv.dup
769
- tokens[-1] = "'...'" if tokens.size > 1 && tokens[-1].to_s.match?(/\s/)
770
- preview = segment_display(tokens)
771
- preview.length > WRAPPER_PREVIEW_CAP ? "#{preview[0, WRAPPER_PREVIEW_CAP - 1]}..." : preview
772
- end
773
-
774
- # Shortest top-level argv prefix that actually satisfies the gate's
775
- # token-prefix match (command_allowlisted?): the wrapper binary up to
776
- # and including its delegation flag for flag-value payloads
777
- # ("bash -c", "bash -e -c"), the bare binary for rest-argv wrappers
778
- # ("sudo", "xargs"). Deriving it from delegation_source keeps the hint
779
- # gate-honest for flag permutations a naive first-two-tokens guess
780
- # would miss.
781
- def wrapper_allowlist_entry(wrapper)
782
- argv = Array(wrapper.argv)
783
- return argv.first.to_s if argv.size <= 1
784
-
785
- first_inner = Array(wrapper.inner_commands).first
786
- if first_inner&.delegation_mode.to_s == "flag_value_is_expression"
787
- idx = argv.index(first_inner.delegation_source)
788
- return argv[0..idx].join(" ") if idx&.positive?
789
- end
790
- argv.first.to_s
791
- end
792
-
793
- # An allowlist entry can only carry whitespace-free tokens:
794
- # normalize_allowlist splits entries on whitespace, so an argv token
795
- # containing spaces ("feature x") can never be matched by an entry.
796
- # Prefix up to (excluding) the first such token.
797
- def allowlist_entry_for_argv(argv)
798
- prefix = []
799
- Array(argv).each do |token|
800
- break if token.to_s.match?(/\s/)
801
-
802
- prefix << token
803
- end
804
- prefix.empty? ? Array(argv).first.to_s : prefix.join(" ")
805
- end
806
-
807
- # Display-only rendering: collapse newlines, single-quote tokens that
808
- # contain whitespace, hard-cap length. Shellwords.escape would
809
- # backslash-quote every token (noise on Windows paths) — quote
810
- # conditionally instead.
811
- def segment_display(argv)
812
- text = argv.map { |t| t.to_s.tr("\r\n", " ") }
813
- .map { |t| t.match?(/\s/) ? "'#{t}'" : t }
814
- .join(" ")
815
- text.length > SEGMENT_DISPLAY_CAP ? "#{text[0, SEGMENT_DISPLAY_CAP - 1]}..." : text
816
- end
817
-
818
- def segment_count(report)
819
- report ? report[:segments].size : 0
165
+ def allow_safe_probes?
166
+ @command_gate.allow_safe_probes?
820
167
  end
821
168
 
822
- # Classifier-crash gate for the shell path: structured block by
823
- # default, one sanctioned rescue — an operator allowlist entry
824
- # covering the exact single-command prefix (the same explicit
825
- # authorization contract as the unknown-command gate). The
826
- # catastrophic fallback regex still runs afterwards on the rescue
827
- # path; on the block path it gets first refusal so a catastrophic
828
- # command keeps its precise :dangerous_pattern reason.
829
- def block_on_classifier_failure!(cmd_str, error)
830
- allowlisted = begin
831
- command_allowlisted_raw?(cmd_str)
832
- rescue StandardError => e
833
- warn "[Guard] raw allowlist evaluation failed, failing closed: #{e.class}: #{e.message}"
834
- false
835
- end
836
- log_audit("classifier_error", command: cmd_str, reason: "#{error.class}: #{error.message}",
837
- decision: allowlisted ? "operator_allowlist" : "blocked")
838
-
839
- if allowlisted
840
- log_audit("allowed_command", command: cmd_str, reason: "operator_allowlist_classifier_error")
841
- return
842
- end
843
-
844
- verify_command_fallback_regex!(cmd_str)
845
- log_audit("blocked_command", command: cmd_str, reason: "classifier_error")
846
- raise BlockedWriteError.new(
847
- "AST evaluation failed, so the command could not be classified; execution blocked (fail-closed): #{cmd_str}",
848
- kind: :classifier_error,
849
- blocked_command: cmd_str,
850
- rule_name: "classifier_error",
851
- probe_like: probe_shape?(cmd_str),
852
- segment_report: nil
853
- )
169
+ def allow_safe_probes=(val)
170
+ @command_gate.allow_safe_probes = val
854
171
  end
855
172
 
856
- # Token-prefix allowlist check for an input whose AST does not exist
857
- # (classifier crashed). Only a single simple command qualifies: with
858
- # shell metacharacters present the string may hold several segments
859
- # and the gate's "every segment must match" contract cannot be
860
- # honored — fail closed instead of over-promising the prefix match.
861
- # Quoting is handled by Shellwords; an unparseable string (unbalanced
862
- # quote) fails closed.
863
- def command_allowlisted_raw?(cmd_str)
864
- return false if @command_allowlist.empty?
865
- return false if cmd_str.match?(RAW_ALLOWLIST_UNSAFE_PATTERN)
866
-
867
- tokens = nil
868
- begin
869
- tokens = Shellwords.split(cmd_str)
870
- rescue ArgumentError
871
- return false
872
- end
873
- return false if tokens.empty?
874
- return false if Rubik::Security::Classifier::Matcher::BUILTIN_DANGEROUS_CMDS.include?(tokens[0].to_s)
875
-
876
- @command_allowlist.any? do |entry|
877
- next false if entry.length > tokens.length
878
-
879
- entry.each_with_index.all? do |token, i|
880
- i.zero? ? binary_allowlist_match?(tokens[i], token) : tokens[i] == token
881
- end
882
- end
173
+ def verify_command_safety!(cmd, shell: nil, allow_unknown: false)
174
+ @command_gate.verify_command_safety!(cmd, shell: shell, allow_unknown: allow_unknown)
883
175
  end
884
176
 
885
177
  def verify_command_fallback_regex!(cmd_str)
886
- return true unless DANGEROUS_COMMAND_PATTERNS.any? { |p| cmd_str.match?(p) }
887
-
888
- log_audit("blocked_command", command: cmd_str, reason: "dangerous_pattern")
889
- raise BlockedWriteError.new(
890
- "Dangerous command execution blocked: #{cmd_str}",
891
- kind: :dangerous_pattern,
892
- blocked_command: cmd_str,
893
- rule_name: "dangerous_pattern"
894
- )
178
+ @command_gate.verify_command_fallback_regex!(cmd_str)
895
179
  end
896
180
 
897
- # ── Synthesis capability table (Candidate 07) ───────────────────────
898
- # The ONE declaration point for everything the synthesis AST walk
899
- # denies (docs/explanation/architecture.md §2 "single declaration point" doctrine; §8.3
900
- # "the seam is enforced where it is declared"). Each row is a capability
901
- # a synthesized tool must never exercise; layer fields say WHERE the
902
- # denial bites:
903
- # nodes — RubyVM node types refused on sight
904
- # calls — call names refused on ANY call shape (:fcall/:vcall
905
- # AND :call/:qcall/:attrasgn)
906
- # bare_calls — names refused on :fcall/:vcall only; receiver forms
907
- # stay legal (ctx.require is the coeffect accessor)
908
- # consts — constants refused as call RECEIVERS only
909
- # any_const — constants refused on ANY :const/:colon3 reference,
910
- # anti `X = TCPSocket; X.new` aliasing
911
- # The FORBIDDEN_SYNTHESIS_* constants below are derived projections of
912
- # this table, kept under their historical names for the walk's call
913
- # sites; test_synthesis_capability_coverage.rb locks table <-> constant
914
- # <-> behavior equivalence so the derivation cannot drift. Note: the
915
- # :block node (grouped expressions) intentionally has NO row —
916
- # `(a || b).to_i`-style expressions must stay allowed.
917
- SynthesisCapability = Struct.new(:name, :reason, :nodes, :calls,
918
- :bare_calls, :consts, :any_const,
919
- keyword_init: true)
920
-
921
- SYNTHESIS_CAPABILITIES = [
922
- SynthesisCapability.new(
923
- name: :shell_execution,
924
- reason: "backtick/%x shell escapes execute outside every Ruby-level guard",
925
- nodes: [:xstr, :dxstr]
926
- ),
927
- SynthesisCapability.new(
928
- name: :code_definition,
929
- reason: "method/class definitions mutate the eval target; synthesized payloads are single lambdas",
930
- nodes: [:defn, :defs, :class, :sclass]
931
- ),
932
- SynthesisCapability.new(
933
- name: :method_table_mutation,
934
- reason: "alias/undef rewrite the method table behind the guard",
935
- nodes: [:alias, :undef]
936
- ),
937
- SynthesisCapability.new(
938
- name: :global_state,
939
- reason: "global variables are process-wide ambient state the host context cannot revert",
940
- nodes: [:gvar, :gasgn]
941
- ),
942
- SynthesisCapability.new(
943
- name: :dynamic_execution,
944
- reason: "string eval and Binding turn data into code outside the AST walk",
945
- calls: [:eval, :instance_eval, :class_eval, :module_eval, :binding,
946
- :instance_exec, :class_exec, :module_exec, :define_method, :define_singleton_method]
947
- ),
948
- SynthesisCapability.new(
949
- name: :process_control,
950
- reason: "subprocess spawn and process lifecycle control escape the sandbox and audit trail; " \
951
- "trap/at_exit install process-wide hooks the host cannot revert — Signal.trap can " \
952
- "swallow the host REPL's Interrupt/exit handling; exit/exit! can kill the host " \
953
- "when preflight runs in-process",
954
- calls: [:system, :exec, :spawn, :fork, :syscall, :exit, :exit!, :trap, :at_exit,
955
- :popen, :capture2, :capture2e, :capture3, :popen2, :popen2e,
956
- :popen3, :pipeline, :kill, :daemon],
957
- consts: [:Process, :Thread, :Signal, :Open3]
958
- ),
959
- SynthesisCapability.new(
960
- name: :reflection,
961
- reason: "send/method-object families bypass static call-name checks (the method(:x).call escape)",
962
- calls: [:send, :public_send, :__send__,
963
- :method, :public_method, :singleton_method,
964
- :instance_method, :public_instance_method, :bind, :bind_call]
965
- ),
966
- SynthesisCapability.new(
967
- name: :state_introspection,
968
- reason: "object internals and object-graph walks fish for live objects and sidestep the AST deny surface (the method(:x).call family at runtime)",
969
- calls: [:instance_variable_get, :instance_variable_set],
970
- consts: [:ObjectSpace]
971
- ),
972
- SynthesisCapability.new(
973
- name: :namespace_mutation,
974
- reason: "const_get/const_set/remove_const read and rewrite constant namespaces at runtime",
975
- calls: [:const_get, :const_set, :remove_const]
976
- ),
977
- SynthesisCapability.new(
978
- name: :filesystem,
979
- reason: "raw file/IO handles bypass the OutputView and every guard write check",
980
- calls: [:open, :read, :write, :binread, :binwrite, :unlink, :rm_rf, :rmtree,
981
- :sysopen, :syswrite, :sysread, :readlines, :foreach, :Pathname],
982
- consts: [:IO, :File, :Dir, :FileUtils, :STDIN, :STDOUT, :STDERR, :ARGF, :Pathname]
983
- ),
984
- SynthesisCapability.new(
985
- name: :code_loading,
986
- reason: "require/load execute files outside every guard. :require/:require_relative must NOT live in calls: " \
987
- "ctx.require('database') is the canonical coeffect accessor (receiver call) and every synthesized " \
988
- "tool depends on it — the bare forms are the escape. Kernel.require/Kernel.load are already caught " \
989
- "via :Kernel in runtime_root; obj.load would load arbitrary code or deserialize untrusted state",
990
- calls: [:load, :autoload],
991
- bare_calls: [:require, :require_relative, :load, :autoload]
992
- ),
993
- SynthesisCapability.new(
994
- name: :runtime_root,
995
- reason: "core runtime singletons (Kernel/RubyVM/Class/Module/...) re-open every denied capability",
996
- consts: [:Kernel, :RubyVM, :Object, :Class, :Module, :BasicObject, :Rubik, :Fiber, :TracePoint, :GC]
997
- ),
998
- SynthesisCapability.new(
999
- name: :ambient_state,
1000
- reason: "ENV reads expose provider keys / ambient config and mutate process-wide state the host cannot revert",
1001
- consts: [:ENV]
1002
- ),
1003
- SynthesisCapability.new(
1004
- name: :network_serialization,
1005
- reason: "sockets and Marshal have no legitimate synthesized-tool use; receiver-only checks leave " \
1006
- "`X = TCPSocket; X.new` (:casgn aliasing) wide open, so their mere appearance is a refusal",
1007
- any_const: [:Socket, :IPSocket, :TCPSocket, :TCPServer, :UDPSocket,
1008
- :UNIXSocket, :UNIXServer, :Net, :Marshal]
1009
- )
1010
- ].map do |cap|
1011
- # Deep-freeze: the ONE declaration point for a security gate must be
1012
- # immutable by construction, not by convention — Struct#freeze alone
1013
- # leaves the member arrays mutable.
1014
- cap.members.each { |member| cap[member].freeze if cap[member].is_a?(Array) }
1015
- cap.freeze
1016
- end.freeze
1017
-
1018
- # Fold one capability layer into its denial list. Load-time, pure;
1019
- # test_synthesis_capability_coverage.rb pins this helper as the ONLY
1020
- # fold from table to denial constants.
1021
- def self.synthesis_capability_layer(field)
1022
- SYNTHESIS_CAPABILITIES.flat_map { |cap| cap[field].to_a }.freeze
1023
- end
1024
-
1025
- FORBIDDEN_SYNTHESIS_NODES = synthesis_capability_layer(:nodes)
1026
- FORBIDDEN_SYNTHESIS_CALLS = synthesis_capability_layer(:calls)
1027
- FORBIDDEN_SYNTHESIS_BARE_CALLS = synthesis_capability_layer(:bare_calls)
1028
- FORBIDDEN_SYNTHESIS_CONSTS = synthesis_capability_layer(:consts)
1029
- FORBIDDEN_SYNTHESIS_NETWORK_CONSTS = synthesis_capability_layer(:any_const)
1030
-
1031
- # The ONE synthesis gate: every site about to eval synthesized code
1032
- # comes through here (synthesis builtins AND PreflightRunner's
1033
- # spawn-boundary re-check). A guard lacking verify_synthesis_safety!
1034
- # is downgraded to the shell-only gate — the duck-typed fallback is a
1035
- # test-double affordance, but skipping the entire AST deny surface is
1036
- # security-observable, so the downgrade is loud. $stderr.puts, not
1037
- # Kernel#warn: warn is silenced when $VERBOSE is nil (bundler/rake
1038
- # -W0) — same ruling as Log.emit. A failing emit is fail-closed AND
1039
- # honest: refusal with the real cause, never a misattributed
1040
- # "dangerous operations".
1041
- def self.run_synthesis_gate(guard, code)
1042
- if guard.respond_to?(:verify_synthesis_safety!)
1043
- guard.verify_synthesis_safety!(code)
1044
- else
1045
- begin
1046
- $stderr.puts "[Synthesize] guard lacks verify_synthesis_safety!; downgraded to shell-only gate" # rubocop:disable Style/StderrPuts
1047
- rescue StandardError => e
1048
- raise BlockedWriteError,
1049
- "guard downgrade warn could not be written to stderr (#{e.class}: #{e.message}); refusing to eval"
1050
- end
1051
- guard.verify_command_safety!(code)
1052
- end
1053
- end
1054
-
1055
- # Reject synthesized Ruby before it is ever eval'd.
1056
- #
1057
- # Defense-in-depth architecture:
1058
- # 1. Fast regex pattern matching (DANGEROUS_SYNTHESIS_PATTERNS) intercepts known keywords.
1059
- # 2. RubyVM::AbstractSyntaxTree semantic walk checks normalized node types, method calls,
1060
- # and receiver constants against explicit deny rules to block AST-level evasion vectors.
1061
- #
1062
- # Raises Rubik::Security::BlockedWriteError with an actionable message.
181
+ # ── SynthesisGate ────────────────────────────────────────────────────
1063
182
  def verify_synthesis_safety!(code)
1064
- code_str = code.to_s
1065
-
1066
- matched = DANGEROUS_SYNTHESIS_PATTERNS.find { |p| code_str.match?(p) }
1067
- if matched
1068
- log_audit("blocked_synthesis", code: code_str, reason: "dangerous_synthesis_pattern")
1069
- raise BlockedWriteError, "Dangerous synthesis code blocked by security guard: #{matched.inspect}"
1070
- end
1071
-
1072
- synthesize_safety_walk(code_str)
183
+ @synthesis_gate.verify_synthesis_safety!(code)
1073
184
  end
1074
185
 
1075
186
  def synthesize_safety_walk(code_str)
1076
- ast = begin
1077
- RubyVM::AbstractSyntaxTree.parse(code_str)
1078
- rescue ArgumentError, SyntaxError
1079
- # Code with syntax errors cannot execute; let synthesis eval safely report
1080
- # a SyntaxError to the user rather than misclassifying a syntax typo as a security breach.
1081
- nil
1082
- end
1083
-
1084
- return true if ast.nil?
1085
-
1086
- synthesize_safety_check_node(ast)
1087
-
1088
- true
1089
- end
1090
-
1091
- # Recursively walk the AST, refusing if any disallowed construct is encountered.
1092
- def synthesize_safety_check_node(node)
1093
- return true unless node.respond_to?(:type)
1094
-
1095
- type = node.type.to_s.downcase.to_sym
1096
- reject_unsafe(node, "node type :#{type}") if FORBIDDEN_SYNTHESIS_NODES.include?(type)
1097
-
1098
- case type
1099
- when :const, :colon3
1100
- # :const covers Net::HTTP / Marshal.dump receivers, `X = Socket`
1101
- # RHS values, and local aliasing `k = Kernel`; :colon3 covers top-level scoped `::TCPSocket`.
1102
- name = node.children[0]
1103
- forbidden_const = FORBIDDEN_SYNTHESIS_NETWORK_CONSTS.include?(name) || FORBIDDEN_SYNTHESIS_CONSTS.include?(name)
1104
- reject_unsafe(node, "reference to forbidden constant :#{name}") if forbidden_const
1105
- when :colon2
1106
- # Scoped constant reference like Rubik::Security::Guard
1107
- name = node.children[1]
1108
- forbidden_const = FORBIDDEN_SYNTHESIS_NETWORK_CONSTS.include?(name) || FORBIDDEN_SYNTHESIS_CONSTS.include?(name)
1109
- reject_unsafe(node, "reference to forbidden constant :#{name}") if forbidden_const
1110
- when :fcall, :vcall
1111
- name = node.children[0]
1112
- reject_unsafe(node, "call to :#{name}") if FORBIDDEN_SYNTHESIS_CALLS.include?(name)
1113
- reject_unsafe(node, "bare call to :#{name}") if FORBIDDEN_SYNTHESIS_BARE_CALLS.include?(name)
1114
- when :call, :qcall, :attrasgn
1115
- recv = node.children[0]
1116
- name = node.children[1]
1117
-
1118
- reject_unsafe(node, "call to :#{name}") if FORBIDDEN_SYNTHESIS_CALLS.include?(name)
1119
-
1120
- # Receiver const check must accept const node shapes: :const, :colon3, and :colon2
1121
- if recv.respond_to?(:type)
1122
- recv_type = recv.type.to_s.downcase.to_sym
1123
- if [:const, :colon3].include?(recv_type)
1124
- const_name = recv.children[0]
1125
- reject_unsafe(node, "access to #{const_name}.#{name}") if FORBIDDEN_SYNTHESIS_CONSTS.include?(const_name)
1126
- elsif recv_type == :colon2
1127
- const_name = recv.children[1]
1128
- reject_unsafe(node, "access to #{const_name}.#{name}") if FORBIDDEN_SYNTHESIS_CONSTS.include?(const_name)
1129
- end
1130
- end
1131
- end
1132
-
1133
- node.children.compact.each do |c|
1134
- synthesize_safety_check_node(c) if c.respond_to?(:type)
1135
- end
1136
- true
1137
- end
1138
-
1139
- def reject_unsafe(node, detail = nil)
1140
- kind = node.type.inspect
1141
- reason = detail ? "unsafe_#{detail.to_s.gsub(/\s+/, '_')}" : "unsafe_node_#{kind}"
1142
- log_audit("blocked_synthesis", code: node.children[0].to_s, reason: reason)
1143
- raise BlockedWriteError,
1144
- "Synthesized code was refused by the security guard: #{detail || "a #{kind} node"} is not permitted in synthesized tools."
1145
- end
1146
-
1147
- def mask_text(text)
1148
- Rubik::Security::Redactor.redact(text)
1149
- end
1150
-
1151
- def log_audit(action, details = {})
1152
- return if @audit_log_path.nil? || @audit_log_path.to_s.strip.empty?
1153
-
1154
- # Nil-safety: a nil details hash (or nil value) must never crash the
1155
- # command path — audit failure is already swallowed below.
1156
- masked_details = (details || {}).transform_values { |v| v.nil? ? "" : mask_text(v.to_s) }
1157
-
1158
- entry = {
1159
- ts: Time.now.iso8601,
1160
- action: action,
1161
- details: masked_details
1162
- }
1163
-
1164
- dir = File.dirname(@audit_log_path)
1165
- FileUtils.mkdir_p(dir) unless File.directory?(dir)
1166
-
1167
- File.open(@audit_log_path, "a") do |f|
1168
- f.puts(JSON.dump(entry))
1169
- end
1170
- rescue StandardError => e
1171
- # Unconditional: an audit trail failing silently is indistinguishable
1172
- # from an operator's intentional disable — the one warn in the guard
1173
- # that must not hide behind RUBIK_DEBUG.
1174
- warn "[WARN] Failed to write audit log #{@audit_log_path}: #{e.message}"
187
+ @synthesis_gate.synthesize_safety_walk(code_str)
1175
188
  end
1176
189
  end
1177
190
  end