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