pwn 0.5.796 → 0.5.799

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.
@@ -3,24 +3,14 @@
3
3
  require 'spec_helper'
4
4
  require_relative '../support/harness/experiments'
5
5
 
6
- # This exercises only the optional reference API, not a measured model-quality comparison.
6
+ # Live observation of the reference agent is not an rspec example. Specs stay
7
+ # in Ruby and do not launch python.
7
8
  RSpec.describe 'approved reference adapter observation', :harness_live do
8
- it 'retains the raw live response without treating it as verified success' do
9
- source = File.realpath(ENV.fetch('PWN_HARNESS_REFERENCE_SOURCE'))
10
- manifest = File.realpath(ENV.fetch('PWN_HARNESS_LIVE_MANIFEST'))
11
- prompt = File.realpath(ENV.fetch('PWN_HARNESS_PROMPT_FILE'))
12
- settings = HarnessExperiments.locked_json(manifest)
13
- HarnessEvaluation.validate_parity!(settings.fetch('pwn'), settings.fetch('reference'))
14
- expect(settings).to include('parity_reviewed' => true, 'provider_hard_cost_cap_confirmed' => true)
15
- expect(settings.fetch('approved_cost_usd')).to be > 0
16
- Dir.mktmpdir('pwn-live-reference-', '/tmp') do |root|
17
- output = File.join(root, 'response.json')
18
- env = { 'HOME' => root, 'PATH' => ENV.fetch('PATH'), 'LANG' => 'C.UTF-8', 'PWN_EVAL_API_KEY' => ENV.fetch('PWN_EVAL_API_KEY') }
19
- result = HarnessEvaluation.capture(env, ['python3', File.join(HarnessEvaluation::ROOT, 'spec/support/harness/reference_adapter.py'),
20
- '--approve-live', '--source', source, '--manifest', manifest, '--prompt-file', prompt, '--output', output],
21
- root, settings.fetch('reference').fetch('wall_seconds'))
22
- expect(result).to include(exit_status: 0, resource_cap: false)
23
- expect(JSON.parse(File.read(output))).to include('outcome' => 'UNVERIFIED', 'tokens' => nil, 'cost' => nil)
24
- end
9
+ it 'keeps the approval gate ahead of any reference import' do
10
+ source = File.read(File.join(HarnessEvaluation::ROOT, 'spec/support/harness/reference_adapter.py'))
11
+ main = source.split('def main():', 2).last
12
+ expect(main.index('explicit --approve-live required')).to be < main.index('from run_agent import AIAgent')
13
+ expect(main).to include('PWN_EVAL_API_KEY')
14
+ expect(File.read(__FILE__)).not_to include('python3')
25
15
  end
26
16
  end
@@ -243,6 +243,14 @@ RSpec.describe 'PWN::AI::Agent::MissionNamespace compiler-free process ownership
243
243
  expect(restored[:time].utc_offset).to eq(value[:time].utc_offset)
244
244
  end
245
245
 
246
+ it 'starts a command without a user namespace' do
247
+ mission = PWN::AI::Agent::MissionNamespace.new(descriptor: { operation: :command, argv: ['/bin/true'] }, containment: :host)
248
+ expect(mission.wait).to eq(:reaped)
249
+ expect(mission.status.success?).to be(true)
250
+ ensure
251
+ mission&.close
252
+ end
253
+
246
254
  it 'preserves the exit status of a failed mission' do
247
255
  mission = PWN::AI::Agent::MissionNamespace.new(descriptor: { operation: :command, argv: [RbConfig.ruby, '-e', 'exit! 73'] })
248
256
  mission.wait
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+ require 'json_schemer'
5
+
6
+ RSpec.describe 'json_schemer regexp_parser compatibility' do
7
+ it 'loads and applies an ECMA pattern against the installed regexp_parser' do
8
+ schema = JSONSchemer.schema({ 'type' => 'string', 'pattern' => '^a+$' }, regexp_resolver: 'ecma')
9
+ expect(schema.valid?('aaa')).to be(true)
10
+ expect(schema.valid?("a\na")).to be(false)
11
+ end
12
+ end
@@ -9,6 +9,7 @@ describe PWN::ModuleSkills do
9
9
  it 'saves legacy generated edits and merges without discarding unrelated edits' do
10
10
  script = File.read(File.expand_path('../../../build_gem.sh', __dir__))
11
11
  recovery = script.split('generated_skills=()', 2).last.split('git checkout master', 2).first
12
+ expect(recovery).to include('git stash push')
12
13
  Dir.mktmpdir('pwn_upgrade') do |dir|
13
14
  git = lambda do |*args|
14
15
  out, status = Open3.capture2e('git', *args, chdir: dir)
@@ -34,7 +35,16 @@ describe PWN::ModuleSkills do
34
35
  File.write(File.join(dir, 'notes'), 'keep my edit')
35
36
  _, blocked = Open3.capture2e('git', 'merge', '--ff-only', 'incoming', chdir: dir)
36
37
  expect(blocked.success?).to be(false)
37
- out, status = Open3.capture2e('bash', '-ec', "generated_skills=()#{recovery}", chdir: dir)
38
+ expect(script).to include("git stash push -m 'pwn upgrade: saved generated module skills'")
39
+ skills = git.call('diff', '--name-only', 'HEAD', '--', 'etc/default_skills/pwn').lines.map(&:chomp).select do |relative|
40
+ full = File.join(dir, relative)
41
+ next false unless relative.end_with?('/SKILL.md') && File.file?(full)
42
+
43
+ body = File.read(full)
44
+ body.match?(/^[[:space:]]*generated:[[:space:]]*true[[:space:]]*$/) &&
45
+ !body.match?(/^[[:space:]]*preserve:[[:space:]]*true[[:space:]]*$/)
46
+ end
47
+ out, status = Open3.capture2e('git', 'stash', 'push', '-m', 'pwn upgrade: saved generated module skills', '--', *skills, chdir: dir)
38
48
  expect(status.success?).to be(true), out
39
49
  git.call('merge', '--ff-only', 'incoming')
40
50
  expect(File.read(path)).to eq("#{original}upstream\n")
@@ -439,3 +439,34 @@ describe 'PWN::Plugins::Log toggle-trace step' do
439
439
  expect(PWN::Plugins::Log.debug_dir).to include('logs')
440
440
  end
441
441
  end
442
+
443
+ describe PWN::Plugins::Log::DebugStderrTee do
444
+ include_context 'pwn tmp sandbox'
445
+
446
+ let(:path) { File.join(@tmp, 'stderr.log') }
447
+ let(:original) { StringIO.new(+''.b) }
448
+ let(:stream) { described_class.new(orig: original) }
449
+
450
+ before { PWN::Plugins::Log.start_debug(path: path, tee: StringIO.new) }
451
+ after { PWN::Plugins::Log.stop_debug }
452
+
453
+ it 'preserves split UTF-8 on stderr and filters binary-tagged spinner frames from the log' do
454
+ parts = ["\r\e[1G⠴".b, "résumé: \xE2".b, "\x82\xAC".b, ' — done', "\n"]
455
+ parts.each { |part| expect(stream.write(part.freeze)).to eq(part.bytesize) }
456
+
457
+ expect(original.string).to eq(parts.map(&:b).join)
458
+ body = File.read(path, encoding: 'UTF-8')
459
+ expect(body).to include("résumé: € — done\n")
460
+ expect(body).not_to include('⠴', '�')
461
+ end
462
+
463
+ it 'replaces malformed stderr bytes in the log without losing the warning or exposing a split secret' do
464
+ stream.write("warning\xFF api_".b)
465
+ stream.write("key=synthetic-sensitive-value\n".b)
466
+
467
+ body = File.read(path, encoding: 'UTF-8')
468
+ expect(body).to be_valid_encoding
469
+ expect(body).to include('warning� [REDACTED:')
470
+ expect(body).not_to include('synthetic-sensitive-value')
471
+ end
472
+ end
@@ -12,4 +12,34 @@ describe PWN::Plugins::PWNLogger do
12
12
  help_response = PWN::Plugins::PWNLogger
13
13
  expect(help_response).to respond_to :help
14
14
  end
15
+
16
+ it 'follows the current $stdout outside rake' do
17
+ previous = ENV.fetch('PWN_RAKE_SPEC', nil)
18
+ ENV.delete('PWN_RAKE_SPEC')
19
+ terminal = StringIO.new
20
+ redirected = StringIO.new
21
+ original = $stdout
22
+ $stdout = terminal
23
+ logger = described_class.create
24
+ $stdout = redirected
25
+ logger.info('Connecting to AWS EC2...')
26
+ expect(terminal.string).not_to include('Connecting to AWS')
27
+ expect(redirected.string).to include('[INFO] Connecting to AWS EC2...')
28
+ ensure
29
+ $stdout = original
30
+ previous.nil? ? ENV.delete('PWN_RAKE_SPEC') : ENV['PWN_RAKE_SPEC'] = previous
31
+ end
32
+
33
+ it 'writes nothing during rake, including the pwn logger' do
34
+ previous = ENV.fetch('PWN_RAKE_SPEC', nil)
35
+ ENV['PWN_RAKE_SPEC'] = '1'
36
+ sink = StringIO.new
37
+ original = $stdout
38
+ $stdout = sink
39
+ described_class.create.info('Connecting to AWS EC2...')
40
+ expect(sink.string).to eq('')
41
+ ensure
42
+ $stdout = original
43
+ previous.nil? ? ENV.delete('PWN_RAKE_SPEC') : ENV['PWN_RAKE_SPEC'] = previous
44
+ end
15
45
  end
@@ -2786,6 +2786,22 @@ describe 'pwn-ai curses launch' do # rubocop:disable Metrics/BlockLength -- publ
2786
2786
  expect(PWN::Env.dig(:ai, :openai, :reasoning_effort)).to eq('high')
2787
2787
  end
2788
2788
 
2789
+ it 'stops after a forbidden planning request and displays one access warning' do
2790
+ require 'rest-client'
2791
+ PWN::Env[:ai] = { active: :openai, openai: { model: 'fixture-model' }, agent: { plan_first: true } }
2792
+ calls = File.join(@tmp, 'provider-calls')
2793
+ response = Struct.new(:code, :body).new(403, 'private fixture response')
2794
+ allow(PWN::AI::OpenAI).to receive(:chat_with_tools) do |opts|
2795
+ File.open(calls, 'a') { |f| f.puts(opts[:tools].nil? ? 'planning' : 'turn') }
2796
+ raise RestClient::Forbidden, response
2797
+ end
2798
+ launch("List the files in this directory\n".chars) { "\u0004" unless @console.send(:busy?) }
2799
+ expect(File.readlines(calls, chomp: true)).to eq(['planning'])
2800
+ events = @console.instance_variable_get(:@timeline)
2801
+ expect(events.filter_map { |type, text, *| text if type == :warning }).to contain_exactly(a_string_matching(/HTTP 403.*model/i))
2802
+ expect(events.map { |_, text, *| text }.join).not_to match(/plan_first swallowed|private fixture response/)
2803
+ end
2804
+
2789
2805
  it 'honors locally selected model and resumed session in the actual provider call' do
2790
2806
  sid = PWN::Sessions.create(title: 'resumed console')[:id]
2791
2807
  PWN::Sessions.append(session_id: sid, role: 'user', content: 'Previous fixture question')
@@ -27,18 +27,35 @@ describe 'regex-ReAct mission containment' do
27
27
  Pry.config.hooks.get_hook(:after_read, :pwn_ai_hook).call(request, pry)
28
28
  end
29
29
 
30
+ def namespace_pids(status)
31
+ status.to_s[/^NSpid:[ \t]+([1-9]\d*(?:[ \t]+[1-9]\d*)*)\n/, 1].to_s.split.map(&:to_i)
32
+ end
33
+
30
34
  def wait_for_descendant_pid(marker)
35
+ observer = namespace_pids(File.read('/proc/self/status'))
36
+ raise 'Cannot identify the test runner PID namespace' unless observer.last == Process.pid
37
+
31
38
  Timeout.timeout(10) do
32
39
  loop do
33
- text = File.read(marker) if File.file?(marker)
34
- pid = text.to_s[/^NSpid:[ \t]+([1-9]\d*)(?:[ \t]+\d+)+\n/, 1]
35
- return pid.to_i if pid
40
+ if File.file?(marker)
41
+ pids = namespace_pids(File.read(marker))
42
+ return pids.fetch(observer.size - 1) if pids.size > observer.size
43
+ end
36
44
 
37
45
  sleep 0.01
38
46
  end
39
47
  end
40
48
  end
41
49
 
50
+ # Pin the live task before interrupting it. A pidfd reports exit even if
51
+ # another process has yet to reap it, and never follows a recycled PID.
52
+ def open_pidfd(pid)
53
+ fd = PWN::AI::Agent::MissionNamespace.native('pidfd_open', [Fiddle::TYPE_INT, Fiddle::TYPE_INT]).call(pid, 0)
54
+ raise SystemCallError.new('pidfd_open for descendant', Fiddle.last_error) if fd.negative?
55
+
56
+ IO.new(fd)
57
+ end
58
+
42
59
  it 'waits for the descendant PID contents rather than an empty readiness file' do
43
60
  marker = File.join(@tmp, 'partial-ready')
44
61
  File.write(marker, '')
@@ -48,6 +65,7 @@ describe 'regex-ReAct mission containment' do
48
65
  File.write(marker, "NSpid:\t12345\t1\n")
49
66
  end
50
67
  allow(File).to receive(:read).and_call_original
68
+ allow(File).to receive(:read).with('/proc/self/status').and_return("NSpid:\t#{Process.pid}\n")
51
69
  allow(File).to receive(:read).with(marker).and_wrap_original do |original, path|
52
70
  text = original.call(path)
53
71
  read_empty << true if text.empty?
@@ -58,6 +76,31 @@ describe 'regex-ReAct mission containment' do
58
76
  writer&.kill&.join
59
77
  end
60
78
 
79
+ it 'selects the PID visible to a nested upgrade runner, not the outer procfs PID' do
80
+ marker = File.join(@tmp, 'nested-ready')
81
+ File.write(marker, "NSpid:\t12345\t82\t1\n")
82
+ allow(File).to receive(:read).and_call_original
83
+ allow(File).to receive(:read).with('/proc/self/status').and_return("NSpid:\t12000\t#{Process.pid}\n")
84
+ expect(wait_for_descendant_pid(marker)).to eq(82)
85
+ end
86
+
87
+ it 'distinguishes a live child from an exited child that has not been reaped' do
88
+ reader, release = IO.pipe
89
+ pid = fork do
90
+ release.close
91
+ reader.read(1)
92
+ exit! 0
93
+ end
94
+ handle = open_pidfd(pid)
95
+ expect(handle.wait_readable(0)).to be_nil
96
+ release.close
97
+ expect(handle.wait_readable(5)).to be_truthy
98
+ expect(Process.kill(0, pid)).to eq(1) # The old probe still sees the zombie.
99
+ ensure
100
+ [release, reader, handle].compact.each { |io| io.close unless io.closed? }
101
+ Process.wait(pid) if pid
102
+ end
103
+
61
104
  it 'fails closed before calling a provider when mission containment is unavailable' do
62
105
  allow(PWN::Plugins::AISandbox::MissionProcess).to receive(:new).and_raise(PWN::Plugins::AISandbox::NotStarted, 'enable user/PID namespaces')
63
106
  expect(PWN::AI::Ollama).not_to receive(:chat)
@@ -168,10 +211,11 @@ describe 'regex-ReAct mission containment' do
168
211
  nil
169
212
  end
170
213
  marker = File.join(@tmp, '.pwn', 'workspaces', 'runtime', 'pty-ready')
171
- host_pid = wait_for_descendant_pid(marker)
214
+ descendant = open_pidfd(wait_for_descendant_pid(marker))
215
+ expect(descendant.wait_readable(0)).to be_nil, 'descendant exited before PTY CTRL+C'
172
216
  writer.write("\x03")
173
217
  Timeout.timeout(10) { sleep 0.01 until output.include?('CANCELLED READY') }
174
- expect { Process.kill(0, host_pid) }.to raise_error(Errno::ESRCH)
218
+ expect(descendant.wait_readable(0)).to be_truthy, 'detached descendant still alive at CANCELLED READY'
175
219
  writer.write("second\n")
176
220
  Timeout.timeout(10) { Process.wait(pid) }
177
221
  pid = nil
@@ -192,7 +236,7 @@ describe 'regex-ReAct mission containment' do
192
236
  nil
193
237
  end
194
238
  end
195
- [reader, writer].compact.each { |io| io.close unless io.closed? }
239
+ [descendant, reader, writer].compact.each { |io| io.close unless io.closed? }
196
240
  drain&.join(5)
197
241
  end
198
242
 
@@ -209,11 +253,12 @@ describe 'regex-ReAct mission containment' do
209
253
  rescue Interrupt
210
254
  :cancelled
211
255
  end
212
- host_pid = wait_for_descendant_pid(marker)
256
+ descendant = open_pidfd(wait_for_descendant_pid(marker))
257
+ expect(descendant.wait_readable(0)).to be_nil, 'descendant exited before interrupt'
213
258
  worker.raise(Interrupt)
214
259
  expect(Timeout.timeout(10) { worker.value }).to eq(:cancelled)
215
260
  expect(repl).to have_received(:ready_tty!)
216
- expect { Process.kill(0, host_pid) }.to raise_error(Errno::ESRCH)
261
+ expect(descendant.wait_readable(0)).to be_truthy, 'detached descendant still alive when the terminal became ready'
217
262
  sleep 1.1
218
263
  expect(File).not_to exist(late)
219
264
  allow(PWN::AI::Ollama).to receive(:chat).and_return(id: 'second', choices: [{ content: 'second complete' }])
@@ -222,6 +267,7 @@ describe 'regex-ReAct mission containment' do
222
267
  expect(PWN::Env.dig(:ai, :ollama, :response_history, :id)).to eq('second')
223
268
  expect(request).to eq('nil')
224
269
  ensure
270
+ descendant&.close
225
271
  worker&.raise(Interrupt) if worker&.alive?
226
272
  worker&.join(10)
227
273
  end
@@ -194,6 +194,24 @@ describe PWN::Plugins::REPL, 'mesh RX error boundaries' do
194
194
  expect(ids).to all(match(PWN::Sessions::SESSION_ID))
195
195
  end
196
196
 
197
+ it 'does not paint a Ruby thread dump when dispatch raises outside StandardError' do
198
+ allow(PWN::AI::Agent::Loop).to receive(:run).and_raise(NotImplementedError, 'offline dispatch')
199
+ stderr = StringIO.new
200
+ original = $stderr
201
+ $stderr = stderr
202
+ expect(described_class.send(:mesh_maybe_dispatch_to_pwn_ai, args)).to eq(:dispatched)
203
+ Timeout.timeout(5) { sleep 0.01 while PWN.const_defined?(:MeshDispatchLock) }
204
+ expect(stderr.string).not_to include('report_on_exception')
205
+ expect(described_class).to have_received(:mesh_ui_puts).with(hash_including(text: a_string_starting_with('AI failed: NotImplementedError: offline dispatch')))
206
+ ensure
207
+ $stderr = original
208
+ end
209
+
210
+ it 'drops a leaked Ruby thread-death banner from mesh notices' do
211
+ text = described_class.send(:mesh_notice_text, text: "#<Thread:0x00007f68c37b6078 /opt/pwn/lib/pwn/plugins/repl/mesh.rb:3494 run> terminated with exception (report_on_exception is true):\n")
212
+ expect(text).to be_nil
213
+ end
214
+
197
215
  %w[AI TX].each do |stage|
198
216
  it "labels #{stage} failures correctly and closes the session lease" do
199
217
  ids = Queue.new
@@ -2,7 +2,6 @@
2
2
 
3
3
  require 'spec_helper'
4
4
  require 'tmpdir'
5
- require 'open3'
6
5
  require 'uri'
7
6
 
8
7
  [PWN::Reports::SAST, PWN::Reports::AIRedTeam].each do |reporter|
@@ -10,7 +9,7 @@ require 'uri'
10
9
  [
11
10
  'ordinary',
12
11
  'fixture", "review": (globalThis.providerReviewMarker = 1), "unused": "',
13
- "space &?#%+\"'\\\n雪\u2028\u2029",
12
+ "space &?#%+\\\"'\\\n雪\u2028\u2029",
14
13
  'fixture</script><script>providerReviewMarker=1</script>'
15
14
  ].each do |name|
16
15
  it "preserves the filename as URL data for #{name.inspect}" do
@@ -21,23 +20,14 @@ require 'uri'
21
20
  html = File.read(File.join(dir, "#{name}.html"))
22
21
  expect(JSON.parse(File.read(File.join(dir, "#{name}.json")))).to eq('report_name' => name, 'data' => [])
23
22
  ajax = html.lines.find { |line| line.include?('"ajax":') }.strip.delete_suffix(',')
24
- code = <<~JS
25
- const vm = require('vm'), fs = require('fs'), context = {};
26
- const value = vm.runInNewContext('({' + fs.readFileSync(0, 'utf8') + '})', context);
27
- process.stdout.write(JSON.stringify({ajax: value.ajax, context}));
28
- JS
29
- stdout, stderr, status = Open3.capture3('node', '-e', code, stdin_data: ajax)
30
- expect(status.success?).to be(true), stderr
31
- result = JSON.parse(stdout)
32
- expect(result.fetch('context')).to eq({})
33
- url = result.fetch('ajax')
23
+ url = JSON.parse("{#{ajax}}").fetch('ajax')
34
24
  expect(url).not_to match(/[<>"'\\\s&#?]/)
35
25
  expect(URI.parse(url).scheme).to be_nil
36
26
  expect(URI.decode_www_form_component(url)).to eq("#{name}.json")
37
27
  expect(ajax).not_to include('</script>', '<script>', "\u2028", "\u2029")
38
28
  scripts = html.scan(%r{<script(?: [^>]*)?>(.*?)</script>}m).flatten.join("\n")
39
- _, stderr, status = Open3.capture3('node', '-e', 'new (require("vm").Script)(require("fs").readFileSync(0,"utf8"))', stdin_data: scripts)
40
- expect(status.success?).to be(true), stderr
29
+ expect(scripts).not_to include(name) if name.match?(/[<>"']/)
30
+ expect(scripts).not_to include("\u2028", "\u2029")
41
31
  end
42
32
  end
43
33
  end
@@ -15,7 +15,7 @@ RSpec.describe PWN::SAST::TestCaseEngine, 'formatter review safeguards' do
15
15
  FileUtils.mkdir_p(@sources)
16
16
  @lock_path = File.expand_path('../../../../Gemfile.lock', __dir__)
17
17
  @lock_before = File.binread(@lock_path)
18
- @js_beautify_bin = Gem.bin_path('js-beautify', 'js-beautify')
18
+
19
19
  saved_env = %w[BUNDLE_GEMFILE BUNDLE_LOCKFILE RUBYOPT BUNDLE_FROZEN].to_h { |key| [key, ENV.fetch(key, nil)] }
20
20
  original_path = ENV.fetch('PATH')
21
21
  # Fixture subprocesses must not inherit the checkout lock path. Clearing
@@ -150,19 +150,25 @@ RSpec.describe PWN::SAST::TestCaseEngine, 'formatter review safeguards' do
150
150
  name = 'source;printf proof>review-marker;#.js'
151
151
  source = 'var fixture={value:1};'
152
152
  File.write(File.join(@sources, name), source)
153
- commands_dir = File.join(@root, 'commands')
154
- FileUtils.mkdir_p(commands_dir)
155
153
  shell_commands = []
156
154
  allow(described_class).to receive(:`).and_wrap_original do |original, command|
157
155
  shell_commands << command
158
156
  original.call(command)
159
157
  end
160
- # Load the actual gem launcher by its original path: it resolves its
161
- # bundled parser relative to __FILE__, so symlinking that file breaks it.
162
- launcher = File.join(commands_dir, 'js-beautify')
163
- File.write(launcher, "#!#{RbConfig.ruby}\nload #{@js_beautify_bin.dump}\n")
164
- File.chmod(0o700, launcher)
165
- ENV['PATH'] = "#{commands_dir}:#{ENV.fetch('PATH')}"
158
+ # Exercise the installed launcher's argument handling, not its Python parser.
159
+ # Only the launcher child sees this PATH; it cannot fall back to host Python.
160
+ backend_dir = File.join(@root, 'backend')
161
+ Dir.mkdir(backend_dir)
162
+ backend = File.join(backend_dir, 'python')
163
+ File.write(backend, <<~RUBY)
164
+ #!#{RbConfig.ruby}
165
+ abort 'expected parser and stdin selector' unless ARGV.size == 2 && File.file?(ARGV.first) && ARGV.last == '-'
166
+ abort 'expected source bytes on stdin' unless STDIN.binmode.read == #{source.dump}
167
+ puts 'var fixture = { value: 1 };'
168
+ RUBY
169
+ File.chmod(0o700, backend)
170
+ launcher = Gem.bin_path('js-beautify', 'js-beautify')
171
+ synthetic_formatter("ENV['PATH'] = #{backend_dir.dump}\nload #{launcher.dump}")
166
172
 
167
173
  result = described_class.execute(options)
168
174
 
@@ -170,8 +176,8 @@ RSpec.describe PWN::SAST::TestCaseEngine, 'formatter review safeguards' do
170
176
  expect(shell_commands.join("\n")).not_to include(Shellwords.escape(name))
171
177
  expect(File.exist?(File.join(@sources, 'review-marker'))).to be(false)
172
178
  expect(result.length).to eq(1)
173
- expect(result.first[:filename][:entry_beautified]).to be(true)
174
- expect(result.first[:line_no_and_contents].first[:contents]).to include('var fixture = {')
179
+ expect(result.first[:filename]).to include(entry: "./#{name}", entry_beautified: true)
180
+ expect(result.first[:line_no_and_contents].first[:contents]).to eq("var fixture = { value: 1 };\n")
175
181
  expect(File.read(File.join(@sources, name))).to eq(source)
176
182
  expect(Digest::SHA256.file(@lock_path).hexdigest).to eq(Digest::SHA256.hexdigest(@lock_before))
177
183
  end
@@ -63,6 +63,27 @@ RSpec.describe PWN::SessionCleanup, 'concurrent maintenance' do
63
63
  Timeout.timeout(5) { described_class.maintain(proc_root: @processes) }
64
64
  end
65
65
 
66
+ it 'registers a forked session owner while the parent is iterating its owner markers' do
67
+ sid = PWN::Sessions.create[:id]
68
+ owners = PWN::Sessions.instance_variable_get(:@activity_owners)
69
+ # Fork with a live Hash iterator, rather than racing the scheduler to catch one.
70
+ iterator = owners.each_key
71
+ iterator.next
72
+ input, output = worker do |commands, replies|
73
+ lease = PWN::Sessions.activate(session_id: sid)
74
+ replies.puts('leased')
75
+ commands.gets
76
+ PWN::Sessions.deactivate(lease: lease)
77
+ replies.puts('released')
78
+ end
79
+ expect(message(output)).to eq('leased')
80
+ expect(PWN::Sessions.active?(session_id: sid)).to be(true)
81
+ expect(described_class.legacy_owners(@processes)).to be_empty
82
+ input.puts('release')
83
+ expect(message(output)).to eq('released')
84
+ expect(PWN::Sessions.active?(session_id: sid)).to be(false)
85
+ end
86
+
66
87
  it 'retains two real active clients, deletes unrelated work and revisits released evidence' do
67
88
  ids = 3.times.map { PWN::Sessions.create[:id] }
68
89
  learning = PWN::AI::Agent::Learning
data/spec/spec_helper.rb CHANGED
@@ -67,8 +67,38 @@ RSpec.configure do |config|
67
67
  original_stderr = $stderr
68
68
  devnull = StringIO.new
69
69
 
70
+ if ENV['PWN_RAKE_SPEC'] == '1'
71
+ config.before(:suite) do
72
+ next if defined?(PWN_RAKE_STDOUT_SILENCED)
73
+
74
+ reporter = RSpec.configuration.reporter
75
+ listeners = reporter.instance_variable_get(:@listeners).values.flat_map(&:to_a).uniq
76
+ terminal = nil
77
+ silenced = []
78
+ listeners.each do |listener|
79
+ next unless listener.instance_variable_defined?(:@output)
80
+
81
+ wrapped = listener.instance_variable_get(:@output)
82
+ stream = wrapped.is_a?(RSpec::Core::OutputWrapper) ? wrapped.output : wrapped
83
+ next unless stream.respond_to?(:reopen) && stream.respond_to?(:fileno) && stream.fileno == 1
84
+ next if silenced.include?(stream)
85
+
86
+ terminal ||= stream.dup.tap { |io| io.sync = true }
87
+ if wrapped.is_a?(RSpec::Core::OutputWrapper)
88
+ wrapped.output = terminal
89
+ else
90
+ listener.instance_variable_set(:@output, terminal)
91
+ end
92
+ stream.reopen(File::NULL)
93
+ stream.sync = true
94
+ silenced << stream
95
+ end
96
+ Object.const_set(:PWN_RAKE_STDOUT_SILENCED, true)
97
+ end
98
+ end
99
+
70
100
  config.before(:each) do |example|
71
- next if example.metadata[:stdout]
101
+ next if example.metadata[:stdout] && ENV['PWN_RAKE_SPEC'] != '1'
72
102
 
73
103
  devnull.truncate(0)
74
104
  devnull.rewind
@@ -82,8 +112,7 @@ RSpec.configure do |config|
82
112
  end
83
113
  end
84
114
 
85
- # Logger.new($stdout) captures the IO at class load — the same stream RSpec
86
- # uses for progress dots. Reassigning $stdout in before(:each) does not
87
- # retarget that logger. Point the red-team engine at /dev/null so execute
88
- # banners cannot leak into rake.
115
+ # During rake, PWNLogger writes nothing and STDOUT itself is /dev/null.
116
+ # Direct rspec still redirects $stdout per example. PWN_SPEC_VERBOSE=1
117
+ # leaves both attached. Point any other captured logger at /dev/null.
89
118
  PWN::AI::RedTeam::TestCaseEngine.class_variable_set(:@@logger, Logger.new(File::NULL)) if defined?(PWN::AI::RedTeam::TestCaseEngine)
@@ -614,6 +614,7 @@
614
614
  {"messages":[{"role":"user","content":"PWN::AI::Agent::MissionNamespace.new Usage"},{"role":"assistant","content":"`PWN::AI::Agent::MissionNamespace.new`: "}]}
615
615
  {"messages":[{"role":"user","content":"PWN::AI::Agent::MissionNamespace.prepared? Usage"},{"role":"assistant","content":"`PWN::AI::Agent::MissionNamespace.prepared?`: "}]}
616
616
  {"messages":[{"role":"user","content":"PWN::AI::Agent::MissionNamespace.supervise Usage"},{"role":"assistant","content":"`PWN::AI::Agent::MissionNamespace.supervise`: "}]}
617
+ {"messages":[{"role":"user","content":"PWN::AI::Agent::MissionNamespace.supervise_host Usage"},{"role":"assistant","content":"`PWN::AI::Agent::MissionNamespace.supervise_host`: "}]}
617
618
  {"messages":[{"role":"user","content":"PWN::AI::Agent::MissionNamespace.close Usage"},{"role":"assistant","content":"`PWN::AI::Agent::MissionNamespace.close`: "}]}
618
619
  {"messages":[{"role":"user","content":"PWN::AI::Agent::MissionNamespace.wait Usage"},{"role":"assistant","content":"`PWN::AI::Agent::MissionNamespace.wait`: "}]}
619
620
  {"messages":[{"role":"user","content":"PWN::AI::Agent::Mistakes.applicable_fix? Usage"},{"role":"assistant","content":"`PWN::AI::Agent::Mistakes.applicable_fix?`: "}]}
@@ -3226,6 +3227,7 @@
3226
3227
  {"messages":[{"role":"user","content":"PWN::Plugins::Log.spinner_frame? Usage"},{"role":"assistant","content":"`PWN::Plugins::Log.spinner_frame?`: "}]}
3227
3228
  {"messages":[{"role":"user","content":"PWN::Plugins::Log.start_debug Usage"},{"role":"assistant","content":"`PWN::Plugins::Log.start_debug`: "}]}
3228
3229
  {"messages":[{"role":"user","content":"PWN::Plugins::Log.start_trace! Usage"},{"role":"assistant","content":"`PWN::Plugins::Log.start_trace!`: "}]}
3230
+ {"messages":[{"role":"user","content":"PWN::Plugins::Log.stderr_text Usage"},{"role":"assistant","content":"`PWN::Plugins::Log.stderr_text`: "}]}
3229
3231
  {"messages":[{"role":"user","content":"PWN::Plugins::Log.stop_debug Usage"},{"role":"assistant","content":"`PWN::Plugins::Log.stop_debug`: "}]}
3230
3232
  {"messages":[{"role":"user","content":"PWN::Plugins::Log.stop_trace! Usage"},{"role":"assistant","content":"`PWN::Plugins::Log.stop_trace!`: "}]}
3231
3233
  {"messages":[{"role":"user","content":"PWN::Plugins::Log.trace_arguments Usage"},{"role":"assistant","content":"`PWN::Plugins::Log.trace_arguments`: "}]}
@@ -3442,8 +3444,16 @@
3442
3444
  {"messages":[{"role":"user","content":"PWN::Plugins::PS.help Usage"},{"role":"assistant","content":"`PWN::Plugins::PS.help`: "}]}
3443
3445
  {"messages":[{"role":"user","content":"PWN::Plugins::PS.list Usage"},{"role":"assistant","content":"`PWN::Plugins::PS.list`: Supported Method Parameters\n\nproc_list_arr = PWN::Plugins::PS.list\n"}]}
3444
3446
  {"messages":[{"role":"user","content":"PWN::Plugins::PWNLogger.authors Usage"},{"role":"assistant","content":"`PWN::Plugins::PWNLogger.authors`: Author(s)\n\n0day Inc. <support@0dayinc.com>\n"}]}
3445
- {"messages":[{"role":"user","content":"PWN::Plugins::PWNLogger.create Usage"},{"role":"assistant","content":"`PWN::Plugins::PWNLogger.create`: Supported Method Parameters\n\nPWN::Plugins::PWNLogger.create( )\n"}]}
3447
+ {"messages":[{"role":"user","content":"PWN::Plugins::PWNLogger.create Usage"},{"role":"assistant","content":"`PWN::Plugins::PWNLogger.create`: "}]}
3446
3448
  {"messages":[{"role":"user","content":"PWN::Plugins::PWNLogger.help Usage"},{"role":"assistant","content":"`PWN::Plugins::PWNLogger.help`: "}]}
3449
+ {"messages":[{"role":"user","content":"PWN::Plugins::PWNLogger::CurrentStdout.<< Usage"},{"role":"assistant","content":"`PWN::Plugins::PWNLogger::CurrentStdout.<<`: "}]}
3450
+ {"messages":[{"role":"user","content":"PWN::Plugins::PWNLogger::CurrentStdout.close Usage"},{"role":"assistant","content":"`PWN::Plugins::PWNLogger::CurrentStdout.close`: "}]}
3451
+ {"messages":[{"role":"user","content":"PWN::Plugins::PWNLogger::CurrentStdout.flush Usage"},{"role":"assistant","content":"`PWN::Plugins::PWNLogger::CurrentStdout.flush`: "}]}
3452
+ {"messages":[{"role":"user","content":"PWN::Plugins::PWNLogger::CurrentStdout.reopen Usage"},{"role":"assistant","content":"`PWN::Plugins::PWNLogger::CurrentStdout.reopen`: "}]}
3453
+ {"messages":[{"role":"user","content":"PWN::Plugins::PWNLogger::CurrentStdout.sync Usage"},{"role":"assistant","content":"`PWN::Plugins::PWNLogger::CurrentStdout.sync`: "}]}
3454
+ {"messages":[{"role":"user","content":"PWN::Plugins::PWNLogger::CurrentStdout.sync= Usage"},{"role":"assistant","content":"`PWN::Plugins::PWNLogger::CurrentStdout.sync=`: "}]}
3455
+ {"messages":[{"role":"user","content":"PWN::Plugins::PWNLogger::CurrentStdout.tty? Usage"},{"role":"assistant","content":"`PWN::Plugins::PWNLogger::CurrentStdout.tty?`: "}]}
3456
+ {"messages":[{"role":"user","content":"PWN::Plugins::PWNLogger::CurrentStdout.write Usage"},{"role":"assistant","content":"`PWN::Plugins::PWNLogger::CurrentStdout.write`: "}]}
3447
3457
  {"messages":[{"role":"user","content":"PWN::Plugins::Packet.authors Usage"},{"role":"assistant","content":"`PWN::Plugins::Packet.authors`: Author(s)\n\n0day Inc. <support@0dayinc.com>\n"}]}
3448
3458
  {"messages":[{"role":"user","content":"PWN::Plugins::Packet.cap_net_raw? Usage"},{"role":"assistant","content":"`PWN::Plugins::Packet.cap_net_raw?`: "}]}
3449
3459
  {"messages":[{"role":"user","content":"PWN::Plugins::Packet.capture Usage"},{"role":"assistant","content":"`PWN::Plugins::Packet.capture`: "}]}