ace-lab 0.13.1 → 0.14.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.
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+ require "fileutils"
5
+ require "pathname"
6
+
7
+ module Ace
8
+ module Lab
9
+ module Molecules
10
+ # Shared extension-projection primitives (task 8xs.t.pu0.0): the
11
+ # ONE place that knows how the installed gem's handbook/extensions
12
+ # tree is located, enumerated, and projected safely — used by both
13
+ # ExtensionProvisioner (convergence) and Verify (readiness), so
14
+ # the two can never drift.
15
+ module ExtensionProjection
16
+ RECEIPT_NAME = ".ace-lab-extension-projection.json"
17
+
18
+ module_function
19
+
20
+ # The installed gem's own tree at the EXACT declared version.
21
+ # @return [String, nil] the handbook/extensions directory or nil
22
+ # when the gem (or its extensions tree) is not installed
23
+ def gem_source_root(gem_home, name, version)
24
+ candidate = File.join(gem_home, "gems", "#{name}-#{version}")
25
+ extensions = File.join(candidate, "handbook", "extensions")
26
+ File.directory?(extensions) ? extensions : nil
27
+ end
28
+
29
+ # Relative path → absolute source file for every file under the
30
+ # gem's handbook/extensions tree (e.g. "ace-wake/index.js").
31
+ # @return [Hash<String, String>]
32
+ def source_files(source_root)
33
+ Dir.glob(File.join(source_root, "**", "*")).select { |path| File.file?(path) }
34
+ .to_h { |path| [path.delete_prefix("#{source_root}/"), path] }
35
+ end
36
+
37
+ # Resolve and fully validate a projection destination before
38
+ # anything is written or verified (the provider_syncer
39
+ # validate_projection_destination posture): every path
40
+ # component under the projection directory must be a directory
41
+ # or creatable — a symlinked component could redirect the
42
+ # write outside the extensions directory, so it is refused.
43
+ # @param output_dir [String] manifest-declared extension dir
44
+ # @param relative_path [String] receipt-relative file path
45
+ # @return [String] the validated absolute destination
46
+ # @raise [Ace::Lab::Error] invalid or escaping destination
47
+ def validate_destination!(output_dir, relative_path)
48
+ segments = relative_path.to_s.split(File::SEPARATOR)
49
+ if segments.empty? || segments.any? { |segment| segment.empty? || segment == "." || segment == ".." }
50
+ raise Ace::Lab::Error, "cannot project #{relative_path.inspect}: invalid destination path"
51
+ end
52
+
53
+ begin
54
+ current = Pathname.new(File.realpath(output_dir))
55
+ rescue Errno::ENOENT
56
+ # the projection directory itself does not exist yet — no
57
+ # component below it can escape
58
+ return File.join(output_dir, *segments)
59
+ end
60
+ segments.each_with_index do |segment, index|
61
+ current = current.join(segment)
62
+ if File.symlink?(current.to_s)
63
+ raise Ace::Lab::Error,
64
+ "cannot project #{relative_path} into #{output_dir}: a symlinked path component " \
65
+ "would escape the projection directory"
66
+ end
67
+ # The FINAL segment is the file itself — only intermediate
68
+ # components must be directories (compare by position, not
69
+ # value: "a/a/index.js" repeats "a" legitimately).
70
+ next if index == segments.size - 1
71
+
72
+ if !current.directory? && File.exist?(current.to_s)
73
+ raise Ace::Lab::Error,
74
+ "cannot project #{relative_path} into #{output_dir}: #{current} exists and is not a directory"
75
+ end
76
+ end
77
+ if File.directory?(current.to_s)
78
+ # Receipt ownership of a path never authorizes writing
79
+ # through a directory planted at that path — cp would
80
+ # reinterpret the destination as a container.
81
+ raise Ace::Lab::Error,
82
+ "cannot project #{relative_path} into #{output_dir}: #{current} exists and is a directory"
83
+ end
84
+ current.to_s
85
+ rescue Errno::ENOENT
86
+ raise Ace::Lab::Error, "cannot project #{relative_path} into #{output_dir}: projection directory vanished"
87
+ end
88
+ end
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,226 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+ require_relative "extension_projection"
5
+ require "etc"
6
+ require "fileutils"
7
+ require "json"
8
+
9
+ module Ace
10
+ module Lab
11
+ module Molecules
12
+ # Projects harness extension assets from an INSTALLED gem's exact
13
+ # declared version into the manifest-declared extension directory
14
+ # (task 8xs.t.pu0.0): the manual host-lane copy of the ace-wake
15
+ # extension is replaced by a converged, repeatable projection.
16
+ #
17
+ # Source of truth is the installed gem tree itself —
18
+ # `<gem_home>/gems/<name>-<version>/handbook/extensions` — so the
19
+ # projection always matches the exact version the manifest
20
+ # declared (never the checkout, never a newer gem beside it).
21
+ # Each target directory carries a receipt
22
+ # (`.ace-lab-extension-projection.json`) recording the producing
23
+ # gem, version and file list; ONLY receipt-listed files are ever
24
+ # removed, so user-authored extensions in the same directory are
25
+ # never touched. The report names the version that WAS loaded
26
+ # before this run (`loaded_version`) and whether the projection
27
+ # changed (`restart_required`) — a changed projection means the
28
+ # running harness processes still hold the OLD extension; the
29
+ # installer REPORTS the restart need, it never restarts an
30
+ # executor on its own.
31
+ class ExtensionProvisioner
32
+ RECEIPT_NAME = ExtensionProjection::RECEIPT_NAME
33
+ FILE_MODE = 0o644
34
+ DIR_MODE = 0o755
35
+
36
+ # @param gem_home [String] target runtime the gems were
37
+ # converged into
38
+ # @param dry_run [Boolean] predict without writing
39
+ # @param account_lookup [Proc, nil] passwd lookup seam for the
40
+ # declared accounts (projection ownership convergence)
41
+ def initialize(gem_home:, dry_run: false, account_lookup: nil)
42
+ @gem_home = gem_home
43
+ @dry_run = dry_run
44
+ @account_lookup = account_lookup || method(:lookup_passwd)
45
+ end
46
+
47
+ # @param extensions [Array<Hash>] normalized manifest gemset
48
+ # extensions entries ({"gem" =>, "path" =>, "account" =>})
49
+ # @param gems [Array<Hash>] declared gem set (name/version)
50
+ # @return [Array<Hash>] one report per entry:
51
+ # {extension:, gem:, version:, path:, account:, status:,
52
+ # loaded_version:, restart_required:, files:, message:}
53
+ def call(extensions:, gems:)
54
+ extensions.map do |entry|
55
+ converge(entry, gems)
56
+ end
57
+ end
58
+
59
+ private
60
+
61
+ def converge(entry, gems)
62
+ declared = gems.find { |gem| gem["name"] == entry["gem"] }
63
+ version = declared && declared["version"]
64
+ source = version && ExtensionProjection.gem_source_root(@gem_home, entry["gem"], version)
65
+
66
+ if source.nil?
67
+ # Fresh-lab dry run (the gem phase predicts would_install
68
+ # for the same missing gem): predict the projection the
69
+ # converged gem would feed instead of reporting a failure
70
+ # the wet run would not produce.
71
+ if @dry_run
72
+ return entry_report(entry, version, "would_project", nil, true, [])
73
+ end
74
+ return failed(entry, version,
75
+ "gem '#{entry["gem"]}' is not installed in runtime '#{@gem_home}' at declared " \
76
+ "version '#{version}'; converge the gemset first (ace-lab install)")
77
+ end
78
+
79
+ expected = ExtensionProjection.source_files(source)
80
+ if expected.empty?
81
+ return failed(entry, version,
82
+ "gem '#{entry["gem"]}' #{version} carries no handbook/extensions tree")
83
+ end
84
+
85
+ output_dir = entry["path"]
86
+ escape = projection_escape_reason(output_dir, expected.keys)
87
+ return failed(entry, version, escape) if escape
88
+
89
+ receipt = read_receipt(output_dir)
90
+ loaded_version = receipt && receipt["gem"] == entry["gem"] ? receipt["version"] : nil
91
+
92
+ changed = projection_changed?(output_dir, expected, receipt, version)
93
+ if !changed
94
+ converge_modes(output_dir, expected, entry)
95
+ return entry_report(entry, version, "unchanged", loaded_version, false,
96
+ receipt ? receipt.fetch("files") : expected.keys)
97
+ end
98
+ # dry-run predicts the projection (restart needed) without
99
+ # writing anything
100
+ return entry_report(entry, version, "projected", loaded_version, true, expected.keys) if @dry_run
101
+
102
+ project(output_dir, expected, entry, version)
103
+ entry_report(entry, version, "projected", loaded_version, true, expected.keys)
104
+ rescue SystemCallError => e
105
+ failed(entry, version,
106
+ "extension projection into '#{output_dir}' failed (#{e.class.name}); " \
107
+ "rerun ace-lab prepare with sudo or adjust ownership manually")
108
+ end
109
+
110
+ def failed(entry, version, message)
111
+ entry_report(entry, version, "failed", nil, false, [])
112
+ .merge("message" => message)
113
+ end
114
+
115
+ def entry_report(entry, version, status, loaded_version, restart_required, files)
116
+ {"extension" => entry["gem"], "gem" => entry["gem"], "version" => version,
117
+ "path" => entry["path"], "account" => entry["account"], "status" => status,
118
+ "loaded_version" => loaded_version, "restart_required" => restart_required,
119
+ "files" => files, "message" => nil}
120
+ end
121
+
122
+ # Refuse a destination that escapes the projection directory
123
+ # through a symlinked component BEFORE anything is written (the
124
+ # provider_syncer validate_projection_destination posture).
125
+ def projection_escape_reason(output_dir, relative_paths)
126
+ relative_paths.each { |relative| ExtensionProjection.validate_destination!(output_dir, relative) }
127
+ nil
128
+ rescue Ace::Lab::Error => e
129
+ e.message
130
+ end
131
+
132
+ # A projection changed when the receipt is absent, names a
133
+ # different version, lists a different file set, or any
134
+ # expected file's content differs on disk.
135
+ def projection_changed?(output_dir, expected, receipt, version)
136
+ return true if receipt.nil?
137
+ return true if receipt["version"] != version
138
+ return true unless receipt.fetch("files", []).sort == expected.keys.sort
139
+
140
+ expected.any? do |relative, source|
141
+ target = File.join(output_dir, relative)
142
+ !File.file?(target) || !FileUtils.compare_file(source, target)
143
+ end
144
+ end
145
+
146
+ def project(output_dir, expected, entry, version)
147
+ FileUtils.mkdir_p(output_dir)
148
+ expected.each do |relative, source|
149
+ target = File.join(output_dir, relative)
150
+ FileUtils.mkdir_p(File.dirname(target))
151
+ FileUtils.cp(source, target)
152
+ end
153
+
154
+ # Only receipt-owned files no longer in the projection are
155
+ # removed; a removal that fails keeps its receipt entry so a
156
+ # later run retries it (user-authored extensions are never
157
+ # touched).
158
+ previous = read_receipt(output_dir)&.fetch("files", []) || []
159
+ retained = previous.filter_map do |relative|
160
+ target = File.join(output_dir, relative)
161
+ next relative if expected.key?(relative)
162
+
163
+ FileUtils.rm_f(target)
164
+ File.exist?(target) ? relative : nil
165
+ end
166
+
167
+ write_receipt(output_dir, entry, version, (expected.keys + retained).sort)
168
+ converge_modes(output_dir, expected, entry)
169
+ end
170
+
171
+ # Mode/ownership convergence (the key-provisioner posture):
172
+ # projected files carry owner read/write plus world read
173
+ # (0644), projection directories 0755, and both are owned by
174
+ # the declared account whenever the passwd lookup resolves it —
175
+ # so the target executor can always read its extensions.
176
+ def converge_modes(output_dir, expected, entry)
177
+ account = @account_lookup.call(entry["account"])
178
+ targets = expected.keys.map { |relative| File.join(output_dir, relative) }
179
+ targets << File.join(output_dir, RECEIPT_NAME)
180
+ targets.each do |target|
181
+ next unless File.file?(target)
182
+
183
+ FileUtils.chmod(FILE_MODE, target)
184
+ FileUtils.chown(account.uid, account.gid, target) if account
185
+ end
186
+ root = File.realpath(output_dir)
187
+ dirs = expected.keys.filter_map do |relative|
188
+ File.dirname(File.join(root, relative)) if relative.include?(File::SEPARATOR)
189
+ end.uniq
190
+ until dirs.empty?
191
+ dir = dirs.pop
192
+ FileUtils.chmod(DIR_MODE, dir)
193
+ FileUtils.chown(account.uid, account.gid, dir) if account
194
+ parent = File.dirname(dir)
195
+ dirs << parent if dir != root && parent.start_with?("#{root}/") && !dirs.include?(parent) && parent != root
196
+ end
197
+ end
198
+
199
+ def write_receipt(output_dir, entry, version, files)
200
+ document = {
201
+ "gem" => entry["gem"], "version" => version,
202
+ "projected_at" => Time.now.utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
203
+ "files" => files.sort
204
+ }
205
+ File.write(File.join(output_dir, RECEIPT_NAME), JSON.pretty_generate(document))
206
+ end
207
+
208
+ def read_receipt(output_dir)
209
+ path = File.join(output_dir, RECEIPT_NAME)
210
+ return nil unless File.file?(path)
211
+
212
+ document = JSON.parse(File.read(path))
213
+ document.is_a?(Hash) ? document : nil
214
+ rescue JSON::ParserError, Errno::EACCES
215
+ nil
216
+ end
217
+
218
+ def lookup_passwd(username)
219
+ Etc.getpwnam(username)
220
+ rescue ArgumentError
221
+ nil
222
+ end
223
+ end
224
+ end
225
+ end
226
+ end
@@ -0,0 +1,174 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "open3"
5
+ require "rbconfig"
6
+ require "find"
7
+
8
+ module Ace
9
+ module Lab
10
+ module Molecules
11
+ # Installed specifications select identity; cached gem archives own payload
12
+ # membership (installed gemspecs omit files). No recursive runtime sweep.
13
+ class GemPayloadPermissions
14
+ class Error < StandardError; end
15
+ INVENTORY = <<~'CODE'
16
+ require 'json'
17
+ require 'rubygems'
18
+ require 'rubygems/package'
19
+ home = ARGV.shift
20
+ Gem.use_paths(home)
21
+ queue = [Gem::Specification.find_by_name(ARGV.shift, ARGV.shift)]
22
+ dry_run = ARGV.shift == "dry-run"
23
+ seen = {}; rows = []
24
+ until queue.empty?
25
+ spec = queue.shift
26
+ next if seen[spec.full_name]
27
+ seen[spec.full_name] = true
28
+ unless spec.default_gem?
29
+ cache = File.join(home, "cache", "#{spec.full_name}.gem")
30
+ unless File.file?(cache) && !File.symlink?(cache) && !File.symlink?(File.dirname(cache))
31
+ puts JSON.generate(error: "installed gem payload cache missing or symlinked: #{cache}")
32
+ exit 1
33
+ end
34
+ package = Gem::Package.new(cache)
35
+ package.verify
36
+ unless package.spec.full_name == spec.full_name
37
+ puts JSON.generate(error: "installed gem payload cache identity mismatch: #{cache}")
38
+ exit 1
39
+ end
40
+ rows << {root: spec.full_gem_path, spec: spec.loaded_from,
41
+ files: package.contents, executables: spec.executables,
42
+ bindir: spec.bindir, extension: spec.extensions.empty? ? nil : spec.extension_dir}
43
+ end
44
+ spec.runtime_dependencies.each do |dep|
45
+ begin
46
+ queue << dep.to_spec
47
+ rescue Gem::MissingSpecError
48
+ # Convergence already predicts installing absent dependencies.
49
+ # Validate the existing payload; do not invent future files.
50
+ raise unless dry_run
51
+ end
52
+ end
53
+ end
54
+ puts JSON.generate(rows)
55
+ CODE
56
+
57
+ def initialize(gem_home:, dry_run:, privileged:)
58
+ @declared_home = File.expand_path(gem_home)
59
+ raise Error, "gem runtime is a symlink" if File.symlink?(@declared_home)
60
+ @home = File.realpath(@declared_home)
61
+ @dry_run, @privileged = dry_run, privileged
62
+ end
63
+
64
+ def call(name:, version:)
65
+ # Default Ruby gems need no mutation in this runtime. With no local
66
+ # specifications there cannot be any owned installed payload here.
67
+ return [] unless File.directory?(File.join(@home, "specifications"))
68
+
69
+ env = ENV.keys.grep(/\ABUNDLE/).to_h { |key| [key, nil] }
70
+ env.merge!("RUBYOPT" => nil, "RUBYLIB" => nil, "GEM_HOME" => @home, "GEM_PATH" => @home)
71
+ out, _err, status = Open3.capture3(env, RbConfig.ruby, "-e", INVENTORY, @home, name, version, @dry_run ? "dry-run" : "apply")
72
+ unless status.success?
73
+ detail = begin
74
+ JSON.parse(out)["error"]
75
+ rescue JSON::ParserError
76
+ nil
77
+ end
78
+ raise Error, detail || "could not inventory installed gem payload #{name} #{version}"
79
+ end
80
+
81
+ converge(JSON.parse(out))
82
+ rescue SystemCallError, JSON::ParserError => e
83
+ raise Error, "gem payload permission convergence failed (#{e.class})"
84
+ end
85
+
86
+ def converge(rows)
87
+ paths = {}
88
+ executables = []
89
+ rows.each do |row|
90
+ root = validate(row.fetch("root"))
91
+ raise Error, "invalid installed gem root" unless File.dirname(root) == File.join(@home, "gems")
92
+ spec = validate(row.fetch("spec"))
93
+ raise Error, "invalid installed gem specification" unless File.dirname(spec) == File.join(@home, "specifications")
94
+ add(paths, spec)
95
+ row.fetch("files").each { |file| add(paths, payload_path(root, file)) }
96
+ row.fetch("executables").each do |exe|
97
+ raise Error, "invalid gem executable" unless File.basename(exe) == exe && !%w[. ..].include?(exe)
98
+ [payload_path(root, File.join(row.fetch("bindir"), exe)), File.join(@home, "bin", exe)].each do |path|
99
+ add(paths, path)
100
+ executables << validate(path)
101
+ end
102
+ end
103
+ if (extension = row["extension"])
104
+ extension = validate(extension)
105
+ raise Error, "invalid gem extension directory" unless
106
+ extension.start_with?(File.join(@home, "extensions") + "/") &&
107
+ File.basename(extension) == File.basename(root)
108
+ Find.find(extension) do |path|
109
+ validate(path)
110
+ add(paths, path)
111
+ end
112
+ end
113
+ end
114
+ changes = paths.filter_map do |path, stat|
115
+ desired = stat.directory? || executables.include?(path) || (stat.mode & 0o111).positive? ? 0o755 : 0o644
116
+ owner_change = @privileged && (stat.uid != 0 || stat.gid != 0)
117
+ next if (stat.mode & 0o7777) == desired && !owner_change
118
+ {"path" => path, "mode" => desired, "owner_change" => owner_change,
119
+ "status" => @dry_run ? "would_normalize" : "normalized"}
120
+ end
121
+ # Inventory validation is complete before the first mutation.
122
+ unless @dry_run
123
+ changes.each do |change|
124
+ path = validate(change.fetch("path"))
125
+ current = File.lstat(path)
126
+ original = paths.fetch(path)
127
+ raise Error, "gem payload changed during permission convergence: #{path}" unless
128
+ current.ino == original.ino && current.dev == original.dev && !current.symlink?
129
+ File.chown(0, 0, path) if change["owner_change"]
130
+ File.chmod(change.fetch("mode"), path)
131
+ end
132
+ end
133
+ changes
134
+ end
135
+
136
+ private
137
+
138
+ def payload_path(root, relative)
139
+ path = File.expand_path(relative, root)
140
+ raise Error, "gem payload escapes specification root" unless path.start_with?(root + "/")
141
+ path
142
+ end
143
+
144
+ def validate(path)
145
+ path = File.expand_path(path)
146
+ if path == @declared_home || path.start_with?(@declared_home + "/")
147
+ path = @home + path.delete_prefix(@declared_home)
148
+ end
149
+ raise Error, "gem payload escapes declared runtime: #{path}" unless path == @home || path.start_with?(@home + "/")
150
+ cursor = path
151
+ loop do
152
+ stat = File.lstat(cursor)
153
+ raise Error, "gem payload symlink refused: #{cursor}" if stat.symlink?
154
+ raise Error, "unsupported gem payload: #{cursor}" unless stat.file? || stat.directory?
155
+ break if cursor == @home
156
+ cursor = File.dirname(cursor)
157
+ end
158
+ path
159
+ end
160
+
161
+ def add(paths, path)
162
+ path = validate(path)
163
+ loop do
164
+ stat = File.lstat(path)
165
+ raise Error, "hardlinked gem payload refused: #{path}" if stat.file? && stat.nlink > 1
166
+ paths[path] = stat
167
+ break if path == @home
168
+ path = File.dirname(path)
169
+ end
170
+ end
171
+ end
172
+ end
173
+ end
174
+ end