ace-lab 0.6.0 → 0.8.0

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.
@@ -64,19 +64,13 @@ module Ace
64
64
  parse_grants(content, trusted_path)
65
65
  end
66
66
 
67
- private
68
-
69
- def verify_error(path)
70
- "invalid lab configuration: trusted authorization file #{path} failed the deployment " \
71
- "ownership verification or could not be read; failing closed " \
72
- "(required: every traversed element root-owned and not group/world-writable)"
73
- end
74
-
75
- # Read the grants document only after proving the deployment owns
76
- # the storage along the original path. Genuine absence is nil
77
- # (nobody authorized); every other filesystem failure — including
78
- # races between lstat and open — classifies fail-closed
79
- # (review rounds 6-7, F2).
67
+ # Read a deployment-owned file only after proving the deployment
68
+ # owns the storage along the original path (same trust rules as
69
+ # `resolve`). Genuine absence is nil; every other filesystem
70
+ # failure — including races between lstat and open — classifies
71
+ # fail-closed (review rounds 6-7, F2). Public so other trusted
72
+ # host-installed documents (e.g. the forge merge service identity)
73
+ # read through the same verification.
80
74
  # @return [String, nil] file content, or nil when absent
81
75
  def read_verified(path)
82
76
  candidate = begin
@@ -104,6 +98,14 @@ module Ace
104
98
  end
105
99
  end
106
100
 
101
+ private
102
+
103
+ def verify_error(path)
104
+ "invalid lab configuration: trusted authorization file #{path} failed the deployment " \
105
+ "ownership verification or could not be read; failing closed " \
106
+ "(required: every traversed element root-owned and not group/world-writable)"
107
+ end
108
+
107
109
  # Walk the ORIGINAL path component by component. Symlinks are
108
110
  # followed only when the link itself is root-owned (a caller-writable
109
111
  # redirect is rejected); symlink permission bits are ignored because
@@ -0,0 +1,131 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+ require_relative "service_policy"
5
+
6
+ module Ace
7
+ module Lab
8
+ module Molecules
9
+ # The scoped ordinary-merge decision/admission resolver (spec 8x3.t.xz9.4,
10
+ # execution clauses). The deployment-owned YAML authorization file remains
11
+ # the sole source of truth; this resolver only makes the exact root
12
+ # authorizations natively executable inside the receiver: one per-request
13
+ # authorization selector resolves to a typed decision within the closed
14
+ # refusal-code family — or it refuses. Scoping rules:
15
+ #
16
+ # - only `operation: merge` decisions of the ordinary shape resolve;
17
+ # anything else (missing reference, shape mismatch, non-merge
18
+ # operation, any binding mismatch, expiry) is a typed
19
+ # `ordinary_merge_authorization_invalid` decision;
20
+ # - exact binding match on every closed key; there are NO wildcards,
21
+ # defaults, prefix grants or broad grants of any kind — a decision
22
+ # authorizes exactly one bound request and nothing else;
23
+ # - expiry bounds the decision itself.
24
+ #
25
+ # Per-request refresh (spec 8x3.t.xz9.5 integration handoff): a
26
+ # long-lived receiver would otherwise decide every sequential candidate
27
+ # against its boot-time snapshot of the authorization document. When a
28
+ # trusted path is installed, every decision re-reads the document
29
+ # through the trusted loader and resolves against the FRESH grants —
30
+ # a root-revoked or expired decision fails closed at the next request
31
+ # without any receiver restart. The refresh is scoped: it reloads and
32
+ # re-validates the exact-request grant only; it never broadens
33
+ # authorization beyond the resolved reference.
34
+ class OrdinaryAdmissionResolver
35
+ BINDING_KEYS = ServicePolicy::ORDINARY_BINDING_KEYS.freeze
36
+ DECISION_KEYS = ServicePolicy::ORDINARY_AUTHORIZATION_KEYS.freeze
37
+ OPERATION = "merge"
38
+
39
+ Decision = Struct.new(:authorized?, :decision, :code, :message, keyword_init: true)
40
+
41
+ # @param policy_document [Hash] boot-time trusted document (the
42
+ # configuration digest is derived from it once, upstream)
43
+ # @param path [String, nil] trusted policy path to re-read per decision
44
+ # @param loader [Proc, nil] trusted reader (default: GrantResolver);
45
+ # the only override point, for non-privileged test documents
46
+ def initialize(policy_document, path: nil, loader: nil, proposal_resolver: nil, caller_uid: nil)
47
+ unless policy_document.is_a?(Hash) && policy_document["authorizations"].is_a?(Hash)
48
+ raise Ace::Lab::InvalidConfigurationError,
49
+ "trusted policy document must contain an authorizations mapping"
50
+ end
51
+ @authorizations = policy_document.fetch("authorizations")
52
+ @configuration_digest = ServicePolicy.configuration_digest(policy_document)
53
+ @path = path
54
+ @proposal_resolver = proposal_resolver
55
+ @caller_uid = caller_uid
56
+ @loader = loader || ->(trusted_path) { GrantResolver.trusted_document(trusted_path) }
57
+ freeze
58
+ end
59
+
60
+ # Resolve one authorization selector against the exact ordinary merge
61
+ # request binding. Returns a typed Decision; `authorized?` is true only
62
+ # for an exact, unexpired, ordinary-merge-shaped match.
63
+ def decide(reference, binding)
64
+ authorizations = current_authorizations
65
+ unless reference.is_a?(String) && reference.match?(ServicePolicy::ID)
66
+ return refuse("invalid authorization reference")
67
+ end
68
+ unless binding.is_a?(Hash) && binding.fetch("operation", nil) == OPERATION
69
+ return refuse("only the ordinary merge operation is resolvable")
70
+ end
71
+ if reference.start_with?("proposal-")
72
+ return refuse("canonical proposal authority is unavailable") unless @proposal_resolver && @caller_uid.is_a?(Integer)
73
+ begin
74
+ decision = @proposal_resolver.call(reference, binding.slice(
75
+ "operation", "project_id", "assignment_id", "attempt_id", "input_digest", "candidate_head").merge(
76
+ "target" => {"resource" => binding.fetch("pr_url"), "artifact_digest" => nil},
77
+ "caller_uid" => @caller_uid))
78
+ return Decision.new(authorized?: true, decision: decision, code: nil, message: nil)
79
+ rescue Ace::Assign::Error
80
+ return refuse("canonical proposal does not authorize this exact ordinary merge")
81
+ end
82
+ end
83
+ decision = authorizations[reference]
84
+ return refuse("authorization reference is unresolved") unless decision.is_a?(Hash)
85
+ unless DECISION_KEYS.all? { |key| decision.key?(key) }
86
+ return refuse("authorization reference is not an ordinary merge decision")
87
+ end
88
+ unless decision.fetch("operation") == OPERATION
89
+ return refuse("authorization does not cover the ordinary merge operation")
90
+ end
91
+ mismatch = BINDING_KEYS.find { |key| decision.fetch(key) != binding.fetch(key, nil) }
92
+ return refuse("authorization does not match the exact ordinary merge request") if mismatch
93
+ begin
94
+ expired = Time.iso8601(decision.fetch("expires_at").to_s) <= Time.now.utc
95
+ rescue ArgumentError
96
+ return refuse("authorization decision has an invalid expiry")
97
+ end
98
+ return refuse("authorization has expired") if expired
99
+ Decision.new(authorized?: true, decision: decision, code: nil, message: nil)
100
+ end
101
+
102
+ private
103
+
104
+ # The authorizations mapping the CURRENT decision resolves against:
105
+ # the boot snapshot when no trusted path is installed, otherwise the
106
+ # freshly re-read document. A failed trusted re-read fails closed
107
+ # (InvalidConfigurationError — the unavailable family), never falls
108
+ # back to the stale snapshot.
109
+ def current_authorizations
110
+ return @authorizations unless @path
111
+ document = @loader.call(@path)
112
+ unless document.is_a?(Hash) && document["authorizations"].is_a?(Hash)
113
+ raise Ace::Lab::InvalidConfigurationError,
114
+ "invalid lab configuration: trusted authorization refresh at #{@path} " \
115
+ "did not yield an authorizations mapping"
116
+ end
117
+ unless ServicePolicy.configuration_digest(document) == @configuration_digest
118
+ raise Ace::Lab::InvalidConfigurationError,
119
+ "ordinary receiver configuration changed; restart with the installed configuration"
120
+ end
121
+ document.fetch("authorizations")
122
+ end
123
+
124
+ def refuse(message)
125
+ Decision.new(authorized?: false, decision: nil,
126
+ code: "ordinary_merge_authorization_invalid", message: message)
127
+ end
128
+ end
129
+ end
130
+ end
131
+ end
@@ -0,0 +1,262 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "socket"
5
+ require_relative "../errors"
6
+ require_relative "ordinary_socket"
7
+
8
+ module Ace
9
+ module Lab
10
+ module Molecules
11
+ # The ordinary receiver's serve-side transport (spec 8x3.t.xz9.4 serve
12
+ # entrypoint). Binds the configured unix socket and answers the exact
13
+ # framed protocol the OrdinarySocket client speaks: one bounded JSON
14
+ # document each way behind the shared handshake line. Authentication is
15
+ # MUTUAL through OS peer credentials: every connection's peer UID must equal
16
+ # the configured producer principal UID, and the listener itself runs
17
+ # as the configured receiver UID — the identity the client verifies on
18
+ # its side. Every identity, framing, deadline or parse failure is
19
+ # fail-closed: the peer receives the closed refusal envelope (or the
20
+ # connection closes) and nothing is ever dispatched. This is not an
21
+ # HTTP transport and there is no cross-VM fallback.
22
+ class OrdinaryListener
23
+ HANDSHAKE = OrdinarySocket::HANDSHAKE
24
+ LIMIT = OrdinarySocket::LIMIT
25
+ DEADLINE_SECONDS = 30
26
+
27
+ def initialize(socket_path:, peer_uid:, handler:, socket_gid: nil, lock_path: nil, logger: nil)
28
+ unless socket_path.is_a?(String) && socket_path.start_with?("/") &&
29
+ peer_uid.is_a?(Integer) && peer_uid >= 0 && handler.respond_to?(:call)
30
+ raise ArgumentError, "ordinary listener needs an absolute socket path, a peer uid and a handler"
31
+ end
32
+ unless socket_gid.nil? || (socket_gid.is_a?(Integer) && socket_gid >= 0)
33
+ raise ArgumentError, "ordinary listener socket_gid must be a non-negative integer"
34
+ end
35
+ @socket_gid = socket_gid
36
+ @socket_path = socket_path
37
+ @peer_uid = peer_uid
38
+ @handler = handler
39
+ @lock_path = lock_path || "#{@socket_path}.lock"
40
+ @logger = logger
41
+ @stopping = false
42
+ end
43
+
44
+ # Serve until #stop. Excludes a second listener through one owned
45
+ # lock file, removes only its own stale endpoint, and always removes
46
+ # the endpoint it created.
47
+ def serve(on_ready: nil)
48
+ acquire_lock!
49
+ remove_stale_endpoint!
50
+ @listener = UNIXServer.new(@socket_path)
51
+ @endpoint_identity = File.stat(@socket_path)
52
+ File.chown(nil, @socket_gid, @socket_path) if @socket_gid
53
+ File.chmod(@socket_gid ? 0o660 : 0o600, @socket_path)
54
+ on_ready.call if on_ready
55
+ @handler.recover_pending! if @handler.respond_to?(:recover_pending!)
56
+ until @stopping
57
+ socket = @listener.accept
58
+ serve_connection(socket)
59
+ end
60
+ rescue IOError, Errno::EBADF
61
+ raise unless @stopping
62
+ ensure
63
+ @listener&.close
64
+ remove_owned_endpoint!
65
+ @lock&.flock(File::LOCK_UN)
66
+ @lock&.close
67
+ end
68
+
69
+ # The existing listener participates in the Assign owner's lifetime.
70
+ def run(on_ready:)
71
+ serve(on_ready: on_ready)
72
+ end
73
+
74
+ def stop
75
+ @stopping = true
76
+ @listener&.close
77
+ rescue IOError
78
+ nil
79
+ end
80
+
81
+ # One bounded connection: verify the peer identity, read one framed
82
+ # request, answer one framed envelope, close. Fail-closed on every
83
+ # violation; a dispatch never happens from an unverified frame.
84
+ def serve_connection(socket)
85
+ deadline = Time.now.utc + DEADLINE_SECONDS
86
+ begin
87
+ verify_peer!(socket)
88
+ submission = read_request!(socket, deadline)
89
+ response = @handler.call(submission)
90
+ write_response_safely(socket, response, deadline)
91
+ if response.is_a?(Hash) && response["status"] == "ok" && @handler.respond_to?(:execute)
92
+ begin
93
+ # Admission is durable even if the acknowledgment was lost; the
94
+ # execution lifetime belongs to the canonical record, not
95
+ # the short connection. A lost lifecycle stays pending or
96
+ # uncertain and reconciles by the original reference.
97
+ @handler.execute(response.dig("data", "request_id"))
98
+ rescue StandardError => error
99
+ log_failure("effect", error)
100
+ end
101
+ end
102
+ rescue OrdinaryRefused => e
103
+ write_response_safely(socket, e.envelope, deadline)
104
+ rescue OrdinaryListenerError, IOError, SystemCallError => error
105
+ # Fail closed without a fabricated envelope; the client classifies
106
+ # a lost/unreadable response as ordinary_merge_unavailable.
107
+ log_failure("connection", error)
108
+ rescue StandardError => error
109
+ log_failure("request", error)
110
+ write_response_safely(socket, refusal_envelope("ordinary_merge_unavailable",
111
+ "receiver failed to handle the request"), deadline)
112
+ ensure
113
+ begin
114
+ socket.close
115
+ rescue IOError
116
+ nil
117
+ end
118
+ end
119
+ end
120
+
121
+ class OrdinaryListenerError < ::StandardError; end
122
+
123
+ # A verified-connection refusal that still carries a closed envelope.
124
+ class OrdinaryRefused < OrdinaryListenerError
125
+ attr_reader :envelope
126
+
127
+ def initialize(envelope)
128
+ @envelope = envelope
129
+ super(envelope.dig("error", "message").to_s)
130
+ end
131
+ end
132
+
133
+ private
134
+
135
+ def write_response_safely(socket, response, deadline)
136
+ write_response!(socket, response, deadline)
137
+ rescue OrdinaryListenerError, IOError, SystemCallError => error
138
+ log_failure("response", error)
139
+ end
140
+
141
+ def log_failure(phase, error)
142
+ # Arbitrary exception messages may contain provider credentials or
143
+ # request bodies. Journal references remain the source of effect state.
144
+ @logger&.call("ordinary receiver #{phase} failed (#{error.class.name})")
145
+ end
146
+
147
+ # Mutual half of OS peer authentication: the connecting process must run as the
148
+ # configured producer principal UID. Anything else is refused before
149
+ # one byte of request is read.
150
+ def verify_peer!(socket)
151
+ peer_uid, = socket.getpeereid
152
+ return if peer_uid == @peer_uid
153
+ raise OrdinaryRefused, refusal_envelope("ordinary_merge_unauthenticated",
154
+ "connecting principal is not the configured ordinary overseer")
155
+ rescue SystemCallError, IOError, SocketError, NotImplementedError
156
+ raise OrdinaryListenerError, "peer credentials are unavailable"
157
+ end
158
+
159
+ def read_request!(socket, deadline)
160
+ header = read_line!(socket, deadline)
161
+ match = /\A#{Regexp.escape(HANDSHAKE)} (\d{1,5})\n\z/o.match(header)
162
+ raise OrdinaryListenerError, "request header is invalid" unless match
163
+ length = Integer(match[1])
164
+ raise OrdinaryListenerError, "request exceeds the wire bound" if length > LIMIT
165
+ payload = read_exact!(socket, length, deadline)
166
+ JSON.parse(payload, allow_duplicate_key: false, create_additions: false, max_nesting: 16)
167
+ rescue JSON::ParserError
168
+ raise OrdinaryRefused, refusal_envelope("ordinary_merge_invalid_request",
169
+ "request document is not valid JSON")
170
+ end
171
+
172
+ def write_response!(socket, response, deadline)
173
+ payload = JSON.generate(response)
174
+ raise OrdinaryListenerError, "response exceeds the wire bound" if payload.bytesize > LIMIT
175
+ frame = "#{HANDSHAKE} #{payload.bytesize}\n#{payload}"
176
+ written = 0
177
+ while written < frame.bytesize
178
+ raise OrdinaryListenerError, "response write deadline expired" if Time.now.utc >= deadline
179
+ begin
180
+ written += socket.write_nonblock(frame.byteslice(written..))
181
+ rescue IO::WaitWritable
182
+ socket.wait_writable(remaining!(deadline)) or
183
+ raise OrdinaryListenerError, "response write deadline expired"
184
+ end
185
+ end
186
+ rescue JSON::GeneratorError
187
+ raise OrdinaryListenerError, "response is not serializable"
188
+ end
189
+
190
+ def refusal_envelope(code, message)
191
+ {"status" => "error", "error" => {
192
+ "schema" => "ace.lab.service.ordinary-merge-refusal/v1",
193
+ "code" => code,
194
+ "message" => message.to_s.scrub.gsub(/\s+/, " ").strip[0, 512],
195
+ "request_id" => "unknown",
196
+ "input_digest" => nil
197
+ }}
198
+ end
199
+
200
+ def read_line!(socket, deadline)
201
+ line = +""
202
+ until line.end_with?("\n")
203
+ raise OrdinaryListenerError, "request header is unbounded" if line.bytesize > 128
204
+ line << read_exact!(socket, 1, deadline)
205
+ end
206
+ line
207
+ end
208
+
209
+ def read_exact!(socket, length, deadline)
210
+ buffer = +""
211
+ while buffer.bytesize < length
212
+ raise OrdinaryListenerError, "request read deadline expired" if Time.now.utc >= deadline
213
+ begin
214
+ chunk = socket.read_nonblock(length - buffer.bytesize)
215
+ raise OrdinaryListenerError, "peer closed the connection" if chunk.nil?
216
+ buffer << chunk
217
+ rescue IO::WaitReadable
218
+ socket.wait_readable(remaining!(deadline)) or
219
+ raise OrdinaryListenerError, "request read deadline expired"
220
+ end
221
+ end
222
+ buffer
223
+ end
224
+
225
+ def remaining!(deadline)
226
+ left = deadline - Time.now.utc
227
+ raise OrdinaryListenerError, "connection deadline expired" if left <= 0
228
+ left
229
+ end
230
+
231
+ def acquire_lock!
232
+ @lock = File.open(@lock_path, File::RDWR | File::CREAT | File::NOFOLLOW, 0o600)
233
+ stat = @lock.stat
234
+ unless stat.file? && stat.uid == Process.uid && stat.nlink == 1 && (stat.mode & 0o7777) == 0o600
235
+ raise Ace::Lab::InvalidConfigurationError, "receiver listener lock differs"
236
+ end
237
+ unless @lock.flock(File::LOCK_EX | File::LOCK_NB)
238
+ raise Ace::Lab::InvalidConfigurationError, "receiver listener already active"
239
+ end
240
+ end
241
+
242
+ def remove_stale_endpoint!
243
+ stat = File.lstat(@socket_path)
244
+ unless stat.socket? && stat.uid == Process.uid
245
+ raise Ace::Lab::InvalidConfigurationError, "receiver endpoint differs"
246
+ end
247
+ File.unlink(@socket_path)
248
+ rescue Errno::ENOENT
249
+ nil
250
+ end
251
+
252
+ def remove_owned_endpoint!
253
+ return unless @endpoint_identity
254
+ stat = File.stat(@socket_path)
255
+ File.unlink(@socket_path) if stat.socket? && stat.ino == @endpoint_identity.ino
256
+ rescue Errno::ENOENT
257
+ nil
258
+ end
259
+ end
260
+ end
261
+ end
262
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "ordinary_worktree_read"
4
+
5
+ module Ace
6
+ module Lab
7
+ module Molecules
8
+ # Local checks are bounded read-only observations. Only the forge provider
9
+ # executes merge; moving a local ref can never prove a delivered merge.
10
+ class OrdinaryMergeRead
11
+ STRATEGY = "ff"
12
+
13
+ def initialize(repo_path:, base_ref:, root: repo_path, common_dir: File.join(repo_path, ".git"),
14
+ deadline: Process.clock_gettime(Process::CLOCK_MONOTONIC) + 30)
15
+ unless repo_path.is_a?(String) && repo_path.start_with?("/") &&
16
+ base_ref.is_a?(String) && base_ref.start_with?("refs/")
17
+ raise ArgumentError, "ordinary merge read needs an absolute repository and full base ref"
18
+ end
19
+ @repo_path, @base_ref = repo_path, base_ref
20
+ @reader = OrdinaryWorktreeRead.new(root: root, common_dir: common_dir, deadline: deadline)
21
+ end
22
+
23
+ def base_head
24
+ @reader.ref_head(@repo_path, @base_ref)
25
+ rescue Ace::Assign::Error => error
26
+ raise GitUnavailable, error.message
27
+ end
28
+
29
+ def candidate_commit?(head)
30
+ @reader.commit?(@repo_path, head)
31
+ rescue Ace::Assign::Error => error
32
+ raise GitUnavailable, error.message
33
+ end
34
+
35
+ def fast_forwardable?(head)
36
+ @reader.ancestor?(@repo_path, base_head, head)
37
+ rescue Ace::Assign::Error => error
38
+ raise GitUnavailable, error.message
39
+ end
40
+
41
+ class GitUnavailable < StandardError; end
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,106 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+ require "ace/runtime/molecules/protected_socket"
5
+ require "ace/herdr/molecules/herdr_executor"
6
+ require "ace/assign/authority/ordinary_peer"
7
+ require_relative "ordinary_owner_config"
8
+
9
+ module Ace
10
+ module Lab
11
+ module Molecules
12
+ # Read-only use of Herdr's existing native protocol. Root selection pins
13
+ # the endpoint inode and live server; no ambient CLI environment chooses
14
+ # the daemon, and no protected runtime guarantees are borrowed here.
15
+ class OrdinaryNativeRead
16
+ def initialize(config:, deadline:, peer: Ace::Assign::Authority::OrdinaryPeer.new)
17
+ raise ArgumentError, "native reader needs installed selection" unless config.is_a?(OrdinaryOwnerConfig)
18
+ @config, @deadline, @peer = config, deadline, peer
19
+ @native = config.native
20
+ end
21
+
22
+ def preflight!
23
+ result = request("ping", {})
24
+ unless result["type"] == "pong" && result.values_at("version", "protocol") == @native.values_at("version", "protocol")
25
+ unavailable!("native protocol differs from installed selection")
26
+ end
27
+ true
28
+ end
29
+
30
+ def pane_get(pane)
31
+ result = request("pane.get", {"pane_id" => pane})
32
+ unless result["type"] == "pane_info" && result["pane"].is_a?(Hash) && result["pane"]["pane_id"] == pane
33
+ unavailable!("native pane metadata differs from requested pane")
34
+ end
35
+ response(result)
36
+ end
37
+
38
+ def pane_process_info(pane)
39
+ @process_info = nil
40
+ result = request("pane.process_info", {"pane_id" => pane})
41
+ unless result["type"] == "pane_process_info" && result["process_info"].is_a?(Hash) && result["process_info"]["pane_id"] == pane
42
+ unavailable!("native process inventory differs from requested pane")
43
+ end
44
+ @process_info = result.fetch("process_info")
45
+ response(result)
46
+ end
47
+
48
+ # This per-PID native field comes from process_cwd, not the terminal's
49
+ # OSC/UI working directory. The caller separately verifies PID birth.
50
+ def process_cwd(pid)
51
+ processes = @process_info.is_a?(Hash) && @process_info["foreground_processes"]
52
+ unavailable!("native process inventory is unavailable") unless processes.is_a?(Array)
53
+ matches = processes.select { |entry| entry.is_a?(Hash) && entry["pid"] == pid }
54
+ path = matches.one? && matches.first["cwd"]
55
+ unless path.is_a?(String) && path.bytesize.between?(1, 4096) && !path.include?("\0") &&
56
+ path.start_with?("/") && File.expand_path(path) == path
57
+ unavailable!("exact native process working directory is unavailable")
58
+ end
59
+ path
60
+ end
61
+
62
+ private
63
+
64
+ def request(method, params)
65
+ verify_endpoint!
66
+ wire.connect(@native.fetch("socket_path"), deadline: @deadline) do |socket|
67
+ unless @peer.capture(socket, deadline: @deadline) == @native.fetch("server_identity")
68
+ unavailable!("native peer differs from installed server")
69
+ end
70
+ verify_endpoint!
71
+ id = SecureRandom.hex(12)
72
+ wire.write(socket, {"id" => id, "method" => method, "params" => params}, deadline: @deadline, limit: 16_384)
73
+ value = wire.read(wire::Ingress.new(socket), deadline: @deadline, limit: 65_536)
74
+ unless value.is_a?(Hash) && value.keys.sort == %w[id result] && value["id"] == id && value["result"].is_a?(Hash)
75
+ unavailable!("native read response is invalid")
76
+ end
77
+ verify_endpoint!
78
+ @peer.live!(@native.fetch("server_identity"), deadline: @deadline)
79
+ value.fetch("result")
80
+ end
81
+ rescue SystemCallError, IOError, KeyError, Ace::Assign::AttemptErrors::UnauthorizedIdentity
82
+ unavailable!("native read is unavailable")
83
+ end
84
+
85
+ def verify_endpoint!
86
+ @config.verify_selection!
87
+ path = @native.fetch("socket_path")
88
+ wire.root_path!(File.dirname(path), directory: true)
89
+ unless wire.socket_identity(path) == @native.fetch("socket_identity") && (File.lstat(path).mode & 0o007).zero?
90
+ unavailable!("native endpoint generation or access differs")
91
+ end
92
+ end
93
+
94
+ def response(result)
95
+ Ace::Herdr::Molecules::ExecutionResult.new(stdout: JSON.generate({"result" => result}), stderr: "", success: true, exit_code: 0)
96
+ end
97
+
98
+ def wire = Ace::Runtime::Molecules::ProtectedSocket
99
+
100
+ def unavailable!(reason)
101
+ raise Ace::Runtime::RuntimeUnavailableError, reason
102
+ end
103
+ end
104
+ end
105
+ end
106
+ end