kobako 0.30.0-aarch64-linux → 0.31.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 (94) hide show
  1. checksums.yaml +4 -4
  2. data/.release-please-manifest.json +1 -1
  3. data/CHANGELOG.md +335 -0
  4. data/README.md +43 -3
  5. data/ROADMAP.md +1 -1
  6. data/crates/kobako-runtime/CHANGELOG.md +219 -0
  7. data/crates/kobako-runtime/README.md +7 -4
  8. data/crates/kobako-transport/CHANGELOG.md +31 -0
  9. data/crates/kobako-transport/README.md +3 -4
  10. data/crates/kobako-wasmtime/CHANGELOG.md +161 -0
  11. data/crates/kobako-wasmtime/README.md +3 -2
  12. data/crates/kobako-wasmtime/wit/deps/cli.wit +233 -0
  13. data/crates/kobako-wasmtime/wit/deps/clocks.wit +162 -0
  14. data/crates/kobako-wasmtime/wit/deps/filesystem.wit +589 -0
  15. data/crates/kobako-wasmtime/wit/deps/http.wit +733 -0
  16. data/crates/kobako-wasmtime/wit/deps/io.wit +299 -0
  17. data/crates/kobako-wasmtime/wit/deps/random.wit +92 -0
  18. data/crates/kobako-wasmtime/wit/deps/sockets.wit +949 -0
  19. data/data/kobako.wasm +0 -0
  20. data/lib/kobako/3.3/kobako.so +0 -0
  21. data/lib/kobako/3.4/kobako.so +0 -0
  22. data/lib/kobako/4.0/kobako.so +0 -0
  23. data/lib/kobako/catalog/extensions.rb +14 -2
  24. data/lib/kobako/catalog/flags.rb +3 -5
  25. data/lib/kobako/catalog/grants.rb +5 -4
  26. data/lib/kobako/catalog/handles.rb +5 -27
  27. data/lib/kobako/catalog/mount.rb +11 -3
  28. data/lib/kobako/catalog/network.rb +35 -0
  29. data/lib/kobako/catalog/replacements.rb +28 -0
  30. data/lib/kobako/catalog/services.rb +5 -19
  31. data/lib/kobako/catalog/snippets.rb +3 -18
  32. data/lib/kobako/catalog.rb +3 -0
  33. data/lib/kobako/codec/{utils.rb → boundary.rb} +4 -2
  34. data/lib/kobako/codec/decoder.rb +4 -4
  35. data/lib/kobako/codec/ext_types.rb +3 -3
  36. data/lib/kobako/codec/handle_walk.rb +3 -43
  37. data/lib/kobako/codec/value_budget.rb +132 -40
  38. data/lib/kobako/codec.rb +1 -1
  39. data/lib/kobako/context.rb +24 -11
  40. data/lib/kobako/errors.rb +15 -12
  41. data/lib/kobako/extension.rb +3 -2
  42. data/lib/kobako/filesystem.rb +9 -2
  43. data/lib/kobako/handle.rb +2 -2
  44. data/lib/kobako/names.rb +28 -0
  45. data/lib/kobako/network.rb +210 -0
  46. data/lib/kobako/outcome.rb +7 -7
  47. data/lib/kobako/pool.rb +45 -23
  48. data/lib/kobako/runtime.rb +3 -2
  49. data/lib/kobako/sandbox.rb +92 -35
  50. data/lib/kobako/sandbox_options.rb +41 -106
  51. data/lib/kobako/transport/argument_wrap.rb +64 -0
  52. data/lib/kobako/transport/block_failure.rb +1 -1
  53. data/lib/kobako/transport/dispatcher.rb +6 -6
  54. data/lib/kobako/transport/exposure.rb +26 -15
  55. data/lib/kobako/transport/reflection.rb +21 -4
  56. data/lib/kobako/transport/run.rb +8 -23
  57. data/lib/kobako/transport/yielder.rb +2 -9
  58. data/lib/kobako/transport.rb +1 -0
  59. data/lib/kobako/version.rb +1 -1
  60. data/lib/kobako.rb +6 -2
  61. data/release-please-config.json +15 -0
  62. data/sig/core/thread.rbs +6 -0
  63. data/sig/kobako/catalog/extensions.rbs +2 -0
  64. data/sig/kobako/catalog/grants.rbs +7 -4
  65. data/sig/kobako/catalog/handles.rbs +0 -2
  66. data/sig/kobako/catalog/mount.rbs +3 -1
  67. data/sig/kobako/catalog/network.rbs +20 -0
  68. data/sig/kobako/catalog/replacements.rbs +14 -0
  69. data/sig/kobako/catalog/services.rbs +0 -4
  70. data/sig/kobako/catalog/snippets.rbs +0 -2
  71. data/sig/kobako/codec/{utils.rbs → boundary.rbs} +2 -2
  72. data/sig/kobako/codec/handle_walk.rbs +0 -6
  73. data/sig/kobako/codec/value_budget.rbs +47 -4
  74. data/sig/kobako/context.rbs +3 -1
  75. data/sig/kobako/errors.rbs +4 -4
  76. data/sig/kobako/filesystem.rbs +21 -3
  77. data/sig/kobako/network.rbs +115 -0
  78. data/sig/kobako/outcome.rbs +1 -1
  79. data/sig/kobako/pool.rbs +7 -3
  80. data/sig/kobako/runtime.rbs +32 -3
  81. data/sig/kobako/sandbox.rbs +19 -2
  82. data/sig/kobako/sandbox_options.rbs +29 -38
  83. data/sig/kobako/transport/argument_wrap.rbs +15 -0
  84. data/sig/kobako/transport/error.rbs +1 -1
  85. data/sig/kobako/transport/exposure.rbs +2 -4
  86. data/sig/kobako/transport/reflection.rbs +10 -0
  87. data/sig/kobako/transport/run.rbs +0 -2
  88. data/sig/kobako/transport/yielder.rbs +0 -3
  89. data/sig/kobako/transport.rbs +1 -1
  90. data/sig/kobako.rbs +13 -0
  91. metadata +23 -9
  92. data/crates/kobako-runtime/tests/linux_baseline/linux-baseline-expected.txt +0 -16
  93. data/lib/kobako/constant_name.rb +0 -8
  94. data/sig/kobako/constant_name.rbs +0 -3
@@ -41,9 +41,9 @@ module Kobako
41
41
  # The fields land on the exception verbatim — it carries the record
42
42
  # rather than a translation of one.
43
43
  def panic_error(panic, entrypoint)
44
- origin, klass, message, backtrace, available = panic
45
- selected = error_class(origin, klass)
46
- attribution = { origin: origin, klass: klass, backtrace_lines: backtrace }
44
+ origin, class_name, message, backtrace, available = panic
45
+ selected = error_class(origin, class_name)
46
+ attribution = { origin: origin, class_name: class_name, backtrace_lines: backtrace }
47
47
  return selected.new(message, **attribution) unless selected == UndefinedEntrypointError
48
48
 
49
49
  UndefinedEntrypointError.new(message, name: entrypoint, available: available.map(&:to_sym), **attribution)
@@ -54,9 +54,9 @@ module Kobako
54
54
  # naming a class outside the branch its origin chose is ignored rather
55
55
  # than honoured: what a guest calls its exception must not move the
56
56
  # failure to a layer the attribution did not put it in.
57
- def error_class(origin, klass)
57
+ def error_class(origin, class_name)
58
58
  base = origin == ORIGIN_SERVICE ? ServiceError : SandboxError
59
- selected = SUBCLASSES.fetch(klass, base)
59
+ selected = SUBCLASSES.fetch(class_name, base)
60
60
  return base unless selected <= base
61
61
 
62
62
  selected
@@ -71,12 +71,12 @@ module Kobako
71
71
  end
72
72
 
73
73
  # No guest class stands behind a result kobako cannot decode, so
74
- # +klass+ names the host class raised.
74
+ # +class_name+ names the host class raised.
75
75
  def wire_error(message, diagnostic: nil)
76
76
  Kobako::Transport::Error.new(
77
77
  message,
78
78
  origin: ORIGIN_SANDBOX,
79
- klass: "Kobako::Transport::Error",
79
+ class_name: "Kobako::Transport::Error",
80
80
  diagnostic: diagnostic
81
81
  )
82
82
  end
data/lib/kobako/pool.rb CHANGED
@@ -7,21 +7,29 @@ module Kobako
7
7
  # A bounded set of warm, identically set-up Sandboxes, handed out to one
8
8
  # holder at a time. Every Sandbox it builds is kept: an invocation leaves
9
9
  # nothing behind, whatever ended it.
10
+ #
11
+ # Deprecated: the next release removes Pool. A Sandbox keeps nothing
12
+ # between runs, so Threads share one Sandbox instead.
10
13
  class Pool
11
14
  # The default +checkout_timeout+: 5 seconds.
12
15
  DEFAULT_CHECKOUT_TIMEOUT_SECONDS = 5.0
16
+ # What building a Pool warns while deprecation warnings are shown.
17
+ DEPRECATION = "Kobako::Pool is deprecated, removed next release; share a Kobako::Sandbox across Threads"
18
+ private_constant :DEPRECATION
13
19
 
14
- # Build a Pool of up to +slots+ Sandboxes, built on first demand with the
20
+ # Build a Pool of up to +size+ Sandboxes, built on first demand with the
15
21
  # other keywords as Sandbox.new takes them. +checkout_timeout+ bounds how
16
22
  # many seconds #with waits, and +nil+ waits indefinitely. The block, if
17
23
  # given, sets up each Sandbox once, as with Sandbox#bind and
18
24
  # Sandbox#preload.
19
25
  #
20
- # Raises ArgumentError when +slots+ is not a positive Integer or
21
- # +checkout_timeout+ is not a positive finite number.
22
- def initialize(slots:, checkout_timeout: DEFAULT_CHECKOUT_TIMEOUT_SECONDS, **sandbox_options, &setup)
23
- validate_slots(slots)
24
- @slots = slots
26
+ # Raises TypeError when +size+ is not an Integer or +checkout_timeout+
27
+ # is not Numeric, and ArgumentError when either is not positive or
28
+ # +checkout_timeout+ is not finite.
29
+ def initialize(size:, checkout_timeout: DEFAULT_CHECKOUT_TIMEOUT_SECONDS, **sandbox_options, &setup)
30
+ warn(DEPRECATION, category: :deprecated, uplevel: 1)
31
+ validate_size(size)
32
+ @size = size
25
33
  @checkout_timeout = normalize_checkout_timeout(checkout_timeout)
26
34
  @sandbox_options = sandbox_options
27
35
  @setup = setup
@@ -35,12 +43,18 @@ module Kobako
35
43
  # block's value; the Sandbox returns to the pool however the block
36
44
  # exits. Raises PoolTimeoutError once every slot has stayed held past
37
45
  # +checkout_timeout+.
46
+ #
47
+ # An interrupt reaches the checkout only while it waits or builds, and
48
+ # the block as it runs, as connection_pool's +with+ does, so none lands
49
+ # between taking a Sandbox and handing it back.
38
50
  def with
39
- sandbox = acquire
40
- begin
41
- yield sandbox
42
- ensure
43
- checkin(sandbox)
51
+ Thread.handle_interrupt(Exception => :never) do
52
+ sandbox = acquire
53
+ begin
54
+ Thread.handle_interrupt(Exception => :immediate) { yield sandbox }
55
+ ensure
56
+ checkin(sandbox)
57
+ end
44
58
  end
45
59
  end
46
60
 
@@ -64,7 +78,7 @@ module Kobako
64
78
  @mutex.synchronize do
65
79
  return [:idle, @idle.pop] unless @idle.empty?
66
80
 
67
- if @constructed < @slots
81
+ if @constructed < @size
68
82
  @constructed += 1
69
83
  return [:build, nil]
70
84
  end
@@ -79,35 +93,42 @@ module Kobako
79
93
  remaining = deadline && (deadline - monotonic_now)
80
94
  if remaining && remaining <= 0
81
95
  raise PoolTimeoutError,
82
- "no Sandbox returned within #{@checkout_timeout}s: all #{@slots} slots are held"
96
+ "no Sandbox returned within #{@checkout_timeout}s: all #{@size} Sandboxes are held"
83
97
  end
84
98
 
85
- @slot_freed.wait(@mutex, remaining)
99
+ Thread.handle_interrupt(Exception => :immediate) { @slot_freed.wait(@mutex, remaining) }
86
100
  end
87
101
 
88
102
  # A failed construction releases its reserved capacity so a later
89
- # checkout can retry.
103
+ # checkout can retry. Setup closes registration, so each holder gets
104
+ # the Sandbox as the setup block left it.
90
105
  def construct_slot
91
106
  done = false
92
- sandbox = Sandbox.new(**@sandbox_options)
93
- @setup&.call(sandbox)
107
+ sandbox = Thread.handle_interrupt(Exception => :immediate) { build_slot }
94
108
  done = true
95
109
  sandbox
96
110
  ensure
97
111
  release_capacity unless done
98
112
  end
99
113
 
114
+ def build_slot
115
+ sandbox = Sandbox.new(**@sandbox_options)
116
+ @setup&.call(sandbox)
117
+ sandbox.send(:seal, "on a pooled Sandbox once its setup ran")
118
+ sandbox
119
+ end
120
+
100
121
  def checkin(sandbox)
101
122
  @mutex.synchronize do
102
123
  @idle.push(sandbox)
103
- @slot_freed.signal
124
+ @slot_freed.broadcast
104
125
  end
105
126
  end
106
127
 
107
128
  def release_capacity
108
129
  @mutex.synchronize do
109
130
  @constructed -= 1
110
- @slot_freed.signal
131
+ @slot_freed.broadcast
111
132
  end
112
133
  end
113
134
 
@@ -117,16 +138,17 @@ module Kobako
117
138
  Process.clock_gettime(Process::CLOCK_MONOTONIC)
118
139
  end
119
140
 
120
- def validate_slots(slots)
121
- return if slots.is_a?(Integer) && slots.positive?
141
+ def validate_size(size)
142
+ raise TypeError, "size must be an Integer, got #{size.class}" unless size.is_a?(Integer)
143
+ return if size.positive?
122
144
 
123
- raise ArgumentError, "slots must be a positive Integer, got #{slots.inspect}"
145
+ raise ArgumentError, "size must be a positive Integer, got #{size.inspect}"
124
146
  end
125
147
 
126
148
  def normalize_checkout_timeout(checkout_timeout)
127
149
  return nil if checkout_timeout.nil?
128
150
  unless checkout_timeout.is_a?(Numeric)
129
- raise ArgumentError, "checkout_timeout must be Numeric or nil, got #{checkout_timeout.inspect}"
151
+ raise TypeError, "checkout_timeout must be Numeric or nil, got #{checkout_timeout.inspect}"
130
152
  end
131
153
 
132
154
  seconds = checkout_timeout.to_f
@@ -1,8 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Kobako
4
- # The native wasmtime runtime, defined by the ext; this file adds only the
5
- # default Guest Binary path.
4
+ # The Ruby handle of the contract Runtime a Sandbox runs each invocation
5
+ # on, defined by the ext; this file adds only the default Guest Binary
6
+ # path.
6
7
  class Runtime # :nodoc:
7
8
  # The path is answered whether or not the file exists; from_path is
8
9
  # where a missing artifact is refused. A missing +__dir__+ raises
@@ -25,18 +25,19 @@ module Kobako
25
25
  attr_reader :options
26
26
 
27
27
  def_delegators :@options, :timeout, :setup_timeout, :memory_limit, :stdout_limit, :stderr_limit,
28
- :open_file_limit, :profile, :gvl
28
+ :open_file_limit, :open_connection_limit, :connection_limit, :profile, :gvl
29
29
 
30
30
  # Build a Sandbox on the Guest Binary at +wasm_path+, the one bundled
31
31
  # with the gem by default. The other keywords are the options
32
32
  # SandboxOptions describes.
33
33
  #
34
- # Raises ArgumentError for an invalid option, and SetupError when the
35
- # runtime cannot be built or provides less isolation than +profile+ asks
36
- # for.
34
+ # Raises TypeError for an option of another class, RangeError for a cap
35
+ # past what the host counts, ArgumentError for any other invalid option,
36
+ # and SetupError when the runtime cannot be built or provides less
37
+ # isolation than +profile+ asks for.
37
38
  def initialize(wasm_path: nil, **)
38
39
  @wasm_path = wasm_path || Kobako::Runtime.default_path
39
- @options = SandboxOptions.new(**)
40
+ @options = SandboxOptions.new(**Kobako::Runtime.default_options, **)
40
41
  @services = Kobako::Catalog::Services.new
41
42
  @snippets = Catalog::Snippets.new
42
43
  @flags = Catalog::Flags.new
@@ -58,9 +59,10 @@ module Kobako
58
59
  # the constant, and Context#bind supplies the object for each invocation.
59
60
  # A call to one left unfilled fails as a ServiceError.
60
61
  #
61
- # Raises ArgumentError for a malformed path, a path under the reserved
62
- # +Kobako+ namespace, a path that collides with an existing binding, or a
63
- # call after the first invocation.
62
+ # Raises TypeError for a path that is no Symbol or String, ArgumentError
63
+ # for a malformed path, a path under the reserved
64
+ # +Kobako+ namespace, or a path that collides with an existing binding,
65
+ # and FrozenError for a call after the first invocation.
64
66
  def bind(path, object = Unresolved)
65
67
  refuse_once_invoked("bind")
66
68
  @services.bind(path, object)
@@ -71,8 +73,9 @@ module Kobako
71
73
  # backend. Any object answering +name+, +source+, +backend+ and
72
74
  # +depends_on+ works; Extension is the bundled one. Returns +self+.
73
75
  #
74
- # Raises ArgumentError for a malformed Extension, a call after the first
75
- # invocation, or, at the first invocation, a missing dependency.
76
+ # Raises TypeError for an Extension of another shape, FrozenError for a
77
+ # call after the first invocation, and, at the first invocation,
78
+ # ArgumentError for a missing dependency.
76
79
  def install(*extensions)
77
80
  refuse_once_invoked("install")
78
81
 
@@ -92,19 +95,39 @@ module Kobako
92
95
  # or a StandardError, fails that call as <tt>Errno::EACCES</tt> in the
93
96
  # guest and leaves the script running.
94
97
  #
95
- # A path may sit beneath another mount, and the guest reaches the
96
- # innermost one.
98
+ # A path may sit beneath another mount, standing where Linux's +mount+
99
+ # would place it, and a run fails where Linux would refuse it.
97
100
  #
98
101
  # Raises TypeError for a path that is no String or something other than
99
- # a Filesystem, and ArgumentError for a malformed or duplicate path, an
100
- # unknown access, or a call after the first invocation.
102
+ # a Filesystem, ArgumentError for a malformed or duplicate path or an
103
+ # unknown access, and FrozenError for a call after the first invocation.
101
104
  def mount(at, filesystem, access: :read, &policy)
102
105
  refuse_once_invoked("mount")
103
- Runtime.validate_mount(at, access, filesystem)
104
106
  @grants.register(Catalog::Mount.new(at: at, access: access, filesystem: filesystem, policy: policy))
105
107
  self
106
108
  end
107
109
 
110
+ # Give the guest the network entry +entry+ under +name+, any object
111
+ # answering any of +endpoints+, +credentials+, +resolve?+, +connect?+, and
112
+ # +request?+. A given block yields a Kobako::Network::Builder adding to
113
+ # +entry+, so the block's +self+ stays the caller's. Each entry's endpoints
114
+ # and credentials are read afresh for every invocation. Its +resolve?+ is
115
+ # handed each name the guest looks up, its +connect?+ each
116
+ # Kobako::Network::Connection, and its +request?+ each
117
+ # Kobako::Network::Request; any entry refusing refuses. Returns +self+.
118
+ #
119
+ # Raises TypeError for a name that is no Symbol or String, ArgumentError
120
+ # for an empty or duplicate name, an endpoint with an
121
+ # empty host, a port outside 1 to 65535, or an unknown protocol, and
122
+ # FrozenError for a call after the first invocation. An
123
+ # endpoint the ruleset refuses, such as a wildcard leading to +:private+,
124
+ # raises ArgumentError from the invocation that compiles it.
125
+ def network(name, entry = nil, &builder)
126
+ refuse_once_invoked("network")
127
+ @grants.register(Catalog::Network.new(name: name, entry: entry, &builder))
128
+ self
129
+ end
130
+
108
131
  # Register a snippet that every invocation runs, in the order registered,
109
132
  # before its own code. Returns +self+.
110
133
  #
@@ -114,8 +137,9 @@ module Kobako
114
137
  # Precompiled RITE bytecode, trusted as host code: the unmodified
115
138
  # compiler output of the mruby release the Guest Binary is built on.
116
139
  #
117
- # Raises ArgumentError for a malformed or duplicate snippet, or a call
118
- # after the first invocation. A snippet that fails to load fails every
140
+ # Raises TypeError for a snippet part of another class, ArgumentError for
141
+ # a malformed or duplicate snippet, and FrozenError for a call after the
142
+ # first invocation. A snippet that fails to load fails every
119
143
  # invocation with SandboxError, or BytecodeError for bytecode.
120
144
  def preload(code: nil, name: nil, binary: nil)
121
145
  refuse_once_invoked("preload")
@@ -131,8 +155,8 @@ module Kobako
131
155
  # Mark a flag advisory only when a script cannot tell it was skipped.
132
156
  # Returns +self+.
133
157
  #
134
- # Raises ArgumentError for a malformed or duplicate flag, or a call after
135
- # the first invocation.
158
+ # Raises TypeError for a name or value of another class, ArgumentError for
159
+ # a duplicate flag, and FrozenError for a call after the first invocation.
136
160
  def flag(name, value = "", advisory: false)
137
161
  refuse_once_invoked("flag")
138
162
 
@@ -144,9 +168,11 @@ module Kobako
144
168
  # and +kwargs+, and return the Execution. A given block receives the
145
169
  # invocation's Context before the guest runs.
146
170
  #
147
- # Raises TypeError when +target+ is not a Symbol or String, and
148
- # ArgumentError when it is not a constant name or the arguments carry a
149
- # Handle or a non-Symbol keyword. A failed run raises as #eval does.
171
+ # Raises TypeError when +target+ is not a Symbol or String, a keyword is
172
+ # not a Symbol, or an argument holds a Hash key or a reflective object
173
+ # that cannot cross, and ArgumentError when +target+ is not a constant
174
+ # name, the arguments carry a Handle, or an argument nests past what the
175
+ # wire carries. A failed run raises as #eval does.
150
176
  def run(target, *args, **kwargs, &block)
151
177
  request = Transport::Run.new(entrypoint: target, args: args, kwargs: kwargs)
152
178
  Codec.within_value_budget(@options.value_budget) { begin_invocation.run(request, &block) }
@@ -156,25 +182,25 @@ module Kobako
156
182
  # whose +value+ is the last expression. A given block receives the
157
183
  # invocation's Context before the guest runs.
158
184
  #
159
- # Raises TrapError when the engine stopped the guest, a deadline or
160
- # memory budget included; SandboxError when the guest failed, +code+ not
161
- # being a String or the Guest Binary not starting the run included; and
162
- # ServiceError when a Service call failed and the guest left it
185
+ # Raises TypeError when +code+ is no String, and ArgumentError when it is
186
+ # not UTF-8 text, before the guest runs; TrapError when the engine
187
+ # stopped the guest, a deadline or memory budget included; SandboxError
188
+ # when the guest failed, the Guest Binary not starting the run included;
189
+ # and ServiceError when a Service call failed and the guest left it
163
190
  # unrescued.
164
191
  def eval(code, &block)
165
- raise SandboxError, "code must be a String, got #{code.class}" unless code.is_a?(String)
192
+ raise TypeError, "code must be a String, got #{code.class}" unless code.is_a?(String)
166
193
 
167
- Codec.within_value_budget(@options.value_budget) { begin_invocation.eval(code, &block) }
194
+ source = code.dup.force_encoding(Encoding::UTF_8)
195
+ raise ArgumentError, "code must be UTF-8 text" unless source.valid_encoding?
196
+
197
+ Codec.within_value_budget(@options.value_budget) { begin_invocation.eval(source, &block) }
168
198
  end
169
199
 
170
200
  private
171
201
 
172
- # A runtime whose declared posture falls below the request never runs
173
- # guest code.
174
202
  def build_runtime
175
- runtime = Kobako::Runtime.from_path(@wasm_path, **@options.to_h)
176
- @options.enforce_floor(runtime.profile)
177
- runtime
203
+ Kobako::Runtime.from_path(@wasm_path, **@options.to_h)
178
204
  end
179
205
 
180
206
  # The one place the Preamble's parts are put together, for a compile
@@ -186,7 +212,12 @@ module Kobako
186
212
  # Registration closes at the first invocation, so every invocation ships
187
213
  # the same Services, snippets, flags, Extensions and mounts.
188
214
  def refuse_once_invoked(verb)
189
- raise ArgumentError, "cannot #{verb} after first Sandbox invocation" if @sealed
215
+ raise FrozenError, "cannot #{verb} #{@sealed}" if @sealed
216
+ end
217
+
218
+ # Close registration, saying why for the refusal that follows.
219
+ def seal(reason)
220
+ @sealed = reason
190
221
  end
191
222
 
192
223
  # Sealing before the dependency check keeps a Sandbox whose check failed
@@ -195,11 +226,37 @@ module Kobako
195
226
  # the Context it answers, so nothing an invocation does is written back
196
227
  # onto the shared config.
197
228
  def begin_invocation
198
- @sealed = true
229
+ warn_release_on_main_thread
230
+ seal("after first Sandbox invocation")
199
231
  @extensions.assert_dependencies
200
232
  @snippets.compile { |entries| @runtime.compile(preamble(entries)) }
201
233
  Context.new(runtime: @runtime, services: @services, extensions: @extensions, grants: @grants,
202
234
  preamble: preamble(@snippets.entries))
203
235
  end
236
+
237
+ # Ruby runs a signal's trap handler, and a Ractor's +require+, on the main
238
+ # Thread alone, and either raising as a run releasing the GVL takes it back
239
+ # after a Service call leaves the run where it cannot unwind. The first such
240
+ # run warns once.
241
+ def warn_release_on_main_thread
242
+ MainThreadRelease.warn_once if @options.gvl == :release && Thread.current == Thread.main
243
+ end
244
+
245
+ # The process's one warning that a run releasing the GVL ran on the main
246
+ # Thread.
247
+ module MainThreadRelease
248
+ MESSAGE = "Kobako::Sandbox with gvl: :release runs on the main Thread, where a trap handler " \
249
+ "that raises or exits, or another Ractor's require, can stop the run where it cannot " \
250
+ "unwind; run it on another Thread, or keep trap handlers to setting a flag"
251
+ @warned = false
252
+
253
+ def self.warn_once
254
+ return if @warned
255
+
256
+ @warned = true
257
+ warn(MESSAGE)
258
+ end
259
+ end
260
+ private_constant :MainThreadRelease
204
261
  end
205
262
  end
@@ -4,122 +4,57 @@ require_relative "errors"
4
4
 
5
5
  module Kobako
6
6
  # The options a Sandbox was built with, read through Sandbox#options or
7
- # directly on the Sandbox, as in Sandbox#timeout. A cap left out takes its
8
- # default, and +nil+ switches it off.
7
+ # directly on the Sandbox, as in Sandbox#timeout. An option Sandbox.new
8
+ # leaves out takes the runtime's default, given below, and +nil+ switches a
9
+ # cap off.
9
10
  #
10
- # [+timeout+] Float seconds one invocation may run.
11
+ # [+timeout+] Float seconds one invocation may run; 60.
11
12
  # [+setup_timeout+] Float seconds the Guest Binary may take to be set up
12
- # the first time its path is loaded.
13
- # [+memory_limit+] Integer bytes one invocation may grow guest memory by.
13
+ # the first time its path is loaded; 10.
14
+ # [+memory_limit+] Integer bytes one invocation may grow guest memory by;
15
+ # 4 MiB.
14
16
  # [+stdout_limit+, +stderr_limit+]
15
- # Integer bytes kept from each output channel.
17
+ # Integer bytes kept from each output channel; 1 MiB.
16
18
  # [+open_file_limit+]
17
19
  # Integer descriptors one invocation may hold open, the
18
- # standard ones and each Mount's included.
19
- # [+profile+] The isolation the runtime must provide, one of PROFILES.
20
- # [+gvl+] How an invocation holds Ruby's GVL, one of GVL_MODES.
20
+ # standard ones and each outermost mount's included; 1024.
21
+ # [+open_connection_limit+]
22
+ # Integer connections one invocation holds open at once, each
23
+ # socket once it dials, HTTP request, and name lookup in
24
+ # flight one; 6.
25
+ # [+connection_limit+]
26
+ # Integer connections one invocation makes in all, each
27
+ # socket's dial and HTTP request one; 50.
28
+ # [+profile+] The isolation the runtime must provide at least:
29
+ # +:hermetic+, which denies the guest the clock and
30
+ # entropy, or the weaker +:permissive+, which leaves them
31
+ # live; +:hermetic+.
32
+ # [+gvl+] How an invocation holds Ruby's GVL: +:hold+ through
33
+ # the invocation, or +:release+ while the guest runs, so
34
+ # Sandboxes on different Threads run in parallel; +:hold+.
35
+ # [+network+] What the guest's network dials and looks names up
36
+ # through, beneath every rule its entries make: +nil+
37
+ # for the host's own, or a Kobako::Network::Mock a test
38
+ # writes; +nil+.
21
39
  #
22
- # Raises ArgumentError for a value outside these shapes, and SetupError
23
- # when the runtime provides less isolation than +profile+ asks for.
40
+ # Raises TypeError for a cap of another class, RangeError for one past
41
+ # what the host counts, and ArgumentError for another value outside these
42
+ # shapes. The runtime judges every cap, and +profile+, +gvl+, and
43
+ # +network+ as Sandbox.new builds it.
24
44
  class SandboxOptions < Data.define(:timeout, :setup_timeout, :memory_limit, :stdout_limit, :stderr_limit,
25
- :open_file_limit, :profile, :gvl)
26
- # The default +timeout+: 60 seconds.
27
- DEFAULT_TIMEOUT_SECONDS = 60.0
28
-
29
- # The default +setup_timeout+: 10 seconds.
30
- DEFAULT_SETUP_TIMEOUT_SECONDS = 10.0
31
-
32
- # The default +memory_limit+: 4 MiB of growth past the guest's starting
33
- # memory, sized for a guest whose every value takes 16 bytes.
34
- DEFAULT_MEMORY_LIMIT = 4 << 20
35
-
36
- # The default +stdout_limit+ and +stderr_limit+: 1 MiB each.
37
- DEFAULT_OUTPUT_LIMIT = 1 << 20
38
-
39
- # The default +open_file_limit+: 1024, the soft limit Linux gives a
40
- # process.
41
- DEFAULT_OPEN_FILE_LIMIT = 1024
42
-
43
- # The isolation profiles, weakest first. +:hermetic+ denies the guest the
44
- # clock and entropy; +:permissive+ leaves them live.
45
- PROFILES = %i[permissive hermetic].freeze
46
-
47
- # The default +profile+, the strictest.
48
- DEFAULT_PROFILE = :hermetic
49
-
50
- # +:hold+ keeps the GVL through the invocation; +:release+ drops it while
51
- # the guest runs, so Sandboxes on different Threads run in parallel.
52
- GVL_MODES = %i[hold release].freeze
53
-
54
- # The default +gvl+, +:hold+.
55
- DEFAULT_GVL = :hold
56
-
57
- def initialize(timeout: DEFAULT_TIMEOUT_SECONDS,
58
- setup_timeout: DEFAULT_SETUP_TIMEOUT_SECONDS,
59
- memory_limit: DEFAULT_MEMORY_LIMIT,
60
- stdout_limit: DEFAULT_OUTPUT_LIMIT,
61
- stderr_limit: DEFAULT_OUTPUT_LIMIT,
62
- open_file_limit: DEFAULT_OPEN_FILE_LIMIT,
63
- profile: DEFAULT_PROFILE,
64
- gvl: DEFAULT_GVL)
65
- timeout = normalize_timeout(timeout, "timeout")
66
- setup_timeout = normalize_timeout(setup_timeout, "setup_timeout")
67
- memory_limit = normalize_limit(memory_limit, "memory_limit")
68
- stdout_limit = normalize_limit(stdout_limit, "stdout_limit")
69
- stderr_limit = normalize_limit(stderr_limit, "stderr_limit")
70
- open_file_limit = normalize_limit(open_file_limit, "open_file_limit")
71
- profile = normalize_choice(profile, PROFILES, "profile")
72
- gvl = normalize_choice(gvl, GVL_MODES, "gvl")
73
- super
45
+ :open_file_limit, :open_connection_limit, :connection_limit, :profile, :gvl,
46
+ :network)
47
+ # Every option is required; Sandbox.new fills each one left out from
48
+ # the runtime's defaults.
49
+ def initialize(timeout:, setup_timeout:, memory_limit:, stdout_limit:, stderr_limit:, open_file_limit:,
50
+ open_connection_limit:, connection_limit:, profile:, gvl:, network:)
51
+ caps = Kobako::Runtime.normalize_caps({ timeout:, setup_timeout:, memory_limit:, stdout_limit:, stderr_limit:,
52
+ open_file_limit:, open_connection_limit:, connection_limit: })
53
+ super(**caps.merge(profile:, gvl:, network:))
74
54
  end
75
55
 
76
- # The least guest memory one value occupies, so a guest payload may hold
77
- # one value for each of these bytes of +memory_limit+.
78
- VALUE_BYTES = 16
79
- private_constant :VALUE_BYTES
80
-
81
56
  def value_budget # :nodoc:
82
- memory_limit&./(VALUE_BYTES)
83
- end
84
-
85
- # Both fallbacks fail closed: an unknown declaration ranks below every
86
- # request, and an unknown request refuses every declaration.
87
- def enforce_floor(declared) # :nodoc:
88
- return if (PROFILES.index(declared) || -1) >= (PROFILES.index(profile) || PROFILES.size)
89
-
90
- raise Kobako::SetupError, "runtime declares isolation profile #{declared.inspect}, " \
91
- "below the requested floor #{profile.inspect}"
92
- end
93
-
94
- private
95
-
96
- # A zero or negative timeout would either fire instantly or never, both
97
- # more surprising than an early ArgumentError.
98
- def normalize_timeout(timeout, name)
99
- return nil if timeout.nil?
100
- raise ArgumentError, "#{name} must be Numeric or nil, got #{timeout.class}" unless timeout.is_a?(Numeric)
101
-
102
- seconds = timeout.to_f
103
- raise ArgumentError, "#{name} must be > 0 (got #{timeout})" unless seconds.positive? && seconds.finite?
104
-
105
- seconds
106
- end
107
-
108
- def normalize_limit(limit, name)
109
- return nil if limit.nil?
110
- unless limit.is_a?(Integer) && limit.positive?
111
- raise ArgumentError, "#{name} must be a positive Integer or nil, got #{limit.inspect}"
112
- end
113
-
114
- limit
115
- end
116
-
117
- # Unlike the caps there is no +nil+ form: every choice, the weakest
118
- # included, is requested by name, as in +:permissive+.
119
- def normalize_choice(value, choices, name)
120
- return value if choices.include?(value)
121
-
122
- raise ArgumentError, "#{name} must be one of #{choices.map(&:inspect).join(", ")}, got #{value.inspect}"
57
+ Kobako::Runtime.value_budget_of(memory_limit)
123
58
  end
124
59
  end
125
60
  end
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../codec"
4
+ require_relative "exposure"
5
+
6
+ module Kobako
7
+ module Transport
8
+ # The walk a #run argument takes on its way to the guest: a leaf with no
9
+ # wire form becomes a Capability Handle in the invocation's table, and
10
+ # the rest crosses as it stands. An argument the walk refuses is the
11
+ # Host App's mistake, raised as +Marshal.dump+ raises it: +TypeError+
12
+ # for what has no form to cross as, +ArgumentError+ past the depth.
13
+ module ArgumentWrap # :nodoc:
14
+ # Only Hash values are wrapped: a non-representable key raises rather
15
+ # than crossing as a token the guest→host restore walk could not
16
+ # round-trip.
17
+ def self.wrap(value, handles, depth = 0)
18
+ refuse_past_nesting(depth)
19
+ case value
20
+ when ::Array then value.map { |element| wrap(element, handles, depth + 1) }
21
+ when ::Hash then wrap_hash(value, handles, depth)
22
+ else
23
+ Codec::HandleWalk.representable?(value) ? value : wrap_leaf(value, handles)
24
+ end
25
+ end
26
+
27
+ class << self
28
+ private
29
+
30
+ # A reference cycle necessarily trips the nesting bound, so an
31
+ # argument fails as a clean +ArgumentError+ rather than an unbounded
32
+ # host recursion.
33
+ def refuse_past_nesting(depth)
34
+ return unless depth > Codec::MAX_NESTING_DEPTH
35
+
36
+ raise ArgumentError,
37
+ "a #run argument nests deeper than #{Codec::MAX_NESTING_DEPTH} levels within the Run payload " \
38
+ "and cannot cross the sandbox boundary (possible reference cycle)"
39
+ end
40
+
41
+ def wrap_leaf(value, handles)
42
+ refused = Exposure.refused_class_of(value)
43
+ raise TypeError, "a #{refused} cannot cross as a Capability Handle" if refused
44
+
45
+ handles.alloc(value)
46
+ end
47
+
48
+ # A stateful object may cross the boundary as a Hash value but not as
49
+ # a key — the one deliberate asymmetry with the guest→host restore
50
+ # walk, which resolves Handle keys the guest built.
51
+ def wrap_hash(hash, handles, depth)
52
+ hash.to_h do |key, val|
53
+ unless Codec::HandleWalk.representable?(key, depth + 1)
54
+ raise TypeError,
55
+ "a Hash passed to #run has a key that cannot cross the sandbox boundary " \
56
+ "(#{key.class}); only wire-representable values may be Hash keys"
57
+ end
58
+ [key, wrap(val, handles, depth + 1)]
59
+ end
60
+ end
61
+ end
62
+ end
63
+ end
64
+ end
@@ -28,7 +28,7 @@ module Kobako
28
28
  raised = @raised
29
29
  return if raised.nil? || !error.equal?(raised)
30
30
 
31
- "#{raised.klass}: #{raised.message}"
31
+ "#{raised.class_name}: #{raised.message}"
32
32
  end
33
33
  end
34
34
  end