Module: PWN::Backups
- Defined in:
- lib/pwn/backups.rb
Overview
All first-party recovery copies share one serialized seven-generation store. Evidence artifacts are not recovery copies and must not enter this store.
Constant Summary collapse
- LIMIT =
7- GENERATION =
/\A\d{8}_\d{6}_[a-f0-9]{8}\z/- LEGACY_SNAPSHOT =
Published Migrate.backup! names from before .generation.json. Not an unknown folder.
/\A\d{8}_\d{6}\z/- PARTIAL_SNAPSHOT =
Unpublished housekeeping-era copy. Rename was the publish step, so this is not a restore name.
/\A\.partial-\d{8}_\d{6}(?:_[a-f0-9]{8})?\z/
Class Method Summary collapse
-
.active? ⇒ Boolean
- Supported Method Parameters
PWN::Backups.active?.
-
.authors ⇒ Object
- Author(s)
0day Inc.
-
.capture(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::Backups.capture(path: '/path/to/source', label: 'learning').
-
.configure(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::Backups.configure(root: nil).
-
.directory(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::Backups.directory(label: 'maintenance') Caller must hold transaction through the final source mutation and ledger.
-
.help ⇒ Object
Display Usage for this Module.
-
.reconcile(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::Backups.reconcile(generation: 'name', expected_sha256: 'digest', confirmed: true).
-
.relocate_legacy(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::Backups.relocate_legacy(paths: [], dry_run: true, writers_stopped: false).
-
.transaction(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::Backups.transaction(root: nil) { ... }.
Class Method Details
.active? ⇒ Boolean
- Supported Method Parameters
PWN::Backups.active?
22 23 24 25 |
# File 'lib/pwn/backups.rb', line 22 public_class_method def self.active? owner = Thread.current[:pwn_backup_transaction] !owner.nil? && owner[:pid] == Process.pid && owner[:thread] == Thread.current end |
.authors ⇒ Object
- Author(s)
0day Inc. [email protected]
396 397 398 |
# File 'lib/pwn/backups.rb', line 396 public_class_method def self. "AUTHOR(S):\n 0day Inc. <[email protected]>\n" end |
.capture(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::Backups.capture(path: '/path/to/source', label: 'learning')
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 |
# File 'lib/pwn/backups.rb', line 94 public_class_method def self.capture(opts = {}) source = File.(opts[:path]) label = opts[:label] || 'snapshot' transaction do Thread.current[:pwn_backup_transaction][:pinned] = true if opts[:pin] raise IOError, 'Unsafe backup source' unless File.file?(source) && File.realpath(source) == source && File.stat(source).uid == Process.uid directory = self.directory(label: label) target = File.join(directory, File.basename(source)) before = Digest::SHA256.file(source).hexdigest File.open(source, File::RDONLY | File::NOFOLLOW) do |input| File.open(target, File::WRONLY | File::CREAT | File::EXCL | File::NOFOLLOW, 0o600) do |output| IO.copy_stream(input, output) output.flush output.fsync end end raise IOError, 'Backup source changed or copy failed' unless Digest::SHA256.file(source).hexdigest == before && Digest::SHA256.file(target).hexdigest == before File.open(directory, File::RDONLY, &:fsync) target end end |
.configure(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::Backups.configure(root: nil)
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 |
# File 'lib/pwn/backups.rb', line 120 public_class_method def self.configure(opts = {}) root = opts[:root] || File.join(Dir.home, '.pwn', 'backup') transaction(root: root) do path = File.join(root, '.retention-policy.json') raise IOError, 'Unsafe retention policy' if File.symlink?(path) policy = File.file?(path) ? JSON.parse(File.binread(path)) : { 'version' => 1, 'pins' => [] } raise IOError, 'Invalid retention policy' unless policy['version'] == 1 && policy['pins'].is_a?(Array) updated = policy.merge('keep' => LIMIT, 'expire_history' => true, 'scope' => 'global') next updated if updated == policy temporary = "#{path}.#{SecureRandom.hex(8)}" File.open(temporary, File::WRONLY | File::CREAT | File::EXCL | File::NOFOLLOW, 0o600) do |file| file.write(JSON.generate(updated)) file.flush file.fsync end File.rename(temporary, path) File.open(root, File::RDONLY, &:fsync) updated end end |
.directory(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::Backups.directory(label: 'maintenance') Caller must hold transaction through the final source mutation and ledger.
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
# File 'lib/pwn/backups.rb', line 63 public_class_method def self.directory(opts = {}) label = opts[:label].to_s raise ArgumentError, 'Invalid backup label' unless label.match?(/\A[a-zA-Z0-9_-]+\z/) context = Thread.current[:pwn_backup_transaction] raise IOError, 'Backup transaction required' unless context && context[:pid] == Process.pid && context[:thread] == Thread.current unless context[:directory] root = context[:root] names = Dir.children(root).select { |name| File.directory?(File.join(root, name)) || File.symlink?(File.join(root, name)) }.sort pins = names.length >= LIMIT ? reference_pins(root: root) : [] raise IOError, 'Pinned backup missing' unless (pins - names).empty? candidates = names.select { |name| expirable_name?(name: name, root: root, pins: pins) } count = [names.length - LIMIT + 1, 0].max raise IOError, 'Backup capacity occupied by legacy, pinned or interrupted generations' if candidates.length < count candidates.sort_by { |name| [File.mtime(File.join(root, name)).to_r, name] }.first(count).each do |name| FileUtils.remove_entry_secure(File.join(root, name)) end context[:directory] = File.join(root, "#{Time.now.utc.strftime('%Y%m%d_%H%M%S')}_#{SecureRandom.hex(4)}") Dir.mkdir(context[:directory], 0o700) write_state(context: context, state: 'prepared') end path = File.join(context[:directory], "#{label}-#{SecureRandom.hex(8)}") Dir.mkdir(path, 0o700) path end |
.help ⇒ Object
Display Usage for this Module
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 |
# File 'lib/pwn/backups.rb', line 401 public_class_method def self.help puts " # Hold the shared lock through backup and source mutation. #{self}.transaction(root: 'optional - backup root; defaults to Thread.current[:pwn_backup_root] or ~/.pwn/backup') { ... } # Allocate a producer directory inside the current generation. #{self}.directory(label: 'required - producer label') # Copy and hash-verify an owned regular file. #{self}.capture(path: 'required - source path', label: 'optional - producer label', pin: 'optional - retain until explicitly reconciled') # Install the global seven-folder policy without expiring existing data. #{self}.configure(root: 'optional - backup root; defaults ~/.pwn/backup') # Acknowledge completed store-specific recovery; this does not restore data. #{self}.reconcile(generation: 'required - exact generation name', expected_sha256: 'required - inspected generation manifest digest', confirmed: 'required - explicit true after store recovery', pinned: 'optional - retain by default; false permits ordinary retention') # Explicitly relocate recognized unreferenced legacy recovery copies. #{self}.relocate_legacy(paths: 'required - exact legacy paths', dry_run: 'optional - preview only by default', writers_stopped: 'optional - must be true to apply') # Check whether this thread owns the backup transaction. #{self}.active? # Show module authors. #{self}.authors " end |
.reconcile(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::Backups.reconcile(generation: 'name', expected_sha256: 'digest', confirmed: true)
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
# File 'lib/pwn/backups.rb', line 146 public_class_method def self.reconcile(opts = {}) generation = opts[:generation].to_s raise ArgumentError, 'Exact generation and explicit recovery confirmation required' unless generation.match?(GENERATION) && opts[:confirmed] == true transaction do root = Thread.current[:pwn_backup_transaction][:root] directory = File.join(root, generation) raise IOError, 'Recovery generation missing' unless File.directory?(directory) safe_directory(path: directory) path = File.join(directory, '.generation.json') raise IOError, 'Recovery manifest changed' unless !File.symlink?(path) && Digest::SHA256.file(path).hexdigest == opts[:expected_sha256] record = JSON.parse(File.read(path)) raise IOError, 'Unknown recovery manifest' unless record['version'] == 1 && %w[prepared complete].include?(record['state']) write_state(context: { root: root, directory: directory, pinned: opts.fetch(:pinned, true) }, state: 'complete') { generation: generation, state: 'complete', pinned: opts.fetch(:pinned, true) } end end |
.relocate_legacy(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::Backups.relocate_legacy(paths: [], dry_run: true, writers_stopped: false)
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
# File 'lib/pwn/backups.rb', line 169 public_class_method def self.relocate_legacy(opts = {}) paths = Array(opts[:paths]).map { |path| File.(path) }.uniq dry_run = opts.fetch(:dry_run, true) raise ArgumentError, 'Stop all legacy writers before relocation' unless dry_run || opts[:writers_stopped] == true home = Dir.home root = File.join(home, '.pwn') paths.each do |path| relative = path.delete_prefix("#{root}/") recognized = relative.match?(%r{\A(?:learning\.jsonl\.bak[^/]*|preferences\.jsonl\.bak[^/]*|skills/.+/SKILL\.md\.[a-f0-9]{64}\.bak|policy\.json\.rollback-[a-f0-9]{64}\.json|learning/migrations/[a-f0-9]{64}\.backup\.jsonl|session_cleanup_archive/[^/]+|maintenance/(?:retirements|quarantine)/[^/]+)\z}) recognized ||= path == File.join(home, '.config', 'terminator', 'config.pwnbak') raise ArgumentError, 'Unrecognized legacy recovery path' unless recognized raise IOError, 'Unsafe legacy recovery path' unless File.realpath(path) == path && File.stat(path).uid == Process.uid end raise ArgumentError, 'Overlapping legacy sources' if paths.any? { |path| paths.any? { |other| path != other && path.start_with?("#{other}/") } } return { planned: paths, moved: [] } if dry_run transaction do legacy_unreferenced(paths: paths, root: root) mappings = paths.to_h do |path| target = File.join(directory(label: 'legacy'), File.basename(path)) before = legacy_inventory(path: path) FileUtils.cp_r(path, target, preserve: true) raise IOError, 'Legacy recovery changed during copy' unless before == legacy_inventory(path: path) && before == legacy_inventory(path: target) [path, { target: target, inventory: before }] end legacy_unreferenced(paths: paths, root: root) mappings.each do |path, row| raise IOError, 'Legacy recovery changed before relocation' unless row[:inventory] == legacy_inventory(path: path) end ledger = File.join(Thread.current[:pwn_backup_transaction][:directory], '.relocation.json') File.open(ledger, File::WRONLY | File::CREAT | File::EXCL | File::NOFOLLOW, 0o600) do |file| file.write(JSON.generate(version: 1, mappings: mappings)) file.flush file.fsync end mappings.each_key { |path| FileUtils.remove_entry_secure(path) } { moved: mappings.transform_values { |row| row[:target] }, ledger: ledger } end end |
.transaction(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::Backups.transaction(root: nil) { ... }
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/pwn/backups.rb', line 29 public_class_method def self.transaction(opts = {}) owner = Thread.current[:pwn_backup_transaction] override = Thread.current[:pwn_backup_root] real_home = Thread.current[:pwn_backup_real_home] override = nil if real_home && Dir.home != real_home root = File.(opts[:root] || (owner[:root] if active?) || override || File.join(Dir.home, '.pwn', 'backup')) return yield if owner && owner[:pid] == Process.pid && owner[:thread] == Thread.current && owner[:root] == root raise IOError, 'Nested backup roots are not supported' if active? learning = PWN::AI::Agent::Learning.send(:learning_lock) safe_directory(path: root) File.open(File.join(root, '.retention.lock'), File::RDWR | File::CREAT | File::NOFOLLOW, 0o600) do |lock| raise IOError, 'Unsafe backup lock' unless lock.stat.uid == Process.uid && lock.stat.nlink == 1 lock.flock(File::LOCK_EX) context = { pid: Process.pid, thread: Thread.current, root: root } Thread.current[:pwn_backup_transaction] = context begin result = yield failed = result.is_a?(Hash) && (result[:error] || result[:ok] == false || result[:promoted] == false || result[:incomplete] || %w[prepared interrupted blocked].include?(result[:state].to_s)) write_state(context: context, state: 'complete') if context[:directory] && !failed result ensure # Exceptions leave a prepared recovery generation, never silently expire it. Thread.current[:pwn_backup_transaction] = owner end end ensure PWN::AI::Agent::Learning.send(:learning_unlock, lock: learning) if learning end |