kobako 0.30.0-aarch64-linux → 0.32.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 (101) hide show
  1. checksums.yaml +4 -4
  2. data/.githooks/linux-tests.sh +29 -0
  3. data/.release-please-manifest.json +1 -1
  4. data/CHANGELOG.md +460 -0
  5. data/README.md +43 -4
  6. data/ROADMAP.md +1 -2
  7. data/crates/kobako-runtime/CHANGELOG.md +309 -0
  8. data/crates/kobako-runtime/README.md +7 -4
  9. data/crates/kobako-transport/CHANGELOG.md +38 -0
  10. data/crates/kobako-transport/README.md +3 -4
  11. data/crates/kobako-wasmtime/CHANGELOG.md +208 -0
  12. data/crates/kobako-wasmtime/README.md +4 -3
  13. data/crates/kobako-wasmtime/wit/deps/cli.wit +233 -0
  14. data/crates/kobako-wasmtime/wit/deps/clocks.wit +162 -0
  15. data/crates/kobako-wasmtime/wit/deps/filesystem.wit +589 -0
  16. data/crates/kobako-wasmtime/wit/deps/http.wit +733 -0
  17. data/crates/kobako-wasmtime/wit/deps/io.wit +299 -0
  18. data/crates/kobako-wasmtime/wit/deps/random.wit +92 -0
  19. data/crates/kobako-wasmtime/wit/deps/sockets.wit +949 -0
  20. data/crates/kobako-wasmtime/witx/wasi_snapshot_preview1.witx +13 -0
  21. data/data/kobako.wasm +0 -0
  22. data/lib/kobako/3.3/kobako.so +0 -0
  23. data/lib/kobako/3.4/kobako.so +0 -0
  24. data/lib/kobako/4.0/kobako.so +0 -0
  25. data/lib/kobako/catalog/extensions.rb +14 -2
  26. data/lib/kobako/catalog/flags.rb +3 -5
  27. data/lib/kobako/catalog/grants.rb +5 -4
  28. data/lib/kobako/catalog/handles.rb +14 -32
  29. data/lib/kobako/catalog/mount.rb +11 -3
  30. data/lib/kobako/catalog/network.rb +35 -0
  31. data/lib/kobako/catalog/replacements.rb +28 -0
  32. data/lib/kobako/catalog/services.rb +5 -19
  33. data/lib/kobako/catalog/snippets.rb +3 -18
  34. data/lib/kobako/catalog.rb +3 -0
  35. data/lib/kobako/codec/{utils.rb → boundary.rb} +4 -2
  36. data/lib/kobako/codec/decoder.rb +5 -5
  37. data/lib/kobako/codec/ext_types.rb +3 -3
  38. data/lib/kobako/codec/handle_walk.rb +3 -43
  39. data/lib/kobako/codec/state.rb +2 -18
  40. data/lib/kobako/codec/value_budget.rb +133 -41
  41. data/lib/kobako/codec.rb +6 -7
  42. data/lib/kobako/context.rb +24 -11
  43. data/lib/kobako/errors.rb +18 -18
  44. data/lib/kobako/extension.rb +3 -2
  45. data/lib/kobako/filesystem.rb +10 -3
  46. data/lib/kobako/fork.rb +42 -0
  47. data/lib/kobako/handle.rb +2 -3
  48. data/lib/kobako/names.rb +28 -0
  49. data/lib/kobako/network.rb +210 -0
  50. data/lib/kobako/outcome.rb +7 -7
  51. data/lib/kobako/runtime.rb +3 -2
  52. data/lib/kobako/sandbox.rb +73 -35
  53. data/lib/kobako/sandbox_options.rb +42 -109
  54. data/lib/kobako/transport/argument_wrap.rb +64 -0
  55. data/lib/kobako/transport/block_failure.rb +1 -1
  56. data/lib/kobako/transport/dispatcher.rb +6 -6
  57. data/lib/kobako/transport/exposure.rb +26 -15
  58. data/lib/kobako/transport/reflection.rb +21 -4
  59. data/lib/kobako/transport/run.rb +8 -23
  60. data/lib/kobako/transport/yielder.rb +2 -9
  61. data/lib/kobako/transport.rb +1 -0
  62. data/lib/kobako/usage.rb +4 -2
  63. data/lib/kobako/version.rb +1 -1
  64. data/lib/kobako.rb +8 -4
  65. data/release-please-config.json +15 -0
  66. data/sig/kobako/catalog/extensions.rbs +2 -0
  67. data/sig/kobako/catalog/grants.rbs +7 -4
  68. data/sig/kobako/catalog/handles.rbs +2 -2
  69. data/sig/kobako/catalog/mount.rbs +3 -1
  70. data/sig/kobako/catalog/network.rbs +20 -0
  71. data/sig/kobako/catalog/replacements.rbs +14 -0
  72. data/sig/kobako/catalog/services.rbs +0 -4
  73. data/sig/kobako/catalog/snippets.rbs +0 -2
  74. data/sig/kobako/codec/{utils.rbs → boundary.rbs} +2 -2
  75. data/sig/kobako/codec/handle_walk.rbs +0 -6
  76. data/sig/kobako/codec/state.rbs +0 -4
  77. data/sig/kobako/codec/value_budget.rbs +48 -5
  78. data/sig/kobako/codec.rbs +2 -2
  79. data/sig/kobako/context.rbs +3 -1
  80. data/sig/kobako/errors.rbs +4 -7
  81. data/sig/kobako/filesystem.rbs +21 -3
  82. data/sig/kobako/fork.rbs +17 -0
  83. data/sig/kobako/network.rbs +115 -0
  84. data/sig/kobako/outcome.rbs +1 -1
  85. data/sig/kobako/runtime.rbs +32 -3
  86. data/sig/kobako/sandbox.rbs +10 -2
  87. data/sig/kobako/sandbox_options.rbs +29 -40
  88. data/sig/kobako/transport/argument_wrap.rbs +15 -0
  89. data/sig/kobako/transport/error.rbs +1 -1
  90. data/sig/kobako/transport/exposure.rbs +2 -4
  91. data/sig/kobako/transport/reflection.rbs +10 -0
  92. data/sig/kobako/transport/run.rbs +0 -2
  93. data/sig/kobako/transport/yielder.rbs +0 -3
  94. data/sig/kobako/transport.rbs +1 -1
  95. data/sig/kobako.rbs +13 -0
  96. metadata +25 -11
  97. data/crates/kobako-runtime/tests/linux_baseline/linux-baseline-expected.txt +0 -16
  98. data/lib/kobako/constant_name.rb +0 -8
  99. data/lib/kobako/pool.rb +0 -140
  100. data/sig/kobako/constant_name.rbs +0 -3
  101. data/sig/kobako/pool.rbs +0 -42
@@ -0,0 +1,210 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kobako
4
+ # The network a Sandbox gives the guest, one named entry at a time. An entry
5
+ # is any object answering one or more of +endpoints+, +resolve?+,
6
+ # +connect?+, +request?+, and +credentials+, or one Sandbox#network builds
7
+ # from its block:
8
+ #
9
+ # sandbox.network(:github) do |net|
10
+ # net.endpoint "api.github.com", port: 443
11
+ # net.endpoint "cache.internal", port: 6379, protocol: :tcp, addresses: [:private]
12
+ # end
13
+ #
14
+ # A test hands Sandbox.new a Mock as +network:+, so the guest's names
15
+ # answer from a table and its dials reach a server the test runs. The
16
+ # rules judge the Mock's answers as they judge the host's:
17
+ #
18
+ # mock = Kobako::Network::Mock.new
19
+ # mock.resolve("api.example.com", to: "93.184.216.34")
20
+ # mock.route("93.184.216.34", 443, to: ["127.0.0.1", server.addr[1]])
21
+ # sandbox = Kobako::Sandbox.new(network: mock)
22
+ #
23
+ # [<tt>Mock.new(local_addresses: [])</tt>]
24
+ # The host's own addresses, which the rules count as local; +nil+ for a
25
+ # host that cannot say them, so every connect to a name is refused.
26
+ # [<tt>resolve(name, to: address)</tt>, <tt>resolve(name, to: [address, ...])</tt>]
27
+ # What a lookup of +name+ answers from now on; a name with no answer
28
+ # resolves to nothing. The name reads as a guest's lookup reads it, so
29
+ # case, the root's dot, and an IDN's spelling do not matter. Raises
30
+ # ArgumentError for a host no lookup asks, such as an address.
31
+ # [<tt>route(address, port, to: [address, port], protocol: :tcp)</tt>]
32
+ # Where a dial over +protocol+, +:tcp+ or +:udp+, goes instead. A dial
33
+ # with no route for its protocol is refused, so nothing reaches the host
34
+ # network unasked; a UDP socket is refused as it connects.
35
+ # [<tt>refuse(address, port, errno, protocol: :tcp)</tt>]
36
+ # Fails a dial over +protocol+ as a host socket failing with +errno+
37
+ # does: an Errno class such as Errno::ECONNRESET, or a subclass of one,
38
+ # read by its name so it fails alike on every host. Raises ArgumentError
39
+ # for a class no Errno class is behind, or an errno kobako never answers.
40
+ # [<tt>hold(name) { ... }</tt>]
41
+ # Keeps each lookup of +name+ waiting until the block returns or raises,
42
+ # +name+ read as +resolve+ reads it.
43
+ # [+lookups+, +dialed_addresses+]
44
+ # Each name asked, and each <tt>[address, port]</tt> dialed, in order.
45
+ module Network
46
+ # What a keyword nobody wrote reads as, so the runtime's contract alone
47
+ # gives its default.
48
+ UNWRITTEN = Object.new.freeze # :nodoc:
49
+ private_constant :UNWRITTEN
50
+
51
+ # What the guest may reach: a +host+ and a +port+, the +protocol+ it
52
+ # speaks, and the +addresses+ the host's name may lead to. Unless written
53
+ # otherwise it speaks +:http+ and leads only to +:public+ addresses. Each
54
+ # address is +:public+, +:private+, +:local+, or a CIDR as a String or an
55
+ # IPAddr.
56
+ #
57
+ # An +:http+ endpoint's +rules+ say which methods and paths it allows and
58
+ # denies; with none, it allows every request.
59
+ #
60
+ # Raises TypeError for a host neither a Symbol nor a String, and
61
+ # ArgumentError for an empty host, a port outside 1 to 65535, a protocol
62
+ # other than +:http+, +:tcp+, or +:udp+, or another address, by the rules
63
+ # an invocation reads the endpoint with.
64
+ class Endpoint < Data.define(:host, :port, :protocol, :addresses, :rules)
65
+ def initialize(host:, port:, protocol: UNWRITTEN, addresses: UNWRITTEN, rules: UNWRITTEN)
66
+ written = { protocol:, addresses:, rules: }.reject { |_, value| value.equal?(UNWRITTEN) }
67
+ %i[addresses rules].each { |field| written[field] = Array(written[field]).freeze if written.key?(field) }
68
+ host, port, protocol, addresses, rules = Network.normalize_endpoint(host, port, written)
69
+ super
70
+ end
71
+ end
72
+
73
+ # One connection the guest asks for, as a +connect?+ policy is handed it:
74
+ # the +host+ it named, a name or a literal address, its +port+, and its
75
+ # +protocol+. The host is never a real address a name resolved to.
76
+ class Connection < Data.define(:host, :port, :protocol); end
77
+
78
+ # One rule an +:http+ endpoint judges a request by: whether it allows or
79
+ # denies, its +method+ uppercase or +nil+ for any, and a +path+ pattern,
80
+ # where <tt>*</tt> stands for one segment and <tt>**</tt> for any number.
81
+ # Each is given as a Symbol or a String; another class raises TypeError.
82
+ class HttpRule
83
+ attr_reader :method, :path
84
+
85
+ # Whether the rule allows what it matches, or denies it.
86
+ def allow? = @allow
87
+
88
+ def initialize(allow:, method:, path:)
89
+ method = nil if method == :any
90
+ @allow, @method, @path = Network.normalize_rule(allow ? true : false, method, path)
91
+ @method&.freeze
92
+ @path.freeze
93
+ freeze
94
+ end
95
+ end
96
+
97
+ # The rules a block given to Builder#endpoint adds to its endpoint.
98
+ class Rules
99
+ def initialize # :nodoc:
100
+ @rules = [] # : Array[HttpRule]
101
+ end
102
+
103
+ # Allow +method+, or +:any+, on paths +path+ matches. Returns +self+.
104
+ def allow(method, path)
105
+ @rules << HttpRule.new(allow: true, method: method, path: path)
106
+ self
107
+ end
108
+
109
+ # Deny +method+, or +:any+, on paths +path+ matches; a denial wins over
110
+ # any allowance. Returns +self+.
111
+ def deny(method, path)
112
+ @rules << HttpRule.new(allow: false, method: method, path: path)
113
+ self
114
+ end
115
+
116
+ def to_a = @rules.dup # :nodoc:
117
+ end
118
+
119
+ # A value the Host App hands no guest, swapped in place of +placeholder+ in
120
+ # one header of a request bound to its entry's own endpoints. The
121
+ # +placement+ is +:bearer+ or +:basic+ for the +authorization+ header, or a
122
+ # header's name. The block answers the value for a Request, or +nil+ to
123
+ # send nothing, as the request leaves; a block that raises refuses the
124
+ # request. A +placeholder+ neither a Symbol nor a String raises TypeError.
125
+ class Credential
126
+ attr_reader :placement, :placeholder
127
+
128
+ def initialize(placement, placeholder:, &source)
129
+ raise ArgumentError, "a credential needs a block answering its value" unless source
130
+
131
+ @placement = placement.is_a?(String) ? placement.dup.freeze : placement
132
+ @placeholder = Network.normalize_credential(@placement, placeholder).freeze
133
+ @source = source
134
+ end
135
+
136
+ # The value for +request+, or +nil+ to send nothing; raising refuses it.
137
+ def value(request) = @source.call(request)
138
+ end
139
+
140
+ # One HTTP request the guest sends, as a +request?+ policy is handed it:
141
+ # the +host+ lowercase and the +port+, the +method+ as sent, since a
142
+ # method is case-sensitive, the +scheme+, the +path+ with no query, and
143
+ # the +header_names+ lowercase, never a header's value.
144
+ class Request
145
+ attr_reader :host, :port, :method, :scheme, :path, :header_names
146
+
147
+ def initialize(authority, method, scheme, path, header_names) # :nodoc:
148
+ @host, @port = authority
149
+ @method = method
150
+ @scheme = scheme
151
+ @path = path
152
+ @header_names = header_names
153
+ freeze
154
+ end
155
+ end
156
+
157
+ # The entry a block given to Sandbox#network builds, adding to the object
158
+ # given beside it, as Faraday.new yields its builder. It collects what the
159
+ # block declares; each invocation composes it with the given object, the
160
+ # object's endpoints, credentials, and policies first, any refusal
161
+ # winning.
162
+ class Builder
163
+ HOOKS = %i[resolve connect request].freeze # :nodoc:
164
+
165
+ def initialize(entry = nil) # :nodoc:
166
+ @entry = entry
167
+ @endpoints = [] # : Array[Endpoint]
168
+ @policies = HOOKS.to_h { |hook| [hook, []] } # : Hash[Symbol, Array[^(untyped) -> boolish]]
169
+ @credentials = [] # : Array[Credential]
170
+ end
171
+
172
+ # Let the guest reach +host+ on +port+, as Endpoint.new takes them.
173
+ # Returns +self+.
174
+ # A given block yields a Rules adding the methods and paths an +:http+
175
+ # endpoint allows and denies.
176
+ def endpoint(host, port:, protocol: UNWRITTEN, addresses: UNWRITTEN)
177
+ rules = Rules.new
178
+ yield rules if block_given?
179
+ @endpoints << Endpoint.new(host: host, port: port, protocol: protocol, addresses: addresses,
180
+ rules: rules.to_a)
181
+ self
182
+ end
183
+
184
+ # Judge each decision +hook+ names with the block; a falsy answer or a
185
+ # raised StandardError refuses. +:resolve+ hands the block the name a
186
+ # lookup asks for, lowercase with no trailing dot and an IDN as its
187
+ # A-label, +:connect+ a Connection, and +:request+ a Request. Raises
188
+ # ArgumentError for another hook. Returns +self+.
189
+ def policy(hook, &block)
190
+ unless HOOKS.include?(hook)
191
+ raise ArgumentError,
192
+ "a policy hook must be one of #{HOOKS.inspect}, got #{hook.inspect}"
193
+ end
194
+ raise ArgumentError, "a policy needs a block" unless block
195
+
196
+ @policies.fetch(hook) << block
197
+ self
198
+ end
199
+
200
+ # Swap a Credential's value in place of +placeholder+ in requests bound
201
+ # to this entry's endpoints. Returns +self+.
202
+ def credential(placement, placeholder:, &source)
203
+ @credentials << Credential.new(placement, placeholder: placeholder, &source)
204
+ self
205
+ end
206
+
207
+ def to_native = [@entry, @endpoints, @credentials, @policies] # :nodoc:
208
+ end
209
+ end
210
+ end
@@ -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
@@ -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
@@ -44,6 +45,7 @@ module Kobako
44
45
  @grants = Catalog::Grants.new
45
46
  @sealed = false
46
47
  @runtime = build_runtime
48
+ Fork.install
47
49
  end
48
50
 
49
51
  # Make +object+ reachable from the guest as the constant at +path+, a
@@ -58,9 +60,10 @@ module Kobako
58
60
  # the constant, and Context#bind supplies the object for each invocation.
59
61
  # A call to one left unfilled fails as a ServiceError.
60
62
  #
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.
63
+ # Raises TypeError for a path that is no Symbol or String, ArgumentError
64
+ # for a malformed path, a path under the reserved
65
+ # +Kobako+ namespace, or a path that collides with an existing binding,
66
+ # and FrozenError for a call after the first invocation.
64
67
  def bind(path, object = Unresolved)
65
68
  refuse_once_invoked("bind")
66
69
  @services.bind(path, object)
@@ -71,8 +74,9 @@ module Kobako
71
74
  # backend. Any object answering +name+, +source+, +backend+ and
72
75
  # +depends_on+ works; Extension is the bundled one. Returns +self+.
73
76
  #
74
- # Raises ArgumentError for a malformed Extension, a call after the first
75
- # invocation, or, at the first invocation, a missing dependency.
77
+ # Raises TypeError for an Extension of another shape, FrozenError for a
78
+ # call after the first invocation, and, at the first invocation,
79
+ # ArgumentError for a missing dependency.
76
80
  def install(*extensions)
77
81
  refuse_once_invoked("install")
78
82
 
@@ -92,19 +96,39 @@ module Kobako
92
96
  # or a StandardError, fails that call as <tt>Errno::EACCES</tt> in the
93
97
  # guest and leaves the script running.
94
98
  #
95
- # A path may sit beneath another mount, and the guest reaches the
96
- # innermost one.
99
+ # A path may sit beneath another mount, standing where Linux's +mount+
100
+ # would place it, and a run fails where Linux would refuse it.
97
101
  #
98
102
  # 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.
103
+ # a Filesystem, ArgumentError for a malformed or duplicate path or an
104
+ # unknown access, and FrozenError for a call after the first invocation.
101
105
  def mount(at, filesystem, access: :read, &policy)
102
106
  refuse_once_invoked("mount")
103
- Runtime.validate_mount(at, access, filesystem)
104
107
  @grants.register(Catalog::Mount.new(at: at, access: access, filesystem: filesystem, policy: policy))
105
108
  self
106
109
  end
107
110
 
111
+ # Give the guest the network entry +entry+ under +name+, any object
112
+ # answering any of +endpoints+, +credentials+, +resolve?+, +connect?+, and
113
+ # +request?+. A given block yields a Kobako::Network::Builder adding to
114
+ # +entry+, so the block's +self+ stays the caller's. Each entry's endpoints
115
+ # and credentials are read afresh for every invocation. Its +resolve?+ is
116
+ # handed each name the guest looks up, its +connect?+ each
117
+ # Kobako::Network::Connection, and its +request?+ each
118
+ # Kobako::Network::Request; any entry refusing refuses. Returns +self+.
119
+ #
120
+ # Raises TypeError for a name that is no Symbol or String, ArgumentError
121
+ # for an empty or duplicate name, an endpoint with an
122
+ # empty host, a port outside 1 to 65535, or an unknown protocol, and
123
+ # FrozenError for a call after the first invocation. An
124
+ # endpoint the ruleset refuses, such as a wildcard leading to +:private+,
125
+ # raises ArgumentError from the invocation that compiles it.
126
+ def network(name, entry = nil, &builder)
127
+ refuse_once_invoked("network")
128
+ @grants.register(Catalog::Network.new(name: name, entry: entry, &builder))
129
+ self
130
+ end
131
+
108
132
  # Register a snippet that every invocation runs, in the order registered,
109
133
  # before its own code. Returns +self+.
110
134
  #
@@ -114,8 +138,9 @@ module Kobako
114
138
  # Precompiled RITE bytecode, trusted as host code: the unmodified
115
139
  # compiler output of the mruby release the Guest Binary is built on.
116
140
  #
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
141
+ # Raises TypeError for a snippet part of another class, ArgumentError for
142
+ # a malformed or duplicate snippet, and FrozenError for a call after the
143
+ # first invocation. A snippet that fails to load fails every
119
144
  # invocation with SandboxError, or BytecodeError for bytecode.
120
145
  def preload(code: nil, name: nil, binary: nil)
121
146
  refuse_once_invoked("preload")
@@ -131,8 +156,8 @@ module Kobako
131
156
  # Mark a flag advisory only when a script cannot tell it was skipped.
132
157
  # Returns +self+.
133
158
  #
134
- # Raises ArgumentError for a malformed or duplicate flag, or a call after
135
- # the first invocation.
159
+ # Raises TypeError for a name or value of another class, ArgumentError for
160
+ # a duplicate flag, and FrozenError for a call after the first invocation.
136
161
  def flag(name, value = "", advisory: false)
137
162
  refuse_once_invoked("flag")
138
163
 
@@ -144,37 +169,50 @@ module Kobako
144
169
  # and +kwargs+, and return the Execution. A given block receives the
145
170
  # invocation's Context before the guest runs.
146
171
  #
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.
172
+ # Raises TypeError when +target+ is not a Symbol or String, a keyword is
173
+ # not a Symbol, or an argument holds a Hash key or a reflective object
174
+ # that cannot cross, and ArgumentError when +target+ is not a constant
175
+ # name, the arguments carry a Handle, or an argument nests past what the
176
+ # wire carries. A failed run raises as #eval does.
150
177
  def run(target, *args, **kwargs, &block)
151
178
  request = Transport::Run.new(entrypoint: target, args: args, kwargs: kwargs)
152
- Codec.within_value_budget(@options.value_budget) { begin_invocation.run(request, &block) }
179
+ begin_invocation.run(request, &block)
153
180
  end
154
181
 
155
182
  # Evaluate +code+, mruby source as a String, and return the Execution,
156
183
  # whose +value+ is the last expression. A given block receives the
157
184
  # invocation's Context before the guest runs.
158
185
  #
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
186
+ # Raises TypeError when +code+ is no String, and ArgumentError when it is
187
+ # not UTF-8 text, before the guest runs; TrapError when the engine
188
+ # stopped the guest, a deadline or memory budget included, or the host
189
+ # could not start it; SandboxError
190
+ # when the guest failed, the Guest Binary not starting the run included;
191
+ # and ServiceError when a Service call failed and the guest left it
163
192
  # unrescued.
164
193
  def eval(code, &block)
165
- raise SandboxError, "code must be a String, got #{code.class}" unless code.is_a?(String)
194
+ raise TypeError, "code must be a String, got #{code.class}" unless code.is_a?(String)
195
+
196
+ source = code.dup.force_encoding(Encoding::UTF_8)
197
+ raise ArgumentError, "code must be UTF-8 text" unless source.valid_encoding?
198
+
199
+ begin_invocation.eval(source, &block)
200
+ end
201
+
202
+ # What this Sandbox's runs are doing now, as a Hash, or the one value
203
+ # +key+ names, as GC.stat answers: +:runs_waiting+ counts the runs waiting
204
+ # on a lock or an event. Raises ArgumentError for a key it does not hold.
205
+ def stat(key = nil) # :nodoc:
206
+ stat = @runtime.stat
207
+ return stat if key.nil?
166
208
 
167
- Codec.within_value_budget(@options.value_budget) { begin_invocation.eval(code, &block) }
209
+ stat.fetch(key) { raise ArgumentError, "unknown key: #{key}" }
168
210
  end
169
211
 
170
212
  private
171
213
 
172
- # A runtime whose declared posture falls below the request never runs
173
- # guest code.
174
214
  def build_runtime
175
- runtime = Kobako::Runtime.from_path(@wasm_path, **@options.to_h)
176
- @options.enforce_floor(runtime.profile)
177
- runtime
215
+ Kobako::Runtime.from_path(@wasm_path, **@options.to_h)
178
216
  end
179
217
 
180
218
  # The one place the Preamble's parts are put together, for a compile
@@ -186,7 +224,7 @@ module Kobako
186
224
  # Registration closes at the first invocation, so every invocation ships
187
225
  # the same Services, snippets, flags, Extensions and mounts.
188
226
  def refuse_once_invoked(verb)
189
- raise ArgumentError, "cannot #{verb} after first Sandbox invocation" if @sealed
227
+ raise FrozenError, "cannot #{verb} after first Sandbox invocation" if @sealed
190
228
  end
191
229
 
192
230
  # Sealing before the dependency check keeps a Sandbox whose check failed
@@ -4,122 +4,55 @@ 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 the root's included; 16.
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
+ # lookup, dial, and HTTP request one, failed ones too,
28
+ # as a Worker counts its subrequests; 50.
29
+ # [+profile+] The isolation the runtime must provide at least:
30
+ # +:hermetic+, which denies the guest the clock and
31
+ # entropy, or the weaker +:permissive+, which leaves them
32
+ # live; +:hermetic+.
33
+ # [+gvl+] How an invocation holds Ruby's GVL: +:hold+ while the
34
+ # guest runs, handing it over each quantum, or +:release+,
35
+ # giving it up while the guest runs, so Sandboxes on
36
+ # different Threads run in parallel; +:hold+.
37
+ # [+network+] What the guest's network dials and looks names up
38
+ # through, beneath every rule its entries make: +nil+
39
+ # for the host's own, or a Kobako::Network::Mock a test
40
+ # writes; +nil+.
21
41
  #
22
- # Raises ArgumentError for a value outside these shapes, and SetupError
23
- # when the runtime provides less isolation than +profile+ asks for.
42
+ # Raises TypeError for a cap of another class, RangeError for one past
43
+ # what the host counts, and ArgumentError for another value outside these
44
+ # shapes. The runtime judges every cap, and +profile+, +gvl+, and
45
+ # +network+ as Sandbox.new builds it.
24
46
  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
74
- end
75
-
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
- 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}"
47
+ :open_file_limit, :open_connection_limit, :connection_limit, :profile, :gvl,
48
+ :network)
49
+ # Every option is required; Sandbox.new fills each one left out from
50
+ # the runtime's defaults.
51
+ def initialize(timeout:, setup_timeout:, memory_limit:, stdout_limit:, stderr_limit:, open_file_limit:,
52
+ open_connection_limit:, connection_limit:, profile:, gvl:, network:)
53
+ caps = Kobako::Runtime.normalize_caps({ timeout:, setup_timeout:, memory_limit:, stdout_limit:, stderr_limit:,
54
+ open_file_limit:, open_connection_limit:, connection_limit: })
55
+ super(**caps.merge(profile:, gvl:, network:))
123
56
  end
124
57
  end
125
58
  end