rubik 0.12.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 (107) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +71 -1
  4. data/bin/rubik +11 -1
  5. data/lib/rubik/ast/c_extractor.rb +1 -1
  6. data/lib/rubik/ast/graph.rb +38 -57
  7. data/lib/rubik/ast/graph_extensions.rb +57 -15
  8. data/lib/rubik/ast/ruby_extractor.rb +4 -0
  9. data/lib/rubik/ast/treesitter/c_walker.rb +11 -3
  10. data/lib/rubik/buffer/manager.rb +33 -11
  11. data/lib/rubik/buffer/snapshot.rb +23 -3
  12. data/lib/rubik/cli/connect.rb +49 -0
  13. data/lib/rubik/config/defaults.rb +4 -7
  14. data/lib/rubik/config/env_guard.rb +43 -0
  15. data/lib/rubik/config/schema.rb +8 -1
  16. data/lib/rubik/config/secret_policy.rb +6 -5
  17. data/lib/rubik/config.rb +1 -1
  18. data/lib/rubik/connect/http.rb +85 -0
  19. data/lib/rubik/connect/models_dev.rb +173 -0
  20. data/lib/rubik/connect/probes.rb +103 -0
  21. data/lib/rubik/connect/prompt_ui.rb +139 -0
  22. data/lib/rubik/connect/wizard.rb +540 -0
  23. data/lib/rubik/connect.rb +7 -0
  24. data/lib/rubik/context/repo_context_reader.rb +8 -4
  25. data/lib/rubik/llm/chunk_assembler.rb +12 -1
  26. data/lib/rubik/llm/formatter.rb +14 -0
  27. data/lib/rubik/llm/openai_compatible.rb +4 -1
  28. data/lib/rubik/llm/provider_key.rb +32 -0
  29. data/lib/rubik/llm/registry.rb +18 -2
  30. data/lib/rubik/llm/router.rb +19 -1
  31. data/lib/rubik/llm/session_header.rb +128 -0
  32. data/lib/rubik/llm/sse_parser.rb +57 -10
  33. data/lib/rubik/lsp/client.rb +11 -5
  34. data/lib/rubik/lsp/transport.rb +17 -7
  35. data/lib/rubik/mcp/transport/stdio.rb +42 -4
  36. data/lib/rubik/orchestrator/continuation_manager.rb +14 -5
  37. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +18 -2
  38. data/lib/rubik/orchestrator/goal_ledger/observation_projection.rb +13 -4
  39. data/lib/rubik/orchestrator/goal_ledger/validator.rb +46 -7
  40. data/lib/rubik/orchestrator/goal_ledger/verifier.rb +8 -1
  41. data/lib/rubik/orchestrator/goal_session.rb +4 -4
  42. data/lib/rubik/orchestrator/loop.rb +8 -11
  43. data/lib/rubik/orchestrator/provider_resolver.rb +29 -6
  44. data/lib/rubik/orchestrator/step_executor.rb +17 -2
  45. data/lib/rubik/orchestrator/subagent/instance.rb +24 -1
  46. data/lib/rubik/orchestrator/subagent/notices.rb +1 -1
  47. data/lib/rubik/orchestrator/subagent/reaper.rb +21 -2
  48. data/lib/rubik/orchestrator/subagent/start_gate.rb +1 -1
  49. data/lib/rubik/orchestrator/subagent/step_runner.rb +7 -7
  50. data/lib/rubik/orchestrator/subagent/supervisor.rb +10 -3
  51. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +27 -5
  52. data/lib/rubik/orchestrator/turn_executor.rb +24 -8
  53. data/lib/rubik/platform/filesystem.rb +52 -24
  54. data/lib/rubik/plugin/storage.rb +20 -0
  55. data/lib/rubik/prompt/context_builder.rb +2 -1
  56. data/lib/rubik/repair/loop.rb +22 -2
  57. data/lib/rubik/repl/commands/agent_context.rb +1 -1
  58. data/lib/rubik/repl/commands/agent_execution.rb +20 -15
  59. data/lib/rubik/repl/commands/buffer.rb +15 -0
  60. data/lib/rubik/repl/commands/connect.rb +51 -0
  61. data/lib/rubik/repl/commands/lsp.rb +1 -1
  62. data/lib/rubik/repl/commands/plugins.rb +31 -31
  63. data/lib/rubik/repl/commands/session.rb +5 -5
  64. data/lib/rubik/repl/commands/workspace.rb +4 -4
  65. data/lib/rubik/repl/commands.rb +2 -0
  66. data/lib/rubik/repl/input_execution.rb +30 -29
  67. data/lib/rubik/repl/input_loop.rb +10 -4
  68. data/lib/rubik/repl/lifecycle.rb +38 -0
  69. data/lib/rubik/repl/notice_router.rb +11 -5
  70. data/lib/rubik/repl/paste_support.rb +1 -1
  71. data/lib/rubik/repl/prompt_grace.rb +3 -3
  72. data/lib/rubik/repl/shell.rb +10 -2
  73. data/lib/rubik/repl/turn_recorder.rb +14 -3
  74. data/lib/rubik/runtime/context.rb +33 -27
  75. data/lib/rubik/runtime/manager.rb +23 -15
  76. data/lib/rubik/sandbox/driver/bubblewrap.rb +58 -8
  77. data/lib/rubik/sandbox/driver/process.rb +32 -1
  78. data/lib/rubik/sandbox/runner.rb +9 -1
  79. data/lib/rubik/security/classifier/classifier.rb +147 -13
  80. data/lib/rubik/security/classifier/commands/docker.yaml +1 -1
  81. data/lib/rubik/security/classifier/commands/git.yaml +27 -1
  82. data/lib/rubik/security/classifier/commands/sed.yaml +3 -3
  83. data/lib/rubik/security/classifier/database.rb +2 -2
  84. data/lib/rubik/security/command_gate.rb +8 -1
  85. data/lib/rubik/security/redactor.rb +62 -19
  86. data/lib/rubik/session/recorder.rb +13 -18
  87. data/lib/rubik/session/replayer.rb +29 -7
  88. data/lib/rubik/storage/store.rb +19 -5
  89. data/lib/rubik/tools/builtins/exec.rb +1 -1
  90. data/lib/rubik/tools/builtins/files.rb +8 -12
  91. data/lib/rubik/tools/builtins/grep.rb +3 -2
  92. data/lib/rubik/tools/builtins/lsp.rb +31 -7
  93. data/lib/rubik/tools/builtins/show_file.rb +1 -1
  94. data/lib/rubik/tools/builtins/synthesis.rb +4 -4
  95. data/lib/rubik/tools/result_normalizer.rb +1 -1
  96. data/lib/rubik/ui/banner.rb +3 -3
  97. data/lib/rubik/ui/dialog.rb +10 -7
  98. data/lib/rubik/ui/diff_viewer.rb +4 -4
  99. data/lib/rubik/ui/frame.rb +13 -3
  100. data/lib/rubik/ui/markdown_stream.rb +8 -2
  101. data/lib/rubik/ui/panel.rb +11 -11
  102. data/lib/rubik/ui/renderer.rb +6 -6
  103. data/lib/rubik/ui/spinner.rb +1 -1
  104. data/lib/rubik/ui/statusline.rb +3 -3
  105. data/lib/rubik/ui/theme.rb +1 -1
  106. data/lib/rubik/version.rb +1 -1
  107. metadata +12 -1
@@ -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
@@ -48,6 +48,13 @@ subcommands:
48
48
  ls-remote:
49
49
  classification: READONLY
50
50
  strict: false
51
+ # Transport/config options that spawn a shell or hijack execution (issue #539).
52
+ options:
53
+ --upload-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
54
+ --receive-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
55
+ --exec: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
56
+ -c: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
57
+ --config: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
51
58
  ls-tree:
52
59
  classification: READONLY
53
60
  strict: false
@@ -307,16 +314,33 @@ subcommands:
307
314
  pull:
308
315
  classification: LOCAL_EFFECTS
309
316
  strict: false
317
+ options:
318
+ --upload-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
319
+ --receive-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
320
+ --exec: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
321
+ -c: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
322
+ --config: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
310
323
  fetch:
311
324
  classification: LOCAL_EFFECTS
312
325
  risk: LOW
313
326
  strict: false
314
327
  options:
315
328
  --prune: {overrides: LOCAL_EFFECTS}
329
+ --upload-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
330
+ --receive-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
331
+ --exec: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
332
+ -c: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
333
+ --config: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
316
334
  clone:
317
335
  classification: LOCAL_EFFECTS
318
336
  risk: LOW
319
337
  strict: false
338
+ options:
339
+ --upload-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
340
+ --receive-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
341
+ --exec: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
342
+ -c: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
343
+ --config: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
320
344
  init:
321
345
  classification: LOCAL_EFFECTS
322
346
  risk: LOW
@@ -436,7 +460,9 @@ subcommands:
436
460
  classification: READONLY
437
461
  strict: false
438
462
  foreach:
439
- classification: READONLY
463
+ # git evaluates the argument as a shell command in every submodule;
464
+ # typing the payload directly would be DANGEROUS (issue #539).
465
+ classification: DANGEROUS
440
466
  strict: false
441
467
  init:
442
468
  classification: LOCAL_EFFECTS
@@ -1,7 +1,7 @@
1
1
  # $schema: ../../../schemas/command.schema.json
2
2
  command: sed
3
3
  description: "Stream editor for filtering and transforming text"
4
- classification: READONLY
4
+ classification: LOCAL_EFFECTS
5
5
  strict: false
6
6
  global_options:
7
7
  --help: {overrides: READONLY}
@@ -10,5 +10,5 @@ options:
10
10
  --in-place: {overrides: DANGEROUS, risk: HIGH, aliases: [-i]}
11
11
  -e: {takes_value: true}
12
12
  --expression: {takes_value: true, aliases: [-e]}
13
- -f: {takes_value: true}
14
- --file: {takes_value: true, aliases: [-f]}
13
+ -f: {overrides: DANGEROUS, risk: HIGH, takes_value: true}
14
+ --file: {overrides: DANGEROUS, risk: HIGH, takes_value: true, aliases: [-f]}
@@ -81,7 +81,7 @@ module Rubik
81
81
  key_s = self.class.yaml_str(key)
82
82
  return true if shell == :powershell && PwshRules.key?(key_s)
83
83
 
84
- @cache.key?(key_s) || @files.key?(key_s) || PwshRules.key?(key_s)
84
+ synchronize { @cache.key?(key_s) || @files.key?(key_s) || PwshRules.key?(key_s) }
85
85
  end
86
86
 
87
87
  def resolve_alias(command_def)
@@ -97,7 +97,7 @@ module Rubik
97
97
  end
98
98
 
99
99
  def keys
100
- (@files.keys + PwshRules.definitions.keys).uniq
100
+ synchronize { (@files.keys + PwshRules.definitions.keys).uniq }
101
101
  end
102
102
 
103
103
  def size
@@ -197,7 +197,14 @@ module Rubik
197
197
  block_ambiguous_parse!(ast, cmd_str)
198
198
  end
199
199
 
200
- return true if [:readonly, :local_effects, :external_effects].include?(ast.classification) && ast.parse_warnings.empty?
200
+ # Classification-based allow verdicts must not skip the un-bypassable
201
+ # fallback regex: every other allow path runs it (directly or via
202
+ # operator_allowlist_pass?). An under-rated database entry must not
203
+ # become a silent full bypass of the final safety layer.
204
+ if [:readonly, :local_effects, :external_effects].include?(ast.classification) && ast.parse_warnings.empty?
205
+ verify_command_fallback_regex!(cmd_str)
206
+ return true
207
+ end
201
208
  rescue BlockedWriteError
202
209
  raise
203
210
  rescue StandardError => e
@@ -17,8 +17,15 @@ module Rubik
17
17
  %r{(https?://[^\s/@:]+:)([^\s/@:]+)@}
18
18
  ].freeze
19
19
 
20
- ASSIGNMENT_KEY_REGEX = /\b(password|passwd|api_key|secret)(\s*[:=]\s*)(['"][^'"]*['"]|[^\s,;'"]+)/i
21
- ASSIGNMENT_TOKEN_REGEX = /\b(token)(\s*[:=]\s*)(['"][^'"]*['"]|[^\s,;'"]+)/i
20
+ # Generic NAME <sep> VALUE assignment. The name is normalized (camelCase
21
+ # boundaries -> snake_case, downcase) and classified by #secret_key? at
22
+ # match time, so `password=...`, `OPENAI_API_KEY=...`, `apiKey=...` and the
23
+ # `--key=...` flag form all share ONE rule. The optional `--` prefix is
24
+ # what makes provider CLI flags land here (issue #542).
25
+ ASSIGNMENT_KEY_REGEX = /(--)?\b([A-Za-z][A-Za-z0-9_-]*)(\s*[:=]\s*)(['"][^'"]*['"]|[^\s,;'"]+)/
26
+ # Positional counterpart of `--key=...`: `!provider set <name> key <value>`
27
+ # has no separator, so it needs its own bounded shape (no prose masking).
28
+ CLI_POSITIONAL_KEY_REGEX = /\b(set\s+\S+\s+(?:key|api[_-]?key|secret|token|password|passwd)\s+)(['"][^'"]*['"]|[^\s,;'"]+)/i
22
29
 
23
30
  # PERF: Pre-compiled constants to avoid re-allocation inside hot loops
24
31
  URL_PATTERN = %r{(https?://[^\s/@:]+:)([^\s/@:]+)@}
@@ -26,13 +33,18 @@ module Rubik
26
33
  STATIC_PATTERNS = PATTERNS.reject { |pattern| pattern == URL_PATTERN }.freeze
27
34
  # Skip static replacement passes for assignment-only and URL-only inputs.
28
35
  STATIC_PATTERNS_COMBINED_REGEX = Regexp.union(STATIC_PATTERNS).freeze
29
- QUICK_CHECK_REGEX = %r{sk-|AKIA|ghp_|github_pat_|AIza|bearer|PRIVATE KEY|://[^\s/@:]+:|password|passwd|api_key|secret|token}i
36
+ # `key` is load-bearing: without it `--key=...` and `apiKey` take the
37
+ # fast path and keep the credential verbatim (issue #542).
38
+ QUICK_CHECK_REGEX = %r{sk-|AKIA|ghp_|github_pat_|AIza|bearer|PRIVATE KEY|://[^\s/@:]+:|password|passwd|api_key|secret|token|\bkey\b}i
30
39
 
31
40
  # Anahtar-maskeleme desenleri (Session::Recorder#mask_payload ile aynı
32
41
  # aile): sır görünümlü anahtarların değerleri desen eşleşmese bile
33
- # maskelenir; sayaç anahtarları (tokens, max_tokens) istisnadır.
34
- SECRET_KEY_REGEX = /(api_key|auth|password|secret|_token\b|^token\b)/i
35
- TOKEN_COUNT_REGEX = /(tokens|token_count|max_tokens)/i
42
+ # maskelenir. Her iki desen de NORMALİZE anahtara uygulanır; sayaç
43
+ # istisnası tam adla eşleşir, yoksa `auth_tokens` gibi bir sır anahtarı
44
+ # `tokens` alt dizgisi yüzünden yanlışlıkla istisna sayılırdı (#542).
45
+ SECRET_KEY_REGEX = /(?:api_key|auth|password|passwd|secret|_token\z|\Atoken\b|\bkey\b)/i
46
+ TOKEN_COUNT_REGEX = /\A(?:tokens|token_count|max_tokens)\z/i
47
+ TOKEN_NAME_REGEX = /(?:\Atoken\b|_token\z)/i
36
48
 
37
49
  def self.redact(text)
38
50
  return text unless text.is_a?(String)
@@ -59,23 +71,56 @@ module Rubik
59
71
  result.gsub!(URL_PATTERN, URL_MASK)
60
72
 
61
73
  result.gsub!(ASSIGNMENT_KEY_REGEX) do
62
- "#{Regexp.last_match(1)}#{Regexp.last_match(2)}#{MASK_STRING}"
63
- end
64
-
65
- result.gsub!(ASSIGNMENT_TOKEN_REGEX) do |match|
66
- prefix = Regexp.last_match(1)
67
- sep = Regexp.last_match(2)
68
- val = Regexp.last_match(3)
69
- if val =~ /\A['"]?\d+['"]?\z/
70
- match
74
+ full = Regexp.last_match(0)
75
+ flag = Regexp.last_match(1)
76
+ name = Regexp.last_match(2)
77
+ sep = Regexp.last_match(3)
78
+ value = Regexp.last_match(4)
79
+ if maskable_assignment?(name, value)
80
+ "#{flag}#{name}#{sep}#{MASK_STRING}"
71
81
  else
72
- "#{prefix}#{sep}#{MASK_STRING}"
82
+ full
73
83
  end
74
84
  end
75
85
 
86
+ result.gsub!(CLI_POSITIONAL_KEY_REGEX) do
87
+ "#{Regexp.last_match(1)}#{MASK_STRING}"
88
+ end
89
+
76
90
  result
77
91
  end
78
92
 
93
+ # camelCase / SCREAMING_SNAKE -> lower snake_case, so one vocabulary
94
+ # recognizes `apiKey`, `APIKey`, `OPENAI_API_KEY` and `api_key` alike.
95
+ # Both patterns are FIXED-LENGTH: the old `([A-Z]+)([A-Z][a-z])` had a
96
+ # repeated class immediately followed by an overlapping class, which
97
+ # backtracks polynomially on a long uppercase run (CodeQL rb/polynomial-
98
+ # redos). Matching a single uppercase before the boundary is equivalent
99
+ # — the preceding uppercase chars are simply copied — and linear.
100
+ def self.normalize_key(key)
101
+ key.to_s
102
+ .gsub(/([A-Z])([A-Z][a-z])/, '\1_\2')
103
+ .gsub(/([a-z\d])([A-Z])/, '\1_\2')
104
+ .downcase
105
+ end
106
+
107
+ # True for a secret-looking key, with counter names excluded by EXACT
108
+ # match (so `auth_tokens` stays a secret while `max_tokens` does not).
109
+ def self.secret_key?(key)
110
+ normalized = normalize_key(key)
111
+ normalized.match?(SECRET_KEY_REGEX) && !normalized.match?(TOKEN_COUNT_REGEX)
112
+ end
113
+
114
+ # Token-valued assignments keep a numeric value (the existing contract:
115
+ # `token: 20` / `max_tokens: 100` are counters, not credentials).
116
+ def self.maskable_assignment?(name, value)
117
+ normalized = normalize_key(name)
118
+ return false unless normalized.match?(SECRET_KEY_REGEX) && !normalized.match?(TOKEN_COUNT_REGEX)
119
+ return false if normalized.match?(TOKEN_NAME_REGEX) && value.to_s.match?(/\A['"]?\d+['"]?\z/)
120
+
121
+ true
122
+ end
123
+
79
124
  # Bir payload ağacında (Hash/Array/String) her metne redact uygular ve
80
125
  # sır görünümlü anahtarların değerlerini komple maskeler — kalıcı
81
126
  # serileştirmeden önce satır başına çağrılır (transcript sağlığı
@@ -88,9 +133,7 @@ module Rubik
88
133
  case payload
89
134
  when Hash
90
135
  payload.each_with_object({}) do |(k, v), h|
91
- key_str = k.to_s
92
- is_secret_key = key_str.match?(SECRET_KEY_REGEX) && !key_str.match?(TOKEN_COUNT_REGEX)
93
- h[k] = is_secret_key ? MASK_STRING : mask_value(v)
136
+ h[k] = secret_key?(k) ? MASK_STRING : mask_value(v)
94
137
  end
95
138
  when Array
96
139
  payload.map { |v| mask_value(v) }