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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 32b81de8ec15d62449ac8f8894ae59adb2aff049f42e9fa7d5eafcaf172edea1
4
- data.tar.gz: 5a4a451600653d08a64288b559ad54829755ad30c5f5dde538087cfc8cbd29f6
3
+ metadata.gz: c38e0a1f930f304cf9e00ac69c38f28c5430e300ee11e44c6c60cbc9873a882b
4
+ data.tar.gz: 202b5e1f81b967675b8bdbef028efec9b4d819eac46364a81d76560fcf270cf5
5
5
  SHA512:
6
- metadata.gz: b87c67abeb39e314cc040e2f186d9e08f5c04520540a25526f376792ac5d7f7081281b4901aa7ef0e7b0c4c3e1ff4afd2f88005d65ccc0692e7ea653049fffde
7
- data.tar.gz: ba2a8e92e3318fa41df6821f74d62d2eb43e38a301fa3226b8a79468bb98f814046389adba32f9581ac3eb4d129d46a0418674d2ad829b9783f8d81bd5ea13a8
6
+ metadata.gz: 43b187378cc6943a2c6783833de1422f89edda0c132dba35dd82a727cb328d52650c8f1e0b29535aa3e24d8d631751fce4128104571cf8d7529503c1b41ccd75
7
+ data.tar.gz: 53ca63d1f232d26b747dc11af49ceaac8c696f21d5ebf6d48c8f41444da2a5c7676c904472dc1cf5966956ac1f330cbecfd92d3910facee0a5abfbae4910c3ce
data/Gemfile CHANGED
@@ -20,7 +20,7 @@ gem 'base32', '0.3.4'
20
20
  gem 'bitcoin-ruby', '0.0.20'
21
21
  gem 'brakeman', '8.1.0'
22
22
  gem 'bson', '5.2.0'
23
- gem 'bundler', '>=4.0.24'
23
+ gem 'bundler', '>=4.1.0'
24
24
  gem 'bundler-audit', '>=0.9.3'
25
25
  gem 'bunny', '3.6.0'
26
26
  gem 'colorize', '1.1.0'
@@ -30,7 +30,7 @@ gem 'diffy', '3.4.4'
30
30
  gem 'eventmachine', '1.2.7'
31
31
  gem 'executable-hooks', '1.7.1'
32
32
  gem 'faker', '3.8.0'
33
- gem 'faye-websocket', '0.12.0'
33
+ gem 'faye-websocket', '0.13.0'
34
34
  gem 'ffi', '1.17.4'
35
35
  # gem 'fftw3', '0.3'
36
36
  gem 'gdb', '1.0.0'
@@ -49,10 +49,10 @@ gem 'jwt', '3.3.0'
49
49
  gem 'libusb', '0.8.0'
50
50
  gem 'luhn', '3.0.0'
51
51
  gem 'mail', '2.9.1'
52
- gem 'mcp', '1.10.0'
53
- gem 'meshtastic', '0.0.192'
52
+ gem 'mcp', '1.11.0'
53
+ gem 'meshtastic', '0.0.193'
54
54
  gem 'metasm', '1.0.6'
55
- gem 'mongo', '2.26.1'
55
+ gem 'mongo', '2.26.2'
56
56
  gem 'msfrpc-client', '1.1.2'
57
57
  gem 'netaddr', '2.0.6'
58
58
  gem 'net-ldap', '0.21.0'
@@ -81,7 +81,7 @@ gem 'rmagick', '7.2.0'
81
81
  gem 'rqrcode', '3.2.0'
82
82
  gem 'rspec', '3.13.2'
83
83
  gem 'rtesseract', '3.1.4'
84
- gem 'rubocop', '1.92.2'
84
+ gem 'rubocop', '1.92.3'
85
85
  gem 'rubocop-rake', '0.7.1'
86
86
  gem 'rubocop-rspec', '3.10.2'
87
87
  gem 'ruby-audio', '1.6.1'
@@ -89,8 +89,8 @@ gem 'ruby-nmap', '1.0.3'
89
89
  gem 'ruby-saml', '1.18.1'
90
90
  gem 'rvm', '1.11.3.9'
91
91
  gem 'savon', '2.18.1'
92
- gem 'selenium-devtools', '0.156.0'
93
- gem 'selenium-webdriver', '4.52.0'
92
+ gem 'selenium-devtools', '0.157.0'
93
+ gem 'selenium-webdriver', '4.53.0'
94
94
  gem 'slack-ruby-client', '3.3.0'
95
95
  gem 'socksify', '1.8.1'
96
96
  gem 'spreadsheet', '1.3.5'
@@ -12,11 +12,13 @@ not the ownership boundary: setsid, double forks, and nested child namespaces
12
12
  remain descendants of the mission namespace. Other sessions and unrelated
13
13
  processes are not signalled.
14
14
 
15
- There is no systemd, cgroup, application compiler, or PGID fallback.
15
+ There is no systemd, cgroup, or application compiler.
16
16
  `PWN::AI::Agent::MissionNamespace` is Ruby code using stdlib Fiddle for Linux pidfds and
17
- process-death signals. Its runtime prerequisite is **util-linux `unshare`**
18
- (`pwn setup --profile ai`). Linux user/PID namespaces and pidfds must be enabled;
19
- unsupported kernels or local policy fail closed with setup guidance.
17
+ process-death signals. It uses util-linux `unshare` when the kernel allows a user
18
+ namespace. If that call is denied, or the namespace child closes the supervision
19
+ socket, the same handshake runs in a process-group supervisor. No apparmor or
20
+ sysctl change is required. A setsid descendant can leave a process group; a PID
21
+ namespace, when available, is what reaps those.
20
22
 
21
23
  Ruby recreates its timer thread after fork, so creating a user namespace from a
22
24
  Ruby fork is not supported. For ordinary launches the controller **execs** an
@@ -65,7 +65,7 @@ a process that is already running. Restart after installing the matching package
65
65
  | Contract | Current behavior |
66
66
  | --- | --- |
67
67
  | Tool writes | Unspecified `pwn-ai` writes and `TMPDIR` use `~/.pwn/workspaces/runtime`. Another path is writable only when the original operator request names it, including `mv`/`to`. A missing file grants its parent so the file can be created; that parent is still granted when it contains unrelated unreadable directories. `/opt/pwn` and the loaded package stay read-only. |
68
- | Mission lifetime | CTRL+C kills the mission through `PWN::AI::Agent::MissionNamespace`. That owner is Ruby plus util-linux `unshare` and Linux pidfds. There is no compiled `pwn_mission` extension and no systemd fallback. |
68
+ | Mission lifetime | CTRL+C kills the mission through `PWN::AI::Agent::MissionNamespace`. That owner is Ruby plus a pidfd. It uses util-linux `unshare` when the kernel allows a user namespace, and otherwise a process-group supervisor. There is no compiled `pwn_mission` extension and no systemd fallback. No apparmor or sysctl change is required. |
69
69
  | Recovery copies | Every PWN recovery producer uses `PWN::Backups` and `~/.pwn/backup/`, seven generation folders total. Adjacent `.bak` files are not the current producer. |
70
70
  | Housekeeping | A fresh install seeds one internal `session_cleanup` coordinator. Curriculum jobs are not seeded. Housekeeping never uses systemd. |
71
71
  | YubiKey | `PWN::Plugins::YubiKey` is native Ruby over HIDAPI and PC/SC. `required_bins` is empty and no `ykman` process is started. A library probe is not a connected device. Fixture coverage is not physical interoperability. See [YubiKey](YubiKey.md). |
@@ -10,10 +10,12 @@ metadata:
10
10
 
11
11
  # PWN::AI::Agent::MissionNamespace
12
12
 
13
- Launch typed mission descriptors using util-linux `unshare`, Ruby stdlib
14
- Fiddle pidfds, and private inherited sockets. Install `pwn setup --profile ai`.
15
- Linux user/PID namespaces and pidfds must be enabled. Unsupported hosts fail
16
- closed; there is no process-group or uncontained fallback.
13
+ Launch typed mission descriptors using util-linux `unshare` when the kernel
14
+ allows an unprivileged user namespace. If that call is denied, or the
15
+ namespace child closes the supervision socket, the same handshake runs in a
16
+ process-group supervisor. No apparmor or sysctl change is required. Pidfds
17
+ still cancel the owned child. A setsid descendant can leave a process group;
18
+ a PID namespace, when available, is what reaps those.
17
19
 
18
20
  The controller remains outside namespaces. Each request transfers its private
19
21
  configuration snapshot in memory, then owns a PID namespace. Cancellation kills
@@ -1690,6 +1690,10 @@ module PWN
1690
1690
  Thread.current[:pwn_plan_predicted] = predicted
1691
1691
  predicted
1692
1692
  rescue StandardError => e
1693
+ # A forbidden request is not a missing plan. Stop before calling the
1694
+ # provider a second time with tools enabled.
1695
+ raise if e.respond_to?(:http_code) && e.http_code == 403
1696
+
1693
1697
  warn "[pwn-ai/loop] plan_first swallowed: #{e.class}: #{e.message}"
1694
1698
  nil
1695
1699
  end
@@ -86,10 +86,10 @@ module PWN
86
86
  end
87
87
  end
88
88
 
89
- def supervise
89
+ def supervise(pid_namespace: true)
90
90
  channel = UNIXSocket.for_fd(3)
91
91
  snapshot = decode(JSON.parse(channel.gets))
92
- checked(native('unshare', [Fiddle::TYPE_INT]).call(0x20000000), 'unshare PID namespace')
92
+ checked(native('unshare', [Fiddle::TYPE_INT]).call(0x20000000), 'unshare PID namespace') if pid_namespace
93
93
  reader, writer = IO.pipe
94
94
  armed, arm = IO.pipe
95
95
  init = fork do
@@ -151,6 +151,13 @@ module PWN
151
151
  channel&.close unless channel&.closed?
152
152
  end
153
153
 
154
+ # Same handshake without util-linux unshare or a user/PID namespace.
155
+ # The supervisor is a process-group leader so cancellation still reaches
156
+ # children that have not called setsid.
157
+ def supervise_host
158
+ supervise(pid_namespace: false)
159
+ end
160
+
154
161
  def execute(descriptor)
155
162
  case descriptor.fetch(:operation).to_sym
156
163
  when :command
@@ -202,21 +209,22 @@ module PWN
202
209
  end
203
210
  snapshot[:requires].uniq!
204
211
  end
212
+ mode = opts[:containment] == :host ? :host : :namespace
205
213
  payload = JSON.generate(self.class.encode(snapshot))
206
- @channel, child = UNIXSocket.pair
207
- mapping = opts.fetch(:fds, {}).merge(3 => child)
208
- @pid = Process.spawn('unshare', '--user', '--map-current-user', '--keep-caps', RbConfig.ruby, '-I', $LOAD_PATH.join(File::PATH_SEPARATOR), '-rpwn', '-e', 'exit!(PWN::AI::Agent::MissionNamespace.supervise || 1)', mapping.merge(close_others: true))
209
- child.close
210
- Timeout.timeout(15) do
211
- @channel.puts(payload)
212
- @pidfd = @channel.recv_io
213
- @channel.write('1')
214
- end
214
+ start_supervisor(payload, opts, mode)
215
215
  rescue Exception => e # rubocop:disable Lint/RescueException -- failed startup cannot leak a child
216
216
  close
217
- raise Unavailable, "mission not started: #{e.message}; install util-linux unshare and enable Linux user/PID namespaces and pidfds"
218
- ensure
219
- child&.close unless child&.closed?
217
+ detail = startup_detail(e)
218
+ raise Unavailable, detail unless mode != :host && !@host_attempted && namespace_denied?(detail)
219
+
220
+ @host_attempted = true
221
+ @child_error = nil
222
+ begin
223
+ start_supervisor(payload, opts, :host)
224
+ rescue Exception => host_error # rubocop:disable Lint/RescueException -- second attempt must not leak a child
225
+ close
226
+ raise Unavailable, "#{detail}; host supervisor: #{startup_detail(host_error)}"
227
+ end
220
228
  end
221
229
 
222
230
  def wait
@@ -230,6 +238,13 @@ module PWN
230
238
  return :reaped unless @mutex
231
239
 
232
240
  @mutex.synchronize do
241
+ if @group && @pid
242
+ begin
243
+ Process.kill('KILL', -@group)
244
+ rescue Errno::ESRCH, Errno::EPERM
245
+ nil
246
+ end
247
+ end
233
248
  if @pidfd && !@pidfd.closed?
234
249
  result = self.class.native('pidfd_send_signal', [Fiddle::TYPE_INT, Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP, Fiddle::TYPE_INT]).call(@pidfd.fileno, Signal.list.fetch('KILL'), 0, 0)
235
250
  self.class.checked(result, 'pidfd_send_signal') unless result.negative? && Fiddle.last_error == Errno::ESRCH::Errno
@@ -263,6 +278,44 @@ module PWN
263
278
 
264
279
  private
265
280
 
281
+ def start_supervisor(payload, opts, mode)
282
+ @channel, child = UNIXSocket.pair
283
+ err_read, err_write = IO.pipe
284
+ mapping = opts.fetch(:fds, {}).merge(3 => child, err: err_write)
285
+ entry = mode == :host ? 'supervise_host' : 'supervise'
286
+ command = [RbConfig.ruby, '-I', $LOAD_PATH.join(File::PATH_SEPARATOR), '-rpwn', '-e', "exit!(PWN::AI::Agent::MissionNamespace.#{entry} || 1)"]
287
+ command = ['unshare', '--user', '--map-current-user', '--keep-caps', *command] if mode == :namespace
288
+ spawn_opts = mapping.merge(close_others: true)
289
+ spawn_opts[:pgroup] = true if mode == :host
290
+ @pid = Process.spawn(*command, spawn_opts)
291
+ @group = @pid if mode == :host
292
+ child.close
293
+ err_write.close
294
+ drain = Thread.new { @child_error = err_read.read }
295
+ drain.report_on_exception = false
296
+ @stderr_thread = drain
297
+ @stderr_read = err_read
298
+ Timeout.timeout(15) do
299
+ @channel.puts(payload)
300
+ @pidfd = @channel.recv_io
301
+ @channel.write('1')
302
+ end
303
+ ensure
304
+ child&.close unless child&.closed?
305
+ err_write&.close unless err_write&.closed?
306
+ end
307
+
308
+ def startup_detail(error)
309
+ [@child_error.to_s.strip, error.message].reject(&:empty?).uniq.join('; ')
310
+ end
311
+
312
+ def namespace_denied?(detail)
313
+ text = detail.to_s
314
+ return false if text.match?(/snapshot|unknown mission operation|ArgumentError/)
315
+
316
+ text.match?(/Broken pipe|unshare|namespace|Operation not permitted|Invalid argument|No such file or directory/i)
317
+ end
318
+
266
319
  def start_prepared(opts, &operation)
267
320
  ready, announce = IO.pipe
268
321
  release, gate = IO.pipe
@@ -321,6 +374,9 @@ module PWN
321
374
  def reap
322
375
  _pid, @status = Process.wait2(@pid) if @pid
323
376
  @pid = nil
377
+ @group = nil
378
+ @stderr_thread&.join(1)
379
+ @stderr_read&.close unless @stderr_read&.closed?
324
380
  @channel&.close unless @channel&.closed?
325
381
  @pidfd&.close unless @pidfd&.closed?
326
382
  :reaped
@@ -338,16 +338,17 @@ module PWN
338
338
 
339
339
  return if @stderr_redaction_overflow
340
340
 
341
- text = opts[:text].to_s
341
+ text = stderr_text(text: opts[:text])
342
342
  return if text.empty?
343
- return if spinner_frame?(text: text)
343
+ return if spinner_frame?(text: text) && (@stderr_redaction_buffer.to_s.empty? || !text.strip.empty?)
344
344
 
345
345
  Thread.current[:pwn_log_stderr] = true
346
346
  begin
347
347
  io = @debug_file
348
348
  return if io.nil? || (io.respond_to?(:closed?) && io.closed?)
349
349
 
350
- @stderr_redaction_buffer = @stderr_redaction_buffer.to_s + text.gsub(/\e\[[0-9;]*m/, '')
350
+ # A write can end in the middle of a UTF-8 character or an ANSI escape.
351
+ @stderr_redaction_buffer = @stderr_redaction_buffer.to_s.b + text.b
351
352
  buffer = @stderr_redaction_buffer
352
353
  if buffer.bytesize > 65_536
353
354
  clean = PWN::Redaction.token(kind: 'stream', value: buffer)
@@ -355,6 +356,8 @@ module PWN
355
356
  else
356
357
  # A write may split a JWT/header; PEM bodies may span many writes.
357
358
  return unless buffer.end_with?("\n")
359
+
360
+ buffer = stderr_text(text: buffer).scrub.gsub(/\e\[[0-9;]*m/, '')
358
361
  return if buffer.match?(/-----BEGIN [A-Z ]*PRIVATE KEY-----/) && !buffer.match?(/-----END [A-Z ]*PRIVATE KEY-----/)
359
362
 
360
363
  clean = sanitize_debug_text(text: buffer)
@@ -373,10 +376,18 @@ module PWN
373
376
  clean
374
377
  end
375
378
 
376
- # Spinner frames stay on the TTY; never persist them in the RN log.
379
+ private_class_method def self.stderr_text(opts = {})
380
+ text = opts[:text].to_s
381
+ return text.dup.force_encoding(Encoding::UTF_8) if text.encoding == Encoding::BINARY
382
+ return text if text.encoding == Encoding::UTF_8
383
+
384
+ text.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
385
+ end
386
+
387
+ # Spinner frames stay on the TTY; an incomplete character isn't a frame.
377
388
  public_class_method def self.spinner_frame?(opts = {})
378
- raw = opts[:text].to_s
379
- return false if raw.empty?
389
+ raw = stderr_text(text: opts[:text])
390
+ return false if raw.empty? || !raw.valid_encoding?
380
391
 
381
392
  stripped = raw.gsub(/\e\[[0-9;?]*[A-Za-z]/, '').delete("\r").delete("\b")
382
393
  stripped = stripped.gsub(/[\u2800-\u28FF]/, '')
@@ -11,8 +11,44 @@ module PWN
11
11
  # PWN::Plugins::PWNLogger.create(
12
12
  # )
13
13
 
14
+ # Writes to the current $stdout. Logger.new($stdout) captures the terminal
15
+ # at construction, so rake's per-example redirect cannot hide those lines.
16
+ class CurrentStdout
17
+ def write(*)
18
+ return 0 if ENV['PWN_RAKE_SPEC'] == '1' && ENV['PWN_SPEC_VERBOSE'] != '1'
19
+
20
+ $stdout.write(*)
21
+ end
22
+
23
+ def <<(arg)
24
+ write(arg)
25
+ end
26
+
27
+ def flush
28
+ $stdout.flush
29
+ end
30
+
31
+ def sync
32
+ $stdout.sync
33
+ end
34
+
35
+ def sync=(value)
36
+ $stdout.sync = value
37
+ end
38
+
39
+ def close; end
40
+
41
+ def reopen(*)
42
+ self
43
+ end
44
+
45
+ def tty?
46
+ $stdout.tty?
47
+ end
48
+ end
49
+
14
50
  public_class_method def self.create(opts = {})
15
- logger = Logger.new($stdout)
51
+ logger = Logger.new(CurrentStdout.new)
16
52
  level = opts[:level]
17
53
 
18
54
  case level.to_s.downcase.to_sym
@@ -806,7 +806,12 @@ module PWN
806
806
  events << [:session_title, PWN::Sessions.refresh_title(session_id: session_id, ai_config: title_config, on_error: ->(kind) { events << [:warning, "Session title refresh unavailable (#{kind}); previous title retained."] })]
807
807
  end
808
808
  rescue StandardError, Interrupt, Control::Stopped => e
809
- events << [:warning, "#{e.class}: #{e.message}"]
809
+ warning = if e.respond_to?(:http_code) && e.http_code == 403
810
+ 'Access denied (HTTP 403). Check that your account can use the selected model and endpoint.'
811
+ else
812
+ "#{e.class}: #{e.message}"
813
+ end
814
+ events << [:warning, warning]
810
815
  ensure
811
816
  output.flush
812
817
  writer.close
@@ -1988,6 +1988,9 @@ class << PWN::Plugins::REPL # rubocop:disable Metrics/ClassLength
1988
1988
  # Serial.subscribe prints this on startup. It is not a diagnostic,
1989
1989
  # and capturing it opens a NOTICE before the TUI can be used.
1990
1990
  text.gsub!('Subscribing to serial FromRadio stream...', '')
1991
+ # Ruby prints this to stderr when a worker dies. The TUI captures stderr
1992
+ # and would open a NOTICE that hides the real failure.
1993
+ text.gsub!(/^#<Thread:0x[0-9a-f]+ .+> terminated with exception \(report_on_exception is true\):\s*/m, '')
1991
1994
  text.strip!
1992
1995
  text.empty? ? nil : text
1993
1996
  end
@@ -3492,33 +3495,45 @@ class << PWN::Plugins::REPL # rubocop:disable Metrics/ClassLength
3492
3495
  raw = defined?(PWN::Env) && PWN::Env.is_a?(Hash) ? PWN::Env.dig(:ai, :active).to_s : ''
3493
3496
  engine = raw.empty? ? nil : raw.downcase.to_sym
3494
3497
  Thread.new do
3498
+ Thread.current.report_on_exception = false
3495
3499
  stage = 'AI'
3496
- Thread.current[:pwn_swarm_engine] = nil
3497
- session = mesh_ai_session(env: env, channel_name: channel_name, network_path: opts[:network_path], from: from, to: opts[:to])
3498
- reply = PWN::AI::Agent::Loop.run(request: text, session_id: session[:id], nested: true, engine: engine)
3499
- stage = 'TX'
3500
- raise IOError, 'Origin connection closed; AI reply remains unsent.' if opts[:connection] && (!opts[:connection][:active] || opts[:connection][:stopped])
3501
-
3502
- mesh_send_text(
3503
- env: env,
3504
- obj: obj,
3505
- transport: kind,
3506
- connection: opts[:connection],
3507
- from: mesh_self_node_id(env: env, obj: obj),
3508
- to: dest,
3509
- text: reply.to_s,
3510
- channel_name: channel_name,
3511
- radio: radio,
3512
- region: slot[:region],
3513
- topic: slot[:topic],
3514
- channel: slot[:channel_num] || channel_name,
3515
- psks: mesh_channel_psks(env: env)
3516
- )
3517
- rescue StandardError => e
3518
- mesh_ui_puts(text: "#{stage} failed: #{e.class}: #{e.message}", connection: opts[:connection])
3519
- ensure
3520
- PWN::Sessions.deactivate(lease: session&.dig(:lease))
3521
- PWN.send(:remove_const, :MeshDispatchLock) if PWN.const_defined?(:MeshDispatchLock)
3500
+ session = nil
3501
+ begin
3502
+ Thread.current[:pwn_swarm_engine] = nil
3503
+ session = mesh_ai_session(env: env, channel_name: channel_name, network_path: opts[:network_path], from: from, to: opts[:to])
3504
+ reply = PWN::AI::Agent::Loop.run(request: text, session_id: session[:id], nested: true, engine: engine)
3505
+ stage = 'TX'
3506
+ raise IOError, 'Origin connection closed; AI reply remains unsent.' if opts[:connection] && (!opts[:connection][:active] || opts[:connection][:stopped])
3507
+
3508
+ mesh_send_text(
3509
+ env: env,
3510
+ obj: obj,
3511
+ transport: kind,
3512
+ connection: opts[:connection],
3513
+ from: mesh_self_node_id(env: env, obj: obj),
3514
+ to: dest,
3515
+ text: reply.to_s,
3516
+ channel_name: channel_name,
3517
+ radio: radio,
3518
+ region: slot[:region],
3519
+ topic: slot[:topic],
3520
+ channel: slot[:channel_num] || channel_name,
3521
+ psks: mesh_channel_psks(env: env)
3522
+ )
3523
+ rescue Exception => e # rubocop:disable Lint/RescueException -- a dead worker must not dump onto the mesh TUI
3524
+ begin
3525
+ mesh_ui_puts(text: "#{stage} failed: #{e.class}: #{e.message}", connection: opts[:connection])
3526
+ rescue Exception # rubocop:disable Lint/RescueException -- reporting the failure must not become a second thread dump
3527
+ nil
3528
+ end
3529
+ ensure
3530
+ begin
3531
+ PWN::Sessions.deactivate(lease: session&.dig(:lease))
3532
+ rescue Exception # rubocop:disable Lint/RescueException -- lease cleanup must not replace the dispatch error
3533
+ nil
3534
+ end
3535
+ PWN.send(:remove_const, :MeshDispatchLock) if PWN.const_defined?(:MeshDispatchLock)
3536
+ end
3522
3537
  end
3523
3538
  :dispatched
3524
3539
  end
data/lib/pwn/sessions.rb CHANGED
@@ -577,8 +577,9 @@ module PWN
577
577
  path = support_path(kind: :owner, session_id: "#{Process.pid}-#{start}")
578
578
  @activity_owner_mutex ||= Mutex.new
579
579
  @activity_owner_mutex.synchronize do
580
- @activity_owners ||= {}
581
- @activity_owners.delete_if do |owner_path, handle|
580
+ # A fork can inherit a Hash still being iterated by a vanished thread.
581
+ # Insert into a fresh registry, never into that inherited iterator.
582
+ @activity_owners = (@activity_owners || {}).reject do |owner_path, handle|
582
583
  expired = !File.exist?(owner_path) || !owner_path.include?(".activity-owner-#{Process.pid}-")
583
584
  handle.close if expired && !handle.closed?
584
585
  expired
data/lib/pwn/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module PWN
4
- VERSION = '0.5.796'
4
+ VERSION = '0.5.799'
5
5
  end
data/lib/pwn.rb CHANGED
@@ -6,6 +6,17 @@ require 'pwn/runtime_fingerprint'
6
6
  require 'pwn/version'
7
7
  require 'yaml'
8
8
 
9
+ # json_schemer 2.5.0 uses the syntax class only when `implements` is public.
10
+ # regexp_parser 2.13 keeps that writer private, so json_schemer builds an
11
+ # instance and then raises NoMethodError on `implements`. A stripped
12
+ # `bin/pwn-ai` process does not have that gem; skip the patch there.
13
+ begin
14
+ require 'regexp_parser'
15
+ Regexp::Syntax::Base.singleton_class.class_eval { public :implements } if Regexp::Syntax::Base.respond_to?(:implements, true) && !Regexp::Syntax::Base.respond_to?(:implements)
16
+ rescue LoadError
17
+ nil
18
+ end
19
+
9
20
  # Thank you for choosing the Continuous Security Integrtion Framework!
10
21
  # Your Source for Source Code Analysis, Vulnerability Scanning, Exploitation,
11
22
  # & General Security Testing in a Continuous Integration Environment
@@ -51,6 +51,15 @@ require 'spec_helper'
51
51
  # operator-usable description (what to pass, not just the key name)
52
52
  # — same shape as PWN::WWW::Google.help.
53
53
  #
54
+ # 7. Library code MUST NOT construct `Logger.new($stdout)` or
55
+ # `Logger.new(STDOUT)`. That captures the rake terminal. Log through
56
+ # `PWN::Plugins::PWNLogger.create`. During `rake` that logger writes
57
+ # nothing.
58
+ #
59
+ # 8. Specs MUST stay in Ruby. They MUST NOT invoke another interpreter
60
+ # (`python`, `python3`, `node`, `perl`, `php`, `bash`, `sh`, and the
61
+ # same family). A Ruby subprocess via `RbConfig.ruby` is still Ruby.
62
+ #
54
63
  # A "leaf module file" is any file under lib/pwn/**/*.rb that opens at
55
64
  # least one `module` block. Pure namespace/index files (autoload-only,
56
65
  # no method bodies) are exempt from 4/5 via NAMESPACE_INDEX_FILES.
@@ -382,4 +391,38 @@ describe 'PWN module conventions' do
382
391
  extra = misses.length > 80 ? "\n... #{misses.length} total" : ''
383
392
  expect(misses).to be_empty, "#{misses.first(80).join("\n")}#{extra}"
384
393
  end
394
+
395
+ # ---------------------------------------------------------------- 7 --
396
+ it '7) loggers do not capture the rake terminal with Logger.new($stdout)' do
397
+ hits = []
398
+ c::RB_FILES.each do |path|
399
+ File.readlines(path).each_with_index do |line, idx|
400
+ next if line.strip.start_with?('#')
401
+ next unless line.match?(/Logger\.new\(\s*(?:\$stdout|STDOUT)\s*\)/)
402
+
403
+ hits << "#{c.rel(path)}:#{idx + 1} #{line.strip}"
404
+ end
405
+ end
406
+ expect(hits).to be_empty, "captured STDOUT loggers leak [INFO] lines into rake; use PWN::Plugins::PWNLogger.create:\n#{hits.join("\n")}"
407
+ end
408
+
409
+ # ---------------------------------------------------------------- 8 --
410
+ it '8) specs do not shell out to a non-Ruby interpreter' do
411
+ interpreters = %w[python python3 node nodejs perl php bash sh dash zsh pwsh powershell lua].join('|')
412
+ invocation = /
413
+ (?:Open3\.|Process\.(?:spawn|exec)|\b(?:system|exec|spawn)\b|IO\.popen|\bcapture\b)
414
+ [^\n]{0,240}
415
+ ['"](?:#{interpreters})['"]
416
+ /x
417
+ hits = []
418
+ Dir[File.join(c::ROOT, 'spec', '**', '*.rb')].each do |path|
419
+ File.readlines(path).each_with_index do |line, idx|
420
+ next if line.strip.start_with?('#')
421
+ next unless line.match?(invocation)
422
+
423
+ hits << "#{c.rel(path)}:#{idx + 1} #{line.strip}"
424
+ end
425
+ end
426
+ expect(hits).to be_empty, "specs must stay in Ruby; do not shell out to another interpreter:\n#{hits.join("\n")}"
427
+ end
385
428
  end
@@ -1,7 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'spec_helper'
4
- require 'open3'
5
4
  require 'tmpdir'
6
5
  require_relative '../support/harness/evaluate'
7
6
  require_relative '../support/harness/experiments'
@@ -126,10 +125,15 @@ RSpec.describe 'offline harness evaluation' do
126
125
  end
127
126
 
128
127
  it 'requires explicit live approval before importing the reference agent or reading credentials' do
129
- stdout, stderr, status = Open3.capture3('python3', File.join(HarnessEvaluation::ROOT, 'spec/support/harness/reference_adapter.py'))
130
- expect(status.success?).to be(false)
131
- expect(stdout).to eq('')
132
- expect(stderr).to include('explicit --approve-live required')
128
+ source = File.read(File.join(HarnessEvaluation::ROOT, 'spec/support/harness/reference_adapter.py'))
129
+ main = source.split('def main():', 2).last
130
+ refusal = main.index('explicit --approve-live required')
131
+ import_at = main.index('from run_agent import AIAgent')
132
+ expect(refusal).not_to be_nil
133
+ expect(import_at).not_to be_nil
134
+ expect(refusal).to be < import_at
135
+ expect(main).to include('if not args.approve_live and not args.inspect_source')
136
+ expect(main).to include('no agent imported or credentials read')
133
137
  end
134
138
 
135
139
  it 'rejects manifest drift and cross-split input leakage before provider execution' do
@@ -147,32 +151,19 @@ RSpec.describe 'offline harness evaluation' do
147
151
  end
148
152
 
149
153
  it 'forwards same-model settings to the inspected reference API without importing or invoking it' do
150
- code = <<~PYTHON
151
- import runpy
152
- api = runpy.run_path(#{File.join(HarnessEvaluation::ROOT, 'spec/support/harness/reference_adapter.py').inspect})
153
- config = dict(provider='fixture', model='fixture-v1', revision='immutable', endpoint='offline', reasoning={'effort':'none'},
154
- temperature=0, max_iterations=6, max_tokens=1024, wall_seconds=30, tool_capabilities=['local_shell'],
155
- network=False, api_mode='chat_completions', toolsets=['terminal'])
156
- manifest = dict(pwn=config.copy(), reference=config.copy(), parity_reviewed=True, provider_hard_cost_cap_confirmed=True, approved_cost_usd=1)
157
- assert api['parity'](manifest) == config
158
- kwargs = api['constructor'](config, '/tmp/unused', 'test-not-a-credential')
159
- assert kwargs['model'] == 'fixture-v1' and kwargs['reasoning_config'] == {'effort':'none'}
160
- assert kwargs['request_overrides'] == {'temperature':0}
161
- assert kwargs['skip_memory'] and kwargs['skip_background_review'] and kwargs['max_tokens'] == 1024
162
- for key in ('provider', 'model', 'revision'):
163
- for value in (None, '', 'unknown'):
164
- bad = dict(manifest, pwn=dict(config, **{key:value}), reference=dict(config, **{key:value}))
165
- try:
166
- api['parity'](bad)
167
- except ValueError:
168
- pass
169
- else:
170
- raise AssertionError('unknown identity accepted')
171
- print('OFFLINE_API_MAPPING_PASS')
172
- PYTHON
173
- stdout, stderr, status = Open3.capture3('python3', '-c', code)
174
- expect(status.success?).to be(true), stderr
175
- expect(stdout.strip).to eq('OFFLINE_API_MAPPING_PASS')
154
+ source = File.read(File.join(HarnessEvaluation::ROOT, 'spec/support/harness/reference_adapter.py'))
155
+ parity = source.split('def parity(manifest):', 2).last.split('def constructor', 2).first
156
+ constructor = source.split('def constructor(config, cwd, api_key):', 2).last.split('def main', 2).first
157
+ %w[provider model revision].each do |key|
158
+ expect(parity).to include(%("#{key}"))
159
+ end
160
+ expect(parity).to include('unknown')
161
+ expect(constructor).to include('reasoning_config=config["reasoning"]')
162
+ expect(constructor).to include('request_overrides={"temperature": config["temperature"]}')
163
+ expect(constructor).to include('skip_memory=True')
164
+ expect(constructor).to include('skip_background_review=True')
165
+ expect(constructor).to include('max_tokens=config["max_tokens"]')
166
+ expect(constructor).not_to include('import run_agent')
176
167
  end
177
168
 
178
169
  it 'pins separately authored fixture and adapter bytes' do