kobako 0.20.0-aarch64-linux → 0.21.0-aarch64-linux

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.
Files changed (78) hide show
  1. checksums.yaml +4 -4
  2. data/.release-please-manifest.json +1 -1
  3. data/CHANGELOG.md +107 -0
  4. data/README.md +96 -44
  5. data/ROADMAP.md +1 -1
  6. data/crates/kobako-runtime/CHANGELOG.md +37 -0
  7. data/crates/kobako-runtime/README.md +1 -1
  8. data/crates/kobako-transport/CHANGELOG.md +31 -0
  9. data/crates/kobako-transport/README.md +43 -0
  10. data/crates/kobako-wasmtime/CHANGELOG.md +23 -0
  11. data/crates/kobako-wasmtime/README.md +1 -1
  12. data/data/kobako.wasm +0 -0
  13. data/lib/kobako/3.3/kobako.so +0 -0
  14. data/lib/kobako/3.4/kobako.so +0 -0
  15. data/lib/kobako/4.0/kobako.so +0 -0
  16. data/lib/kobako/catalog/services.rb +13 -21
  17. data/lib/kobako/catalog/snippets.rb +16 -34
  18. data/lib/kobako/codec/decoder.rb +10 -13
  19. data/lib/kobako/codec/encoder.rb +7 -7
  20. data/lib/kobako/codec/error.rb +6 -6
  21. data/lib/kobako/codec/ext_types.rb +12 -72
  22. data/lib/kobako/codec/handle_walk.rb +6 -6
  23. data/lib/kobako/codec/state.rb +4 -56
  24. data/lib/kobako/codec/utils.rb +4 -4
  25. data/lib/kobako/codec.rb +11 -21
  26. data/lib/kobako/context.rb +23 -17
  27. data/lib/kobako/errors.rb +32 -11
  28. data/lib/kobako/outcome.rb +71 -128
  29. data/lib/kobako/payload/arguments.rb +59 -0
  30. data/lib/kobako/payload.rb +19 -0
  31. data/lib/kobako/sandbox.rb +12 -13
  32. data/lib/kobako/sandbox_options.rb +1 -1
  33. data/lib/kobako/snippet/binary.rb +3 -4
  34. data/lib/kobako/snippet/source.rb +5 -6
  35. data/lib/kobako/snippet.rb +2 -2
  36. data/lib/kobako/transport/call.rb +21 -0
  37. data/lib/kobako/transport/dispatcher.rb +86 -135
  38. data/lib/kobako/transport/error.rb +21 -5
  39. data/lib/kobako/transport/reflection.rb +82 -0
  40. data/lib/kobako/transport/run.rb +25 -33
  41. data/lib/kobako/transport/yielder.rb +27 -36
  42. data/lib/kobako/transport.rb +11 -8
  43. data/lib/kobako/usage.rb +1 -1
  44. data/lib/kobako/version.rb +1 -1
  45. data/release-please-config.json +47 -2
  46. data/sig/kobako/catalog/services.rbs +1 -1
  47. data/sig/kobako/catalog/snippets.rbs +4 -4
  48. data/sig/kobako/codec/error.rbs +4 -4
  49. data/sig/kobako/codec/ext_types.rbs +0 -7
  50. data/sig/kobako/codec/state.rbs +0 -4
  51. data/sig/kobako/codec.rbs +4 -5
  52. data/sig/kobako/context.rbs +4 -4
  53. data/sig/kobako/errors.rbs +15 -3
  54. data/sig/kobako/outcome.rbs +12 -13
  55. data/sig/kobako/payload/arguments.rbs +26 -0
  56. data/sig/kobako/payload.rbs +4 -0
  57. data/sig/kobako/pool.rbs +0 -2
  58. data/sig/kobako/runtime.rbs +15 -13
  59. data/sig/kobako/snippet/binary.rbs +1 -1
  60. data/sig/kobako/snippet/source.rbs +1 -1
  61. data/sig/kobako/transport/call.rbs +21 -0
  62. data/sig/kobako/transport/dispatcher.rbs +8 -10
  63. data/sig/kobako/transport/error.rbs +11 -0
  64. data/sig/kobako/transport/reflection.rbs +15 -0
  65. data/sig/kobako/transport/run.rbs +1 -1
  66. data/sig/kobako/transport/yielder.rbs +2 -2
  67. data/sig/kobako/transport.rbs +8 -2
  68. metadata +12 -12
  69. data/lib/kobako/fault.rb +0 -38
  70. data/lib/kobako/outcome/panic.rb +0 -42
  71. data/lib/kobako/transport/request.rb +0 -76
  72. data/lib/kobako/transport/response.rb +0 -83
  73. data/lib/kobako/transport/yield.rb +0 -94
  74. data/sig/kobako/fault.rbs +0 -19
  75. data/sig/kobako/outcome/panic.rbs +0 -34
  76. data/sig/kobako/transport/request.rbs +0 -29
  77. data/sig/kobako/transport/response.rbs +0 -33
  78. data/sig/kobako/transport/yield.rbs +0 -34
@@ -133,8 +133,8 @@ module Kobako
133
133
  end
134
134
 
135
135
  # Dispatch into a preloaded entrypoint constant. Delegates host
136
- # pre-flight and wire encoding to +Kobako::Transport::Run+ /
137
- # +Kobako::Transport::Run#encode+: a non-Symbol/String +target+ raises
136
+ # pre-flight and argument encoding to +Kobako::Transport::Run+ /
137
+ # +Kobako::Transport::Run#payload+: a non-Symbol/String +target+ raises
138
138
  # +TypeError+, while a +target+ failing the constant pattern, a forged
139
139
  # +Kobako::Handle+ in +args+ / +kwargs+, or a non-Symbol +kwargs+ key
140
140
  # raise +ArgumentError+. The guest resolves +target+ as a top-level
@@ -143,8 +143,8 @@ module Kobako
143
143
  # and snippet table. Runtime errors follow the same three-class
144
144
  # taxonomy as +#eval+.
145
145
  def run(target, *args, **kwargs, &block)
146
- run_envelope = Transport::Run.new(entrypoint: target, args: args, kwargs: kwargs)
147
- new_invocation.run(run_envelope, &block)
146
+ request = Transport::Run.new(entrypoint: target, args: args, kwargs: kwargs)
147
+ new_invocation.run(request, &block)
148
148
  end
149
149
 
150
150
  # Execute a guest mruby source string in a fresh +mrb_state+. +code+ is
@@ -153,12 +153,11 @@ module Kobako
153
153
  #
154
154
  # Source delivery uses the WASI stdin three-frame protocol
155
155
  # ({docs/wire-codec.md Invocation channels}[link:../../docs/wire-codec.md]):
156
- # Frame 1 carries the msgpack-encoded preamble (Service registry
157
- # snapshot), Frame 2 carries the user source UTF-8 bytes, and
158
- # Frame 3 carries the snippet table registered via +#preload+.
159
- # Each frame is prefixed by a 4-byte big-endian u32 length; Frame 3 is
160
- # mandatory-presence — an empty snippet table sends an empty msgpack
161
- # array, never an absent frame.
156
+ # Frame 1 carries the preamble (Service registry snapshot), Frame 2 the
157
+ # user source UTF-8 bytes, and Frame 3 the snippet table registered via
158
+ # +#preload+. Each frame is prefixed by a 4-byte big-endian u32 length;
159
+ # Frame 1 and Frame 3 are mandatory-presence — an empty registry sends a
160
+ # present, empty frame rather than an absent one.
162
161
  #
163
162
  # The first invocation seals the Service registry and snippet table;
164
163
  # subsequent +#bind+ / +#preload+ calls raise +ArgumentError+.
@@ -197,13 +196,13 @@ module Kobako
197
196
  Context.new(runtime: @runtime, services: @services, snippets: @snippets, extensions: @extensions)
198
197
  end
199
198
 
200
- # Per-invocation prologue on the config tier: seals the Service / snippet /
199
+ # Per-invocation prologue on the config tier: seals the Service and
201
200
  # Extension registries on the first call (idempotent — asserting Extension
202
- # dependencies then). Per-invocation provider resolution and observable
201
+ # dependencies then). The Service seal is the one +#bind+ / +#preload+ /
202
+ # +#install+ all gate on. Per-invocation provider resolution and observable
203
203
  # state live on the +Context+, not here.
204
204
  def begin_invocation!
205
205
  @services.seal!
206
- @snippets.seal!
207
206
  @extensions.seal!
208
207
  end
209
208
  end
@@ -6,7 +6,7 @@ module Kobako
6
6
  # Kobako::SandboxOptions — immutable Value Object holding the four
7
7
  # per-Sandbox configuration caps and the requested isolation profile.
8
8
  # Built on the +class X < Data.define(...)+ subclass form (the
9
- # Steep-friendly shape — see +lib/kobako/outcome/panic.rb+).
9
+ # Steep-friendly shape — see +.rubocop.yml+ for the rationale).
10
10
  #
11
11
  # The +initialize+ normalises every option before delegating to Data's
12
12
  # +super+: +timeout+ to Float seconds, +memory_limit+ / +stdout_limit+ /
@@ -18,10 +18,9 @@ module Kobako
18
18
  # form +Binary.new(body: ...)+. Wire-form construction is the
19
19
  # registry's responsibility.
20
20
  class Binary < Data.define(:body)
21
- # The +kind+ field value carried by bytecode snippets in their
22
- # Frame 3 wire envelope entry
23
- # ({docs/wire-codec.md Invocation channels}[link:../../../docs/wire-codec.md]).
24
- KIND = "bytecode"
21
+ # Names the snippet form the guest replays this entry as. The wire's
22
+ # discriminant byte is assigned by the core envelope, not here.
23
+ KIND = :bytecode
25
24
  end
26
25
  end
27
26
  end
@@ -15,13 +15,12 @@ module Kobako
15
15
  # carries no mutation API. Callers (chiefly +Catalog::Snippets+)
16
16
  # construct instances via keyword form +Source.new(name: ..., body: ...)+.
17
17
  # Wire-form construction is the registry's responsibility: as a leaf
18
- # carrier this Source stays pure and +Catalog::Snippets#encode+ reads
19
- # its attributes off the outside rather than asking it to self-encode.
18
+ # carrier this Source stays pure and +Catalog::Snippets#entries+ reads
19
+ # its attributes off the outside rather than asking it to project itself.
20
20
  class Source < Data.define(:name, :body)
21
- # The +kind+ field value carried by source snippets in their Frame
22
- # 3 wire envelope entry
23
- # ({docs/wire-codec.md Invocation channels}[link:../../../docs/wire-codec.md]).
24
- KIND = "source"
21
+ # Names the snippet form the guest replays this entry as. The wire's
22
+ # discriminant byte is assigned by the core envelope, not here.
23
+ KIND = :source
25
24
  end
26
25
  end
27
26
  end
@@ -10,8 +10,8 @@ module Kobako
10
10
  # +Source+ represents a single +#preload(code:, name:)+ entry; +Binary+
11
11
  # represents a single +#preload(binary:)+ entry. Both are plain value
12
12
  # objects with no dependency on the +Catalog::Snippets+ registry that
13
- # holds them — the registry reads their attributes externally when
14
- # encoding the wire envelope.
13
+ # holds them — the registry reads their attributes externally into the
14
+ # tuples the native side frames.
15
15
  module Snippet
16
16
  end
17
17
  end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kobako
4
+ module Transport
5
+ # One guest-initiated dispatch, as the native side decoded it off the
6
+ # core envelope. The routing fields arrive already decoded — a String
7
+ # for a bound constant's path, an Integer for a Capability Handle id —
8
+ # so the host resolves a target without interpreting a payload byte.
9
+ #
10
+ # +payload+ stays bytes here on purpose: routing never interprets a
11
+ # payload byte, and the one place that does — the Dispatcher — must
12
+ # decode it inside the Codec bracket that records whether a Handle
13
+ # crossed.
14
+ #
15
+ # Built on the +class X < Data.define(...)+ subclass form so the class
16
+ # body is fully Steep-visible; see +.rubocop.yml+ for the
17
+ # rationale.
18
+ class Call < Data.define(:target, :method_name, :block_given, :payload)
19
+ end
20
+ end
21
+ end
@@ -1,32 +1,27 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "../codec"
4
- require_relative "request"
5
- require_relative "response"
6
- require_relative "yield"
4
+ require_relative "../payload"
5
+ require_relative "call"
6
+ require_relative "reflection"
7
7
  require_relative "yielder"
8
8
 
9
9
  module Kobako
10
10
  # See lib/kobako/transport.rb for the umbrella module doc; this file
11
- # owns the pure-function dispatcher that decodes guest-initiated
12
- # Requests and produces encoded Responses.
11
+ # owns the pure-function dispatcher that answers a routed Call.
13
12
  module Transport
14
- # Pure-function dispatcher for guest-initiated transport calls.
15
- # Decodes a msgpack-encoded Request envelope, resolves the target
16
- # object through the per-invocation path +resolver+ (the +Context+, whose
17
- # +#lookup+ layers per-invocation providers over the static bindings) or
18
- # Catalog::Handles (Handle lookup), invokes the method, and returns
19
- # a msgpack-encoded Response envelope.
13
+ # Pure-function dispatcher for guest-initiated Calls. The native side
14
+ # has already decoded the core envelope, so this resolves the target
15
+ # through the per-invocation path +resolver+ (the +Context+, whose
16
+ # +#lookup+ layers per-invocation providers over the static bindings)
17
+ # or Catalog::Handles, decodes only the payload, invokes the method,
18
+ # and answers +[ok, bytes]+ — which the native side puts on the
19
+ # Reply's ok or fault arm. It never raises.
20
20
  #
21
21
  # The module is stateless — all mutable state is threaded through
22
22
  # arguments so Dispatcher has no instance variables and no side
23
23
  # effects beyond mutating the Catalog::Handles via +alloc+ when a
24
24
  # non-wire-representable return value must be wrapped.
25
- #
26
- # Entry point:
27
- #
28
- # Kobako::Transport::Dispatcher.dispatch(request_bytes, resolver, handler, yield_to_guest)
29
- # # => msgpack-encoded Response bytes (never raises)
30
25
  module Dispatcher
31
26
  # Throw tag for the Yielder's break unwind back to the
32
27
  # dispatcher's +catch+ frame. +private_constant+ is a
@@ -36,98 +31,82 @@ module Kobako
36
31
 
37
32
  module_function
38
33
 
39
- # Internal sentinel raised when target resolution fails. Mapped to
40
- # Response.error with type="undefined". Contained at the wire boundary —
34
+ # Internal sentinel raised when target resolution fails. Becomes a
35
+ # Fault with type="undefined". Contained at the wire boundary —
41
36
  # not part of the public Kobako error taxonomy.
42
37
  class UndefinedTargetError < StandardError; end
43
38
 
44
- # Modules whose instance methods are ambient Ruby reflection /
45
- # metaprogramming surface (+send+, +public_send+, +instance_eval+,
46
- # +method+, +tap+, +instance_variable_get+, ...) rather than Service
47
- # behaviour. A guest-supplied method name resolving to one of these is
48
- # rejected: only methods the bound object itself exposes as Service behaviour are
49
- # reachable, and +public_send(:send, ...)+ would otherwise let a guest
50
- # pivot through +send+ into the private +Kernel#eval+ / +#system+
51
- # surface (host RCE).
52
- META_OWNERS = [BasicObject, Kernel, Object, Module, Class].freeze
53
- private_constant :META_OWNERS
54
-
55
- # Callable gadget types whose own public methods are reflection surface
56
- # (+Proc#binding+ reaches +Binding#eval+, +Method#receiver+ / +#unbind+
57
- # hand back the underlying object) rather than Service behaviour. Only
58
- # CALLABLE_ALLOW is reachable on a target of these types; a bound
59
- # lambda stays invocable, its reflective surface does not.
60
- GADGET_OWNERS = [Proc, Method, UnboundMethod, Binding].freeze
61
- private_constant :GADGET_OWNERS
62
-
63
- # The sole methods reachable on a GADGET_OWNERS target: invoking it
64
- # (+call+ / +[]+ / +yield+) and the harmless +arity+ / +lambda?+
65
- # describers that aid guest-side debugging.
66
- CALLABLE_ALLOW = %i[call [] yield arity lambda?].freeze
67
- private_constant :CALLABLE_ALLOW
68
-
69
- # Dispatch a single transport request and return the encoded
70
- # Response bytes. Invoked from the per-invocation dispatch Proc that
39
+ # Answer a single routed Call with +[ok, bytes]+, which the native
40
+ # side puts on the Reply's ok or fault arm. Invoked from the
41
+ # per-invocation dispatch Proc that
71
42
  # +Kobako::Context+ hands to +Runtime#eval+ / +#run+; +resolver+,
72
43
  # +handler+, and +yield_to_guest+ are captured in that Proc's
73
44
  # closure so the Dispatcher stays stateless and neither the resolver
74
45
  # nor the Context needs to publish accessors for the per-invocation
75
46
  # +Catalog::Handles+ or +Runtime+. +yield_to_guest+ is a +String → String+ callable
76
47
  # (the ext's per-dispatch +Kobako::Runtime::GuestYielder+) used only
77
- # when the Request carries +block_given: true+. Always
78
- # returns a binary String — every failure path is reified as a
79
- # Response.error envelope so the guest sees a transport error rather
80
- # than a wasm trap.
48
+ # when the Call carries +block_given: true+. Never raises — every
49
+ # failure path takes the fault arm instead, so the guest sees a
50
+ # transport error rather than a wasm trap.
81
51
  #
82
52
  # The decode runs inside +Codec.track_handles+ so #resolve_call_args
83
53
  # can skip the argument walk when no Capability Handle crossed the
84
54
  # wire.
85
- def dispatch(request_bytes, resolver, handler, yield_to_guest)
86
- request, carried_handle = Kobako::Codec.track_handles { Kobako::Transport::Request.decode(request_bytes) }
87
- target = resolve_target(request.target, resolver, handler)
88
- args, kwargs = resolve_call_args(request, handler, carried_handle)
89
- yielder = Yielder.new(yield_to_guest, BREAK_THROW, handler) if request.block_given
90
- encode_ok(catch(BREAK_THROW) { invoke(target, request.method_name, args, kwargs, yielder) }, handler)
55
+ def dispatch(call, resolver, handler, yield_to_guest)
56
+ yielder = Yielder.new(yield_to_guest, BREAK_THROW, handler) if call.block_given
57
+ [true, encode_ok(run(call, resolver, handler, yielder), handler), nil] # : [bool, String, String?]
91
58
  # StandardError is the boundary by intent: a Service method's
92
- # application fault folds into a guest-rescuable Response.error, while a
59
+ # application fault folds into a guest-rescuable fault, while a
93
60
  # host-process failure (NoMemoryError, SignalException, a bare Exception)
94
61
  # stays uncaught and traps the invocation rather than being masked as a
95
62
  # rescuable fault.
96
63
  rescue StandardError => e
97
- encode_caught_error(e)
64
+ [false, *caught_fault(e)] # : [bool, String, String?]
98
65
  ensure
99
66
  yielder&.invalidate!
100
67
  end
101
68
 
102
- # Resolve positional and keyword arguments off +request+ in one step.
103
- # +carried_handle+ reports whether the decode carried any Capability
104
- # Handle; when it did not, every argument resolves to itself, so the
105
- # decoded values pass straight through and the walk is skipped entirely.
106
- # Otherwise both go through #resolve_arg so Handles round-trip back to
107
- # the host-side Ruby object before the call reaches +public_send+.
108
- def resolve_call_args(request, handler, carried_handle)
109
- return [request.args, request.kwargs] unless carried_handle
110
-
111
- [request.args.map { |v| resolve_arg(v, handler) },
112
- request.kwargs.transform_values { |v| resolve_arg(v, handler) }]
69
+ # Decode the payload, resolve the receiver, and run the method inside
70
+ # the +catch+ frame a guest +break+ unwinds to. Split from #dispatch
71
+ # so the reply-shaping and the failure boundary stay one glance wide.
72
+ def run(call, resolver, handler, yielder)
73
+ arguments, carried_handle = Kobako::Codec.track_handles { Payload::Arguments.decode(call.payload) }
74
+ receiver = resolve_target(call.target, resolver, handler)
75
+ args, kwargs = resolve_call_args(arguments, handler, carried_handle)
76
+ catch(BREAK_THROW) { invoke(receiver, call.method_name, args, kwargs, yielder) }
77
+ end
78
+
79
+ # Resolve positional and keyword arguments off the decoded payload in
80
+ # one step. +carried_handle+ reports whether the decode carried any
81
+ # Capability Handle; when it did not, every argument resolves to
82
+ # itself, so the decoded values pass straight through and the walk is
83
+ # skipped entirely. Otherwise both go through #resolve_arg so Handles
84
+ # round-trip back to the host-side Ruby object before the call reaches
85
+ # +public_send+.
86
+ def resolve_call_args(arguments, handler, carried_handle)
87
+ return [arguments.args, arguments.kwargs] unless carried_handle
88
+
89
+ [arguments.args.map { |v| resolve_arg(v, handler) },
90
+ arguments.kwargs.transform_values { |v| resolve_arg(v, handler) }]
113
91
  end
114
92
 
115
- # Map an error caught at the dispatch boundary to a +Response.error+
116
- # envelope (binary msgpack). +error+ is the +StandardError+ caught by
117
- # #dispatch's rescue; the +type+ field tells the guest which kind
118
- # of failure it was so it can raise the matching proxy-side error.
119
- def encode_caught_error(error)
93
+ # Map an error caught at the dispatch boundary to the message and the
94
+ # category the native side frames into the Reply's fault arm. +error+
95
+ # is the +StandardError+ caught by #dispatch's rescue; the category
96
+ # tells the guest which kind of failure it was so it can raise the
97
+ # matching proxy-side error.
98
+ def caught_fault(error)
120
99
  case error
121
- when Kobako::Codec::Error then encode_error("runtime",
122
- "Sandbox received a malformed request: #{error.message}")
123
- when UndefinedTargetError then encode_error("undefined", error.message)
124
- when ArgumentError then encode_error("argument", error.message)
125
- else encode_error("runtime", "#{error.class}: #{error.message}")
100
+ when Kobako::Codec::Error then fault("runtime",
101
+ "Sandbox received a malformed request: #{error.message}")
102
+ when UndefinedTargetError then fault("undefined", error.message)
103
+ when ArgumentError then fault("argument", error.message)
104
+ else fault("runtime", "#{error.class}: #{error.message}")
126
105
  end
127
106
  end
128
107
 
129
108
  # Dispatch +method+ on +target+. +kwargs+ is already Symbol-keyed
130
- # (the +Request+ invariant pins it). The empty-kwargs branch omits
109
+ # (the +Payload::Arguments+ invariant pins it). The empty-kwargs branch omits
131
110
  # the +**+ splat so Ruby 3.x's strict kwargs separation does not
132
111
  # reject calls to no-kwarg methods when the wire carries the
133
112
  # uniform empty-map shape.
@@ -139,8 +118,7 @@ module Kobako
139
118
  # conditional.
140
119
  def invoke(target, method, args, kwargs, yielder = nil)
141
120
  name = method.to_sym
142
- reject_meta_method!(target, name)
143
- reject_unexposed!(target, name)
121
+ reject_unreachable!(target, name)
144
122
  block = yielder&.to_proc
145
123
  if kwargs.empty?
146
124
  target.public_send(name, *args, &block)
@@ -149,38 +127,14 @@ module Kobako
149
127
  end
150
128
  end
151
129
 
152
- # Guard the +public_send+ below against ambient reflection methods.
153
- # A public method whose owner is a META_OWNERS or GADGET_OWNERS module is
154
- # rejected, except CALLABLE_ALLOW on a gadget target (a bound lambda
155
- # stays invocable). A name with no concrete public method is allowed
156
- # only when the target opts into it via +respond_to?+ (dynamic
157
- # +method_missing+ Services), since the dangerous methods are all
158
- # concretely defined and therefore never reach that branch.
159
- def reject_meta_method!(target, name)
160
- owner = target.public_method(name).owner
161
- gadget = GADGET_OWNERS.include?(owner)
162
- return unless META_OWNERS.include?(owner) || gadget
163
- return if gadget && CALLABLE_ALLOW.include?(name)
164
-
165
- raise UndefinedTargetError, "method #{name.inspect} is not a Service method"
166
- rescue NameError
167
- return if target.respond_to?(name)
168
-
169
- raise UndefinedTargetError, "no public method #{name.inspect} on target"
170
- end
171
-
172
- # Consult the target's opt-in narrowing predicate. A bound object
173
- # may define a private +respond_to_guest?(name)+ to restrict which of its
174
- # methods the guest reaches; a falsy answer rejects the dispatch.
175
- # The predicate composes beneath #reject_meta_method! — it only narrows,
176
- # never re-opening the reflection surface the floor rejects — and is
177
- # consulted with the private surface included so the guest's +public_send+
178
- # dispatch can never reach +respond_to_guest?+ itself.
179
- def reject_unexposed!(target, name)
180
- return unless target.respond_to?(:respond_to_guest?, true)
181
- return if target.__send__(:respond_to_guest?, name)
182
-
183
- raise UndefinedTargetError, "method #{name.inspect} is not exposed to the guest"
130
+ # Guard the +public_send+ below: Reflection decides what counts as
131
+ # Service behaviour on this target, and its refusal reason becomes
132
+ # the guest's +undefined+ fault. Both the ambient-surface floor and
133
+ # the target's own narrowing predicate answer through it, so a
134
+ # rejected name discloses nothing about which of the two refused.
135
+ def reject_unreachable!(target, name)
136
+ reason = Reflection.refusal(target, name)
137
+ raise UndefinedTargetError, reason if reason
184
138
  end
185
139
 
186
140
  # Resolve every Kobako::Handle in an argument — bare or nested in an
@@ -193,19 +147,18 @@ module Kobako
193
147
  raise UndefinedTargetError, e.message
194
148
  end
195
149
 
196
- # Resolve a Request target to the Ruby object the path +resolver+ (or
197
- # Catalog::Handles) holds. String targets go through the resolver;
198
- # Handle targets (ext 0x01) go through the Catalog::Handles.
199
- #
200
- # Target type is already validated by +Transport::Request.decode+
201
- # before this method is reached, so no else-branch is needed here —
202
- # the wire layer is the system boundary that enforces the invariant.
150
+ # Resolve a Call target to the Ruby object the path +resolver+ (or
151
+ # Catalog::Handles) holds. The native side already discriminated the
152
+ # two forms off the core envelope's +kind+ tag: a String is a bound
153
+ # constant's path, an Integer is a Capability Handle id. No
154
+ # else-branch is needed — the envelope layer is the system boundary
155
+ # that enforces the invariant.
203
156
  def resolve_target(target, resolver, handler)
204
157
  case target
205
158
  when String
206
159
  resolve_path(target, resolver)
207
- when Kobako::Handle
208
- require_live_object!(target.id, handler)
160
+ when Integer
161
+ require_live_object!(target, handler)
209
162
  end
210
163
  end
211
164
 
@@ -223,15 +176,15 @@ module Kobako
223
176
  raise UndefinedTargetError, e.message
224
177
  end
225
178
 
226
- # Encode +value+ as a +Response.ok+ envelope. When the value is not
227
- # wire-representable per the codec's type mapping, the
228
- # +UnsupportedType+ rescue routes it through the
229
- # Catalog::Handles via #wrap_as_handle and re-encodes with the Capability
230
- # Handle in place. The happy path encodes exactly once.
179
+ # Encode +value+ as the body of a Reply's ok arm — the value alone,
180
+ # since the envelope's tag already carries the success. A value that
181
+ # is not wire-representable per the codec's type mapping raises
182
+ # +UnsupportedTypeError+; the rescue routes it through the
183
+ # Catalog::Handles via #wrap_as_handle and re-encodes with the
184
+ # Capability Handle in place. The happy path encodes exactly once.
231
185
  def encode_ok(value, handler)
232
- response = Kobako::Transport::Response.ok(value)
233
- response.encode
234
- rescue Kobako::Codec::UnsupportedType
186
+ Kobako::Codec::Encoder.encode(value)
187
+ rescue Kobako::Codec::UnsupportedTypeError
235
188
  encode_ok(wrap_as_handle(value, handler), handler)
236
189
  end
237
190
 
@@ -244,11 +197,9 @@ module Kobako
244
197
 
245
198
  # +message+ folds to UTF-8 first: Ruby core builds some exception
246
199
  # messages as ASCII-8BIT (the arity ArgumentError, for one), and
247
- # the codec would ride those as bin — a shape the guest refuses.
248
- def encode_error(type, message)
249
- message = message.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
250
- fault = Kobako::Fault.new(type: type, message: message)
251
- Kobako::Transport::Response.error(fault).encode
200
+ # the envelope requires UTF-8 of the text fields it frames.
201
+ def fault(type, message)
202
+ [message.encode(Encoding::UTF_8, invalid: :replace, undef: :replace), type] # : [String, String]
252
203
  end
253
204
  end
254
205
  end
@@ -5,10 +5,9 @@ require_relative "../errors"
5
5
  module Kobako
6
6
  module Transport
7
7
  # +Kobako::SandboxError+ subclass raised when the host detects a
8
- # structural violation of the wire contract while decoding bytes
9
- # produced by the guest (a malformed Outcome envelope, a result body
10
- # that fails msgpack decode, a Panic envelope missing required
11
- # fields). Distinct from a Wasm trap (engine signalled the guest
8
+ # structural violation of the wire contract while reading what the
9
+ # guest produced — an invocation value the payload codec cannot
10
+ # decode. Distinct from a Wasm trap (engine signalled the guest
12
11
  # runtime is unrecoverable) and from a normal sandbox-layer failure
13
12
  # (the script raised but the protocol was respected): a
14
13
  # +Transport::Error+ always indicates the guest runtime is corrupted —
@@ -19,6 +18,23 @@ module Kobako
19
18
  # +rescue Kobako::SandboxError+ still catches it; callers that want
20
19
  # to distinguish wire-violation paths from script failures can
21
20
  # +rescue Kobako::Transport::Error+ directly.
22
- class Error < Kobako::SandboxError; end
21
+ class Error < Kobako::SandboxError
22
+ def initialize(message, diagnostic: nil, **)
23
+ super(message, **)
24
+ @diagnostic = diagnostic
25
+ end
26
+
27
+ # The codec fault behind this violation, appended to Ruby's own
28
+ # rendering. A caller cannot act on the inner "Symbol payload must
29
+ # be …" wording, so it stays out of #message; an operator
30
+ # triaging a corrupted runtime still needs it, and
31
+ # +detailed_message+ is where Ruby puts text of exactly that kind.
32
+ def detailed_message(...)
33
+ rendered = super
34
+ return rendered if @diagnostic.nil?
35
+
36
+ "#{rendered}\n#{@diagnostic}"
37
+ end
38
+ end
23
39
  end
24
40
  end
@@ -0,0 +1,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kobako
4
+ module Transport
5
+ # The reflection floor a guest→host dispatch must clear before the
6
+ # Dispatcher reaches +public_send+: which method names on a resolved
7
+ # target count as Service behaviour, and which are Ruby's ambient
8
+ # metaprogramming surface.
9
+ #
10
+ # Answers with a refusal reason rather than raising, so the error
11
+ # taxonomy stays with the Dispatcher and this module holds only the
12
+ # policy.
13
+ module Reflection
14
+ # Modules whose instance methods are ambient Ruby reflection /
15
+ # metaprogramming surface (+send+, +public_send+, +instance_eval+,
16
+ # +method+, +tap+, +instance_variable_get+, ...) rather than Service
17
+ # behaviour. A guest-supplied method name resolving to one of these is
18
+ # rejected: only methods the bound object itself exposes as Service
19
+ # behaviour are reachable, and +public_send(:send, ...)+ would
20
+ # otherwise let a guest pivot through +send+ into the private
21
+ # +Kernel#eval+ / +#system+ surface (host RCE).
22
+ META_OWNERS = [BasicObject, Kernel, Object, Module, Class].freeze
23
+ private_constant :META_OWNERS
24
+
25
+ # Callable gadget types whose own public methods are reflection surface
26
+ # (+Proc#binding+ reaches +Binding#eval+, +Method#receiver+ / +#unbind+
27
+ # hand back the underlying object) rather than Service behaviour. Only
28
+ # CALLABLE_ALLOW is reachable on a target of these types; a bound
29
+ # lambda stays invocable, its reflective surface does not.
30
+ GADGET_OWNERS = [Proc, Method, UnboundMethod, Binding].freeze
31
+ private_constant :GADGET_OWNERS
32
+
33
+ # The sole methods reachable on a GADGET_OWNERS target: invoking it
34
+ # (+call+ / +[]+ / +yield+) and the harmless +arity+ / +lambda?+
35
+ # describers that aid guest-side debugging.
36
+ CALLABLE_ALLOW = %i[call [] yield arity lambda?].freeze
37
+ private_constant :CALLABLE_ALLOW
38
+
39
+ module_function
40
+
41
+ # The reason +name+ is unreachable on +target+, or +nil+ when the
42
+ # dispatch may proceed. Composes the ambient-surface floor with the
43
+ # target's own opt-in narrowing, in that order: the predicate only
44
+ # narrows and can never re-open what the floor rejects.
45
+ def refusal(target, name)
46
+ ambient_refusal(target, name) || narrowing_refusal(target, name)
47
+ end
48
+
49
+ # Guard against ambient reflection methods. A public method whose
50
+ # owner is a META_OWNERS or GADGET_OWNERS module is rejected, except
51
+ # CALLABLE_ALLOW on a gadget target (a bound lambda stays invocable).
52
+ # A name with no concrete public method is allowed only when the
53
+ # target opts into it via +respond_to?+ (dynamic +method_missing+
54
+ # Services), since the dangerous methods are all concretely defined
55
+ # and therefore never reach that branch.
56
+ def ambient_refusal(target, name)
57
+ owner = target.public_method(name).owner
58
+ gadget = GADGET_OWNERS.include?(owner)
59
+ return nil unless META_OWNERS.include?(owner) || gadget
60
+ return nil if gadget && CALLABLE_ALLOW.include?(name)
61
+
62
+ "method #{name.inspect} is not a Service method"
63
+ rescue NameError
64
+ return nil if target.respond_to?(name)
65
+
66
+ "no public method #{name.inspect} on target"
67
+ end
68
+
69
+ # Consult the target's opt-in narrowing predicate. A bound object may
70
+ # define a private +respond_to_guest?(name)+ to restrict which of its
71
+ # methods the guest reaches; a falsy answer refuses the dispatch. It
72
+ # is consulted with the private surface included so the guest's
73
+ # +public_send+ dispatch can never reach +respond_to_guest?+ itself.
74
+ def narrowing_refusal(target, name)
75
+ return nil unless target.respond_to?(:respond_to_guest?, true)
76
+ return nil if target.__send__(:respond_to_guest?, name)
77
+
78
+ "method #{name.inspect} is not exposed to the guest"
79
+ end
80
+ end
81
+ end
82
+ end