microsandbox-rb 0.17.4 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +378 -1
- data/Cargo.lock +747 -1134
- data/DESIGN.md +52 -36
- data/README.md +27 -20
- data/SECURITY.md +22 -6
- data/docs/configuration.md +153 -17
- data/docs/errors.md +8 -2
- data/docs/execution.md +17 -0
- data/docs/filesystem.md +2 -1
- data/docs/images.md +74 -2
- data/docs/lifecycle.md +130 -6
- data/docs/observability.md +9 -7
- data/docs/releasing.md +1 -1
- data/docs/runtime.md +126 -43
- data/docs/surface.md +55 -14
- data/ext/microsandbox/Cargo.toml +22 -20
- data/ext/microsandbox/extconf.rb +9 -8
- data/ext/microsandbox/src/backend.rs +21 -15
- data/ext/microsandbox/src/error.rs +59 -1
- data/ext/microsandbox/src/host_path.rs +37 -28
- data/ext/microsandbox/src/lib.rs +314 -42
- data/ext/microsandbox/src/runtime.rs +5 -5
- data/ext/microsandbox/src/sandbox.rs +508 -241
- data/ext/microsandbox/src/snapshot.rs +63 -20
- data/ext/microsandbox/src/storage.rs +44 -0
- data/lib/microsandbox/errors.rb +63 -0
- data/lib/microsandbox/exec_handle.rb +2 -1
- data/lib/microsandbox/runtime_info.rb +65 -0
- data/lib/microsandbox/sandbox.rb +544 -158
- data/lib/microsandbox/snapshot.rb +101 -28
- data/lib/microsandbox/storage.rb +205 -0
- data/lib/microsandbox/version.rb +5 -4
- data/lib/microsandbox.rb +259 -60
- data/rust-toolchain.toml +1 -1
- data/sig/microsandbox.rbs +113 -7
- metadata +5 -2
data/lib/microsandbox/sandbox.rb
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
require "json"
|
|
4
|
+
require "pathname"
|
|
4
5
|
|
|
5
6
|
module Microsandbox
|
|
6
7
|
# A controllable handle to a sandbox, returned by {Sandbox.get}, {Sandbox.list},
|
|
@@ -51,29 +52,41 @@ module Microsandbox
|
|
|
51
52
|
Microsandbox.time_from_ms(ms)
|
|
52
53
|
end
|
|
53
54
|
|
|
54
|
-
#
|
|
55
|
+
# Request a graceful shutdown and wait, without a deadline, until the
|
|
56
|
+
# runtime has released the sandbox. Since runtime v0.7 nothing escalates to
|
|
57
|
+
# a kill: bound the wait with {#stop_with_timeout}, force it with {#kill}.
|
|
55
58
|
# @return [nil]
|
|
56
59
|
def stop
|
|
57
60
|
@native.stop
|
|
58
61
|
nil
|
|
59
62
|
end
|
|
60
63
|
|
|
61
|
-
#
|
|
62
|
-
#
|
|
64
|
+
# Request a graceful shutdown and wait at most `timeout` seconds (one
|
|
65
|
+
# budget for dispatch and the runtime's release). Expiry raises
|
|
66
|
+
# {StopTimeoutError} and kills nothing — the shutdown may still complete
|
|
67
|
+
# later; call {#kill} if it must end now. A zero budget times out before
|
|
68
|
+
# the request is sent.
|
|
69
|
+
# @param timeout [Numeric] seconds
|
|
70
|
+
# @raise [StopTimeoutError] when the budget runs out
|
|
63
71
|
# @return [nil]
|
|
64
72
|
def stop_with_timeout(timeout)
|
|
65
73
|
@native.stop_with_timeout(Sandbox.send(:coerce_duration, timeout, "timeout"))
|
|
66
74
|
nil
|
|
67
75
|
end
|
|
68
76
|
|
|
69
|
-
# Force-kill the sandbox
|
|
77
|
+
# Force-kill the sandbox, then wait up to 5 seconds to observe it stopped.
|
|
78
|
+
# Taking the name's transition lock first has no deadline: while another
|
|
79
|
+
# lifecycle operation holds it, this waits. Use {#kill_with_timeout} for
|
|
80
|
+
# one bound over the whole call.
|
|
70
81
|
# @return [nil]
|
|
71
82
|
def kill
|
|
72
83
|
@native.kill
|
|
73
84
|
nil
|
|
74
85
|
end
|
|
75
86
|
|
|
76
|
-
# Force-kill
|
|
87
|
+
# Force-kill under one budget of `timeout` seconds that covers the
|
|
88
|
+
# transition lock, the kill request and observing the stop. Expiry raises
|
|
89
|
+
# {Error}; the sandbox may then still be running.
|
|
77
90
|
# @param timeout [Numeric]
|
|
78
91
|
# @return [nil]
|
|
79
92
|
def kill_with_timeout(timeout)
|
|
@@ -140,9 +153,10 @@ module Microsandbox
|
|
|
140
153
|
|
|
141
154
|
# Stop and start *this exact* sandbox, returning the new live sandbox
|
|
142
155
|
# (runtime v0.6.16). A created/stopped/crashed sandbox is started directly.
|
|
143
|
-
# @param force [Boolean]
|
|
144
|
-
# @param timeout [Numeric, nil] graceful-shutdown seconds
|
|
145
|
-
#
|
|
156
|
+
# @param force [Boolean] force-kill instead of requesting a graceful shutdown
|
|
157
|
+
# @param timeout [Numeric, nil] graceful-shutdown budget in seconds (the
|
|
158
|
+
# core's default is 10); expiry raises {StopTimeoutError} and kills
|
|
159
|
+
# nothing (runtime v0.7)
|
|
146
160
|
# @param detached [Boolean] start the replacement detached
|
|
147
161
|
# @raise [SandboxReplacedError] if the name now refers to a different sandbox
|
|
148
162
|
# @return [Sandbox]
|
|
@@ -155,9 +169,10 @@ module Microsandbox
|
|
|
155
169
|
# Stop and remove *this exact* sandbox (runtime v0.6.16) — {#stop} plus
|
|
156
170
|
# {Sandbox.remove} in one convergent step, with an identity check that
|
|
157
171
|
# refuses to remove a same-name replacement.
|
|
158
|
-
# @param force [Boolean]
|
|
159
|
-
# @param timeout [Numeric, nil] graceful-shutdown seconds
|
|
160
|
-
#
|
|
172
|
+
# @param force [Boolean] force-kill instead of requesting a graceful shutdown
|
|
173
|
+
# @param timeout [Numeric, nil] graceful-shutdown budget in seconds (the
|
|
174
|
+
# core's default is 10); expiry raises {StopTimeoutError} and kills
|
|
175
|
+
# nothing (runtime v0.7)
|
|
161
176
|
# @raise [SandboxReplacedError] if the name now refers to a different sandbox
|
|
162
177
|
# @return [nil]
|
|
163
178
|
def destroy(force: false, timeout: nil)
|
|
@@ -210,13 +225,15 @@ module Microsandbox
|
|
|
210
225
|
ModificationPlan.new(JSON.parse(@native.modify(opts)))
|
|
211
226
|
end
|
|
212
227
|
|
|
213
|
-
# Snapshot this (stopped) sandbox
|
|
214
|
-
#
|
|
215
|
-
#
|
|
216
|
-
#
|
|
217
|
-
#
|
|
218
|
-
#
|
|
219
|
-
#
|
|
228
|
+
# Snapshot this (stopped) sandbox. Convenience equivalent of
|
|
229
|
+
# `Snapshot.create(<snapshot-name>, from_sandbox: <this sandbox>)`: the
|
|
230
|
+
# artifact joins the snapshot group named after this sandbox as member
|
|
231
|
+
# `name` and becomes its head (see {Snapshot} for selectors — keep the
|
|
232
|
+
# returned {SnapshotInfo#id}). (`snapshot_to(path)` was removed in 0.11.0
|
|
233
|
+
# with runtime v0.6.7 — for explicit placement use
|
|
234
|
+
# `Snapshot.create(name, from_sandbox:, dest_dir:)`; the core picks the
|
|
235
|
+
# directory beneath `dest_dir`, read it from {SnapshotInfo#path}.)
|
|
236
|
+
# @param name [String] member name alias inside the snapshot group
|
|
220
237
|
# @return [SnapshotInfo]
|
|
221
238
|
def snapshot(name)
|
|
222
239
|
SnapshotInfo.new(@native.snapshot(name.to_s))
|
|
@@ -340,12 +357,30 @@ module Microsandbox
|
|
|
340
357
|
# arguments of {Sandbox#wait_for_status} / {SandboxHandle#wait_for_status}.
|
|
341
358
|
STATUSES = %i[created starting running draining paused stopped crashed].freeze
|
|
342
359
|
|
|
360
|
+
# Seconds the block forms of {create}, {connect_or_create} and {restore}
|
|
361
|
+
# give the graceful stop on exit before they kill the sandbox (runtime
|
|
362
|
+
# v0.7's own default graceful-stop budget). The public {#stop} still waits
|
|
363
|
+
# without a deadline.
|
|
364
|
+
BLOCK_STOP_TIMEOUT = 10
|
|
365
|
+
|
|
366
|
+
# Seconds the same cleanup gives the kill that follows an expired
|
|
367
|
+
# {BLOCK_STOP_TIMEOUT}, transition lock and dispatch included. Upstream's
|
|
368
|
+
# kill itself waits up to 5 s for the process to exit and up to 5 s more
|
|
369
|
+
# for its lifecycle lock, so a slow but successful kill needs headroom
|
|
370
|
+
# above 10 s.
|
|
371
|
+
BLOCK_KILL_TIMEOUT = 15
|
|
372
|
+
private_constant :BLOCK_KILL_TIMEOUT
|
|
373
|
+
|
|
343
374
|
class << self
|
|
344
375
|
# Create and boot a sandbox.
|
|
345
376
|
#
|
|
346
377
|
# When a block is given the sandbox is yielded and stopped automatically
|
|
347
|
-
# when the block returns (the block's value is returned)
|
|
348
|
-
#
|
|
378
|
+
# when the block returns (the block's value is returned): a graceful stop
|
|
379
|
+
# with a {BLOCK_STOP_TIMEOUT} budget, then a kill with its own 15-second
|
|
380
|
+
# budget, both covering the name's transition lock, so leaving the block
|
|
381
|
+
# never hangs (a kill that cannot finish is reported with a warning and
|
|
382
|
+
# the sandbox may still be running). Otherwise the live {Sandbox} is returned and you are
|
|
383
|
+
# responsible for calling {#stop}.
|
|
349
384
|
#
|
|
350
385
|
# @param name [String] sandbox name (max 128 UTF-8 bytes)
|
|
351
386
|
# @param image [String, nil] OCI image reference (e.g. "python")
|
|
@@ -406,14 +441,28 @@ module Microsandbox
|
|
|
406
441
|
# this to inject `secrets:` on non-443 ports or to trust a private CA.
|
|
407
442
|
# @param ipv4_pool [String, nil] guest IPv4 address pool CIDR (e.g. "10.0.0.0/24")
|
|
408
443
|
# @param ipv6_pool [String, nil] guest IPv6 address pool CIDR
|
|
409
|
-
# @param
|
|
444
|
+
# @param max_tcp_connections [Integer, nil] cap on concurrent proxied TCP
|
|
445
|
+
# connections; 0 means unlimited, nil leaves the runtime default
|
|
446
|
+
# @param max_udp_connections [Integer, nil] cap on concurrent UDP relay
|
|
447
|
+
# sessions; 0 means unlimited, nil leaves the runtime default
|
|
448
|
+
# @param max_connections [Integer, nil] deprecated alias of
|
|
449
|
+
# `max_tcp_connections:` (warns); passing both raises ArgumentError
|
|
410
450
|
# @param trust_host_cas [Boolean, nil] trust the host's CA bundle for upstream TLS
|
|
411
451
|
# @param strict [Boolean, nil] strict hostname-policy mode (runtime
|
|
412
|
-
# v0.6.18
|
|
452
|
+
# v0.6.18; ON by default since runtime v0.7 — pass `false` to opt
|
|
453
|
+
# out): a hostname-rule allow must be backed by an
|
|
413
454
|
# inspectable request authority — plain-HTTP `Host`, or SNI/authority
|
|
414
455
|
# under TLS interception. Without that visibility (e.g. bypassed or
|
|
415
456
|
# non-intercepted HTTPS) a flow allowed only by a hostname rule is
|
|
416
457
|
# denied before the upstream dial. Create-only; `modify` cannot change it.
|
|
458
|
+
# @param http [Hash, nil] how a request the network policy denies is
|
|
459
|
+
# answered (runtime v0.7). By default a denied plain-HTTP request — or
|
|
460
|
+
# an HTTPS one under TLS interception — gets a JSON `403`. Keys:
|
|
461
|
+
# `deny_response:` (Boolean; `false` closes the connection instead),
|
|
462
|
+
# `format:` (`:json`, the default, or `:text`), `network_message:` and
|
|
463
|
+
# `secret_message:` (the JSON `message` for a network-policy or a
|
|
464
|
+
# secret-policy denial; JSON format only). Create-only and local-only:
|
|
465
|
+
# a cloud create accepts only the defaults or `deny_response: false`.
|
|
417
466
|
# @param rate_limiter [Hash, nil] per-sandbox egress/ingress token-bucket
|
|
418
467
|
# limits (runtime v0.6.9, local backend):
|
|
419
468
|
# `{ egress: { bandwidth: { size: 1_048_576, refill_time_ms: 1000,
|
|
@@ -435,8 +484,8 @@ module Microsandbox
|
|
|
435
484
|
# sockets), or an Array of
|
|
436
485
|
# `{ host_socket:, port:, socket_type: :stream|:dgram }` Hashes. Guests
|
|
437
486
|
# connect to host CID 2 on the given port; no in-guest proxy required.
|
|
438
|
-
# @param from_snapshot [
|
|
439
|
-
#
|
|
487
|
+
# @param from_snapshot [nil] removed in 0.18.0 — use {Sandbox.restore};
|
|
488
|
+
# passing it raises ArgumentError
|
|
440
489
|
# @param fstype [String, nil] inner filesystem type (e.g. "ext4") when
|
|
441
490
|
# `image:` is a disk-image rootfs path whose filesystem can't be
|
|
442
491
|
# auto-probed; ignored for OCI images
|
|
@@ -478,16 +527,22 @@ module Microsandbox
|
|
|
478
527
|
# instead of HTTPS (for local/self-hosted registries)
|
|
479
528
|
# @param registry_ca_certs [String, Array<String>, nil] extra PEM-encoded CA
|
|
480
529
|
# root certificate(s) to trust (for a registry with a private CA)
|
|
481
|
-
# @param secrets [Array<Hash>, nil] placeholder-protected secrets
|
|
482
|
-
# the TLS proxy (auto-enables TLS interception). Each Hash needs `env
|
|
483
|
-
# `value
|
|
484
|
-
#
|
|
485
|
-
#
|
|
486
|
-
#
|
|
487
|
-
#
|
|
488
|
-
#
|
|
489
|
-
#
|
|
490
|
-
#
|
|
530
|
+
# @param secrets [Array<Hash>, nil] placeholder-protected secrets substituted
|
|
531
|
+
# by the TLS proxy (auto-enables TLS interception). Each Hash needs `env:`,
|
|
532
|
+
# `value:`, and a non-empty `allow:` list of hosts that may receive the
|
|
533
|
+
# real value (`"*.example.com"` wildcards; `"*"` allows ANY host).
|
|
534
|
+
# Optional per-secret: `allow_placeholder_for:` (hosts that may receive
|
|
535
|
+
# the unchanged placeholder; `passthrough:` is a deprecated alias),
|
|
536
|
+
# `placeholder:`, `require_tls_identity:` (default true),
|
|
537
|
+
# `violation_action:` (:block, :block_and_log, :block_and_terminate), and
|
|
538
|
+
# `substitution: { headers:, header_fields:, query:, body: }` (default:
|
|
539
|
+
# headers only). The 0.17 keys (`host:`/`hosts:`/`host_patterns:`,
|
|
540
|
+
# `inject_*:`, `require_tls:`, `on_violation:`) raise ArgumentError.
|
|
541
|
+
# @param secret_violation_action [String, Symbol, nil] sandbox-wide
|
|
542
|
+
# secret-leak action: :block, :block_and_log, or :block_and_terminate
|
|
543
|
+
# (kebab-case spellings accepted)
|
|
544
|
+
# @param on_secret_violation [nil] removed in 0.18.0 — use
|
|
545
|
+
# `secret_violation_action:`; passing it raises ArgumentError
|
|
491
546
|
# @param detached [Boolean] keep running after this process exits
|
|
492
547
|
# @param replace [Boolean] replace an existing sandbox with the same name
|
|
493
548
|
# @param replace_with_timeout [Numeric, nil] replace, waiting up to N seconds
|
|
@@ -505,11 +560,7 @@ module Microsandbox
|
|
|
505
560
|
begin
|
|
506
561
|
yield sandbox
|
|
507
562
|
ensure
|
|
508
|
-
|
|
509
|
-
sandbox.stop
|
|
510
|
-
rescue Microsandbox::Error
|
|
511
|
-
# best-effort cleanup; ignore stop failures during teardown
|
|
512
|
-
end
|
|
563
|
+
teardown(sandbox)
|
|
513
564
|
end
|
|
514
565
|
end
|
|
515
566
|
|
|
@@ -563,11 +614,7 @@ module Microsandbox
|
|
|
563
614
|
begin
|
|
564
615
|
yield sandbox
|
|
565
616
|
ensure
|
|
566
|
-
|
|
567
|
-
sandbox.stop if sandbox.owns_lifecycle?
|
|
568
|
-
rescue Microsandbox::Error
|
|
569
|
-
# best-effort cleanup; ignore stop failures during teardown
|
|
570
|
-
end
|
|
617
|
+
teardown(sandbox, only_if_owned: true)
|
|
571
618
|
end
|
|
572
619
|
end
|
|
573
620
|
|
|
@@ -647,9 +694,13 @@ module Microsandbox
|
|
|
647
694
|
# callers, {create} included: a sandbox this call does not own is never
|
|
648
695
|
# stopped here. Its reference is just let go (GC closes the handle, the
|
|
649
696
|
# sandbox keeps running).
|
|
697
|
+
#
|
|
698
|
+
# {restore} passes `always_stop: true`: its sandbox is always new, but
|
|
699
|
+
# upstream starts it detached, so it never reports lifecycle ownership.
|
|
700
|
+
# @param always_stop [Boolean] stop even a sandbox this call does not own
|
|
650
701
|
# @yieldreturn [Native::Sandbox]
|
|
651
702
|
# @return [Sandbox]
|
|
652
|
-
def acquire
|
|
703
|
+
def acquire(always_stop: false)
|
|
653
704
|
native = nil
|
|
654
705
|
handed_off = false
|
|
655
706
|
begin
|
|
@@ -662,7 +713,7 @@ module Microsandbox
|
|
|
662
713
|
ensure
|
|
663
714
|
if native && !handed_off
|
|
664
715
|
begin
|
|
665
|
-
native
|
|
716
|
+
bounded_stop(native) if always_stop || native.owns_lifecycle
|
|
666
717
|
rescue Microsandbox::Error
|
|
667
718
|
# best-effort cleanup; the interrupt is what the caller must see
|
|
668
719
|
end
|
|
@@ -680,32 +731,33 @@ module Microsandbox
|
|
|
680
731
|
shell: nil, user: nil, hostname: nil, labels: nil, scripts: nil,
|
|
681
732
|
entrypoint: nil, cmd: nil, ports: nil, ports_udp: nil, volumes: nil, network: nil,
|
|
682
733
|
dns: nil, tls: nil, ipv4_pool: nil, ipv6_pool: nil,
|
|
683
|
-
max_connections: nil,
|
|
734
|
+
max_connections: nil, max_tcp_connections: nil, max_udp_connections: nil,
|
|
735
|
+
trust_host_cas: nil, strict: nil, http: nil, rate_limiter: nil, proxy: nil,
|
|
684
736
|
vsock: nil,
|
|
685
737
|
patches: nil,
|
|
686
738
|
from_snapshot: nil, fstype: nil, init: nil, ephemeral: false,
|
|
687
739
|
log_level: nil, quiet_logs: false, security: nil,
|
|
688
740
|
root_disk: nil, oci_upper_size: nil, max_duration: nil, idle_timeout: nil, rlimits: nil,
|
|
689
741
|
pull_policy: nil, registry_auth: nil, registry_insecure: false,
|
|
690
|
-
registry_ca_certs: nil, secrets: nil,
|
|
742
|
+
registry_ca_certs: nil, secrets: nil, secret_violation_action: nil,
|
|
743
|
+
on_secret_violation: nil,
|
|
691
744
|
detached: false, replace: false, replace_with_timeout: nil)
|
|
692
|
-
#
|
|
693
|
-
#
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
745
|
+
# Removed in 0.18.0 (runtime v0.7). Kept as keywords so the old
|
|
746
|
+
# spelling fails with directions instead of "unknown keyword".
|
|
747
|
+
unless from_snapshot.nil?
|
|
748
|
+
raise ArgumentError,
|
|
749
|
+
"from_snapshot: was removed in 0.18.0 (runtime v0.7); boot from a snapshot with " \
|
|
750
|
+
"Sandbox.restore(snapshot, name: ...), selecting it by id or path"
|
|
751
|
+
end
|
|
752
|
+
unless on_secret_violation.nil?
|
|
753
|
+
raise ArgumentError,
|
|
754
|
+
"on_secret_violation: was removed in 0.18.0 (runtime v0.7); use secret_violation_action: " \
|
|
755
|
+
"(:block, :block_and_log, or :block_and_terminate) — a passthrough is now each secret's " \
|
|
756
|
+
"allow_placeholder_for: host list"
|
|
697
757
|
end
|
|
698
758
|
if root_disk && oci_upper_size
|
|
699
759
|
raise ArgumentError, "pass either root_disk: or oci_upper_size:, not both"
|
|
700
760
|
end
|
|
701
|
-
# The core refuses patches on a snapshot-booted sandbox, but only after
|
|
702
|
-
# it has claimed the sandbox name on disk. Refuse the pair before any
|
|
703
|
-
# side effect.
|
|
704
|
-
if from_snapshot && patches && !Array(patches).empty?
|
|
705
|
-
raise ArgumentError,
|
|
706
|
-
"patches: cannot be combined with from_snapshot: (a snapshot restores its own " \
|
|
707
|
-
"root disk; apply changes after boot with sandbox.fs instead)"
|
|
708
|
-
end
|
|
709
761
|
# `fstype:` names the inner filesystem of a disk-image rootfs, so it only
|
|
710
762
|
# applies when `image:` is a disk-image path (a local path ending in
|
|
711
763
|
# .raw/.qcow2/.vmdk). Routing an OCI ref (e.g. "python") through the
|
|
@@ -720,7 +772,6 @@ module Microsandbox
|
|
|
720
772
|
end
|
|
721
773
|
opts = {}
|
|
722
774
|
opts["image"] = image.to_s if image
|
|
723
|
-
opts["from_snapshot"] = from_snapshot.to_s if from_snapshot
|
|
724
775
|
opts["fstype"] = fstype.to_s if fstype
|
|
725
776
|
opts["cpus"] = Integer(cpus) if cpus
|
|
726
777
|
opts["max_cpus"] = Integer(max_cpus) if max_cpus
|
|
@@ -747,9 +798,10 @@ module Microsandbox
|
|
|
747
798
|
opts["tls"] = normalize_tls(tls) if tls
|
|
748
799
|
opts["ipv4_pool"] = ipv4_pool.to_s if ipv4_pool
|
|
749
800
|
opts["ipv6_pool"] = ipv6_pool.to_s if ipv6_pool
|
|
750
|
-
opts
|
|
801
|
+
apply_connection_limits(opts, max_connections, max_tcp_connections, max_udp_connections)
|
|
751
802
|
set_bool(opts, "trust_host_cas", trust_host_cas)
|
|
752
803
|
set_bool(opts, "strict", strict)
|
|
804
|
+
opts["http"] = normalize_http(http) unless http.nil?
|
|
753
805
|
opts["rate_limiter"] = normalize_rate_limiter(rate_limiter) if rate_limiter
|
|
754
806
|
opts["proxy"] = OutboundProxy.coerce(proxy) unless proxy.nil?
|
|
755
807
|
opts["vsock"] = normalize_vsock(vsock) if vsock
|
|
@@ -770,7 +822,9 @@ module Microsandbox
|
|
|
770
822
|
opts["pull_policy"] = pull_policy.to_s if pull_policy
|
|
771
823
|
apply_registry_opts(opts, registry_auth, registry_insecure, registry_ca_certs)
|
|
772
824
|
opts["secrets"] = normalize_secrets(secrets) if secrets
|
|
773
|
-
|
|
825
|
+
unless secret_violation_action.nil?
|
|
826
|
+
opts["secret_violation_action"] = normalize_violation_action(secret_violation_action, "secret_violation_action")
|
|
827
|
+
end
|
|
774
828
|
opts["init"] = normalize_init(init) unless init.nil?
|
|
775
829
|
opts["ephemeral"] = true if ephemeral
|
|
776
830
|
opts["detached"] = true if detached
|
|
@@ -783,6 +837,68 @@ module Microsandbox
|
|
|
783
837
|
opts
|
|
784
838
|
end
|
|
785
839
|
|
|
840
|
+
# Boot a new sandbox from a snapshot (runtime v0.7; replaces 0.17's
|
|
841
|
+
# `create(from_snapshot:)`). A disk snapshot cold-boots its captured
|
|
842
|
+
# disk; a full snapshot ({Snapshot.create}'s `full:`) resumes the
|
|
843
|
+
# captured execution unless `disk_only: true`.
|
|
844
|
+
#
|
|
845
|
+
# The snapshot keeps its image, command, environment and network
|
|
846
|
+
# configuration; restore takes only destination choices. The network
|
|
847
|
+
# policy, security profile, vsock routes and connection caps of the
|
|
848
|
+
# source are not overridable here (planned for a later release).
|
|
849
|
+
#
|
|
850
|
+
# Upstream restores **detached**: without a block the sandbox keeps
|
|
851
|
+
# running after this process exits, until {Sandbox#stop}/{Sandbox#destroy}
|
|
852
|
+
# (or `max_duration:`/`idle_timeout:`). The block form stops it on exit,
|
|
853
|
+
# like {create}'s.
|
|
854
|
+
#
|
|
855
|
+
# @param snapshot [String, Pathname, SnapshotInfo] the snapshot: an id,
|
|
856
|
+
# `"<group>:<member>"`, a digest, or an artifact path (a relative path
|
|
857
|
+
# is anchored to the current directory now); a bare name selects a
|
|
858
|
+
# group head. A {SnapshotInfo} restores by its {SnapshotInfo#reference}.
|
|
859
|
+
# @param name [String] the new sandbox's name
|
|
860
|
+
# @param cpus [Integer, nil] guest vCPUs (disk boot; a full restore takes
|
|
861
|
+
# only the captured count)
|
|
862
|
+
# @param memory [Integer, nil] guest memory in MiB (same rule as `cpus:`)
|
|
863
|
+
# @param user [String, nil] default user for new execs
|
|
864
|
+
# @param log_level [String, Symbol, nil] host runtime log level
|
|
865
|
+
# @param max_duration [Integer, nil] maximum lifetime in seconds
|
|
866
|
+
# @param idle_timeout [Integer, nil] auto-stop after this many idle seconds
|
|
867
|
+
# @param volumes [Hash, nil] destination backing for captured mounts,
|
|
868
|
+
# in {create}'s `volumes:` shape, keyed by the captured guest path. By
|
|
869
|
+
# default every captured bind/named mount must be given one.
|
|
870
|
+
# @param ports [Hash, nil] new published TCP ports (host => guest)
|
|
871
|
+
# @param disable_network [Boolean] no network device (disk boot only)
|
|
872
|
+
# @param cow_memory [Boolean] map captured RAM copy-on-write (full restore)
|
|
873
|
+
# @param forked [Boolean, nil] deprecated alias of `cow_memory:`
|
|
874
|
+
# @param disk_only [Boolean] cold-boot a full snapshot's disk instead of
|
|
875
|
+
# resuming it
|
|
876
|
+
# @param snapshot_base [String, nil] the exact base snapshot for a
|
|
877
|
+
# dependent snapshot archive
|
|
878
|
+
# @param allow_missing_resources [Boolean] restore even when captured
|
|
879
|
+
# external resources have no destination backing (they stay unavailable)
|
|
880
|
+
# @param external_mount_policy [Symbol, String, nil] `:strict` (default)
|
|
881
|
+
# or `:relaxed` validation of supplied mount mappings
|
|
882
|
+
# @yieldparam sandbox [Sandbox]
|
|
883
|
+
# @return [Sandbox, Object] the sandbox, or the block's return value
|
|
884
|
+
def restore(snapshot, name:, **kwargs, &block)
|
|
885
|
+
reference, kind = snapshot_reference(snapshot)
|
|
886
|
+
opts = build_restore_opts(name: name, **kwargs)
|
|
887
|
+
opts["snapshot_kind"] = kind
|
|
888
|
+
Microsandbox.ensure_runtime!
|
|
889
|
+
# Upstream restores detached, so the restored sandbox never reports
|
|
890
|
+
# lifecycle ownership; it is always new, so the interrupt cleanup stops
|
|
891
|
+
# it regardless.
|
|
892
|
+
sandbox = acquire(always_stop: true) { Native::Sandbox.restore(reference, opts) }
|
|
893
|
+
return sandbox unless block_given?
|
|
894
|
+
|
|
895
|
+
begin
|
|
896
|
+
yield sandbox
|
|
897
|
+
ensure
|
|
898
|
+
teardown(sandbox)
|
|
899
|
+
end
|
|
900
|
+
end
|
|
901
|
+
|
|
786
902
|
# Restart a previously-defined sandbox by name.
|
|
787
903
|
# @return [Sandbox]
|
|
788
904
|
def start(name, detached: false)
|
|
@@ -828,6 +944,23 @@ module Microsandbox
|
|
|
828
944
|
|
|
829
945
|
private
|
|
830
946
|
|
|
947
|
+
# max_tcp_connections: / max_udp_connections: (runtime v0.7), with the
|
|
948
|
+
# deprecated max_connections: alias of the TCP cap, as in the Python SDK.
|
|
949
|
+
# 0 selects unlimited; nil leaves the runtime default.
|
|
950
|
+
def apply_connection_limits(opts, legacy, tcp, udp)
|
|
951
|
+
unless legacy.nil?
|
|
952
|
+
raise ArgumentError, "max_connections: and max_tcp_connections: are mutually exclusive" unless tcp.nil?
|
|
953
|
+
warn "Microsandbox: max_connections: is deprecated; use max_tcp_connections:", uplevel: 3
|
|
954
|
+
tcp = legacy
|
|
955
|
+
end
|
|
956
|
+
{"max_tcp_connections" => tcp, "max_udp_connections" => udp}.each do |key, value|
|
|
957
|
+
next if value.nil?
|
|
958
|
+
limit = Integer(value)
|
|
959
|
+
raise ArgumentError, "#{key}: must be >= 0 (0 means unlimited), got #{value.inspect}" if limit.negative?
|
|
960
|
+
opts[key] = limit
|
|
961
|
+
end
|
|
962
|
+
end
|
|
963
|
+
|
|
831
964
|
# Coerce a seconds value to a finite, non-negative Float. Rejects negatives,
|
|
832
965
|
# NaN, and infinities *here* (a clean ArgumentError) rather than letting them
|
|
833
966
|
# reach the native layer, where `Duration::from_secs_f64` panics across the
|
|
@@ -875,6 +1008,113 @@ module Microsandbox
|
|
|
875
1008
|
opts
|
|
876
1009
|
end
|
|
877
1010
|
|
|
1011
|
+
# Block-form teardown shared by {create}, {connect_or_create} and
|
|
1012
|
+
# {restore}: a bounded stop (see {bounded_stop}) — only when this call
|
|
1013
|
+
# owns the lifecycle, for {connect_or_create} — best-effort.
|
|
1014
|
+
def teardown(sandbox, only_if_owned: false)
|
|
1015
|
+
bounded_stop(sandbox) if !only_if_owned || sandbox.owns_lifecycle?
|
|
1016
|
+
rescue Microsandbox::Error
|
|
1017
|
+
# best-effort cleanup; ignore stop failures during teardown
|
|
1018
|
+
end
|
|
1019
|
+
|
|
1020
|
+
# Stop `target` (a {Sandbox} or its native object) without hanging: a
|
|
1021
|
+
# graceful stop with a {BLOCK_STOP_TIMEOUT} budget, then a kill with a
|
|
1022
|
+
# BLOCK_KILL_TIMEOUT budget. Both budgets are enforced natively and
|
|
1023
|
+
# cover the name's transition lock too: since runtime v0.7 a plain stop
|
|
1024
|
+
# waits forever and never escalates, and a plain kill waits for that
|
|
1025
|
+
# lock without a deadline. A kill that fails or runs out of time is
|
|
1026
|
+
# reported with a warning, never raised: the caller's own result or
|
|
1027
|
+
# exception must win.
|
|
1028
|
+
def bounded_stop(target)
|
|
1029
|
+
target.stop_with_timeout(BLOCK_STOP_TIMEOUT.to_f)
|
|
1030
|
+
rescue StopTimeoutError
|
|
1031
|
+
begin
|
|
1032
|
+
target.kill_with_timeout(BLOCK_KILL_TIMEOUT.to_f)
|
|
1033
|
+
rescue Microsandbox::Error => e
|
|
1034
|
+
cleanup_warning(target, e)
|
|
1035
|
+
end
|
|
1036
|
+
end
|
|
1037
|
+
|
|
1038
|
+
# Report a cleanup that gave up. Best-effort from end to end: building
|
|
1039
|
+
# or writing the warning (a closed `$stderr`, a broken logging pipe)
|
|
1040
|
+
# must never replace the caller's own result or exception, and a failed
|
|
1041
|
+
# warning is not reported through another one.
|
|
1042
|
+
def cleanup_warning(target, error)
|
|
1043
|
+
warn "microsandbox: cleanup gave up on sandbox #{cleanup_name(target).inspect}, which " \
|
|
1044
|
+
"may still be running: the graceful stop timed out and the kill failed (#{error.class}: #{error.message})"
|
|
1045
|
+
rescue
|
|
1046
|
+
nil
|
|
1047
|
+
end
|
|
1048
|
+
|
|
1049
|
+
# The name for a cleanup warning; never raises over the caller's exception.
|
|
1050
|
+
def cleanup_name(target)
|
|
1051
|
+
target.name
|
|
1052
|
+
rescue => e
|
|
1053
|
+
"<unknown: #{e.class}>"
|
|
1054
|
+
end
|
|
1055
|
+
|
|
1056
|
+
# The `[value, kind]` pair {restore} hands the native layer: a String is
|
|
1057
|
+
# read by the backend ("auto"), a Pathname is a path, and a
|
|
1058
|
+
# {SnapshotInfo} keeps the kind of its reference.
|
|
1059
|
+
def snapshot_reference(snapshot)
|
|
1060
|
+
case snapshot
|
|
1061
|
+
when SnapshotInfo
|
|
1062
|
+
if snapshot.reference
|
|
1063
|
+
[snapshot.reference, snapshot.reference_kind || "auto"]
|
|
1064
|
+
elsif snapshot.path
|
|
1065
|
+
[snapshot.path, "path"]
|
|
1066
|
+
elsif snapshot.id
|
|
1067
|
+
[snapshot.id, "id"]
|
|
1068
|
+
else
|
|
1069
|
+
[snapshot.digest, "auto"]
|
|
1070
|
+
end
|
|
1071
|
+
when Pathname
|
|
1072
|
+
[snapshot.to_s, "path"]
|
|
1073
|
+
when String, Symbol
|
|
1074
|
+
[snapshot.to_s, "auto"]
|
|
1075
|
+
else
|
|
1076
|
+
raise ArgumentError,
|
|
1077
|
+
"snapshot must be an id, \"<group>:<member>\", digest or path String, a Pathname, " \
|
|
1078
|
+
"or a SnapshotInfo (got #{snapshot.class})"
|
|
1079
|
+
end
|
|
1080
|
+
end
|
|
1081
|
+
|
|
1082
|
+
RESTORE_MOUNT_POLICIES = %w[strict relaxed].freeze
|
|
1083
|
+
private_constant :RESTORE_MOUNT_POLICIES
|
|
1084
|
+
|
|
1085
|
+
# Validation and normalization for {restore} (pure, like
|
|
1086
|
+
# {build_create_opts}: a rejected option never provisions the runtime).
|
|
1087
|
+
def build_restore_opts(name:, cpus: nil, memory: nil, user: nil, log_level: nil,
|
|
1088
|
+
max_duration: nil, idle_timeout: nil, volumes: nil, ports: nil, disable_network: false,
|
|
1089
|
+
cow_memory: false, forked: nil, disk_only: false, snapshot_base: nil,
|
|
1090
|
+
allow_missing_resources: false, external_mount_policy: nil)
|
|
1091
|
+
opts = {"name" => name.to_s}
|
|
1092
|
+
opts["cpus"] = Integer(cpus) if cpus
|
|
1093
|
+
opts["memory"] = Integer(memory) if memory
|
|
1094
|
+
opts["user"] = user.to_s if user
|
|
1095
|
+
opts["log_level"] = log_level.to_s if log_level
|
|
1096
|
+
opts["max_duration"] = Integer(max_duration) if max_duration
|
|
1097
|
+
opts["idle_timeout"] = Integer(idle_timeout) if idle_timeout
|
|
1098
|
+
opts["volumes"] = normalize_volumes(volumes) if volumes
|
|
1099
|
+
opts["ports"] = intify_ports(ports) if ports
|
|
1100
|
+
opts["disable_network"] = true if disable_network
|
|
1101
|
+
unless forked.nil?
|
|
1102
|
+
warn "Microsandbox: Sandbox.restore(forked:) is deprecated; use cow_memory:", uplevel: 2
|
|
1103
|
+
end
|
|
1104
|
+
opts["cow_memory"] = true if cow_memory || forked
|
|
1105
|
+
opts["disk_only"] = true if disk_only
|
|
1106
|
+
opts["snapshot_base"] = snapshot_base.to_s if snapshot_base
|
|
1107
|
+
opts["allow_missing_resources"] = true if allow_missing_resources
|
|
1108
|
+
unless external_mount_policy.nil?
|
|
1109
|
+
policy = external_mount_policy.to_s
|
|
1110
|
+
unless RESTORE_MOUNT_POLICIES.include?(policy)
|
|
1111
|
+
raise ArgumentError, "external_mount_policy: must be :strict or :relaxed, got #{external_mount_policy.inspect}"
|
|
1112
|
+
end
|
|
1113
|
+
opts["external_mount_policy"] = policy
|
|
1114
|
+
end
|
|
1115
|
+
opts
|
|
1116
|
+
end
|
|
1117
|
+
|
|
878
1118
|
def stringify(hash)
|
|
879
1119
|
# Anything that converts to pairs is fine (a Hash, ENV, an Array of
|
|
880
1120
|
# pairs). For the rest, name the type, not the value: env values are
|
|
@@ -943,12 +1183,8 @@ module Microsandbox
|
|
|
943
1183
|
end
|
|
944
1184
|
|
|
945
1185
|
# Normalize secrets into per-secret string-keyed Hashes for the native
|
|
946
|
-
# layer. Each entry is a Hash (string or symbol keys)
|
|
947
|
-
#
|
|
948
|
-
# or :host_patterns (Array of wildcards like "*.stripe.com"). Optional:
|
|
949
|
-
# :placeholder, :require_tls, the injection toggles :inject_headers /
|
|
950
|
-
# :inject_basic_auth / :inject_query / :inject_body, and :on_violation (see
|
|
951
|
-
# {#normalize_violation}).
|
|
1186
|
+
# layer. Each entry is a Hash (string or symbol keys) in the runtime v0.7
|
|
1187
|
+
# vocabulary (see {#normalize_secret}).
|
|
952
1188
|
def normalize_secrets(secrets)
|
|
953
1189
|
if secrets.is_a?(Hash)
|
|
954
1190
|
# One spec given bare is fine. A Hash keyed by variable name is the
|
|
@@ -956,7 +1192,7 @@ module Microsandbox
|
|
|
956
1192
|
# else (the HOST variable to read); it is not a create-time spec.
|
|
957
1193
|
unless secrets.key?(:env) || secrets.key?("env")
|
|
958
1194
|
raise ArgumentError,
|
|
959
|
-
"secrets: takes an Array of Hashes like { env:, value:,
|
|
1195
|
+
"secrets: takes an Array of Hashes like { env:, value:, allow: [...] } at create time; " \
|
|
960
1196
|
"the { \"NAME\" => { ... } } form belongs to #modify"
|
|
961
1197
|
end
|
|
962
1198
|
secrets = [secrets]
|
|
@@ -1017,6 +1253,12 @@ module Microsandbox
|
|
|
1017
1253
|
out
|
|
1018
1254
|
end
|
|
1019
1255
|
|
|
1256
|
+
# Keys a modify-time secret spec accepts.
|
|
1257
|
+
MODIFY_SECRET_KEYS = %w[env value store placeholder allowed_hosts].freeze
|
|
1258
|
+
# Upstream's v0.7 modify policy keys, not bound yet.
|
|
1259
|
+
MODIFY_SECRET_LATER_KEYS = %w[substitution violation_action require_tls_identity
|
|
1260
|
+
allow_placeholder_for passthrough].freeze
|
|
1261
|
+
|
|
1020
1262
|
def normalize_modify_secret(name, spec)
|
|
1021
1263
|
spec ||= {}
|
|
1022
1264
|
unless spec.is_a?(Hash)
|
|
@@ -1027,6 +1269,19 @@ module Microsandbox
|
|
|
1027
1269
|
raise ArgumentError,
|
|
1028
1270
|
"secret #{name.to_s.inspect}: spec must be a Hash (e.g. { value: ... } or { env: ... }), got #{spec.class}"
|
|
1029
1271
|
end
|
|
1272
|
+
keys = spec.keys.map(&:to_s)
|
|
1273
|
+
later = keys & MODIFY_SECRET_LATER_KEYS
|
|
1274
|
+
unless later.empty?
|
|
1275
|
+
raise ArgumentError,
|
|
1276
|
+
"secret #{name.to_s.inspect}: #{later.map { |k| ":#{k}" }.join(", ")} not yet supported on modify " \
|
|
1277
|
+
"(planned for 0.19.0); modify accepts #{MODIFY_SECRET_KEYS.map { |k| ":#{k}" }.join(", ")}"
|
|
1278
|
+
end
|
|
1279
|
+
unknown = keys - MODIFY_SECRET_KEYS
|
|
1280
|
+
unless unknown.empty?
|
|
1281
|
+
raise ArgumentError,
|
|
1282
|
+
"secret #{name.to_s.inspect}: unknown modify key(s) #{unknown.map { |k| ":#{k}" }.join(", ")} " \
|
|
1283
|
+
"(expected #{MODIFY_SECRET_KEYS.map { |k| ":#{k}" }.join(", ")})"
|
|
1284
|
+
end
|
|
1030
1285
|
env = fetch_opt(spec, :env)
|
|
1031
1286
|
value = fetch_opt(spec, :value)
|
|
1032
1287
|
store = fetch_opt(spec, :store)
|
|
@@ -1062,37 +1317,131 @@ module Microsandbox
|
|
|
1062
1317
|
s
|
|
1063
1318
|
end
|
|
1064
1319
|
|
|
1320
|
+
# Keys a create-time secret spec accepts (runtime v0.7 vocabulary, aligned
|
|
1321
|
+
# with the Python SDK's `Secret.env`).
|
|
1322
|
+
SECRET_KEYS = %w[env value allow allow_placeholder_for passthrough placeholder
|
|
1323
|
+
require_tls_identity violation_action substitution].freeze
|
|
1324
|
+
|
|
1325
|
+
# Keys of the 0.17.x (runtime v0.6) secret vocabulary, each with its
|
|
1326
|
+
# replacement. Rejected loudly: silently ignoring one would weaken the
|
|
1327
|
+
# policy the caller asked for (e.g. a dropped `on_violation:`).
|
|
1328
|
+
REMOVED_SECRET_KEYS = {
|
|
1329
|
+
"host" => "use allow: [...] (exact hosts and \"*.example.com\" wildcards share one list)",
|
|
1330
|
+
"hosts" => "use allow: [...] (exact hosts and \"*.example.com\" wildcards share one list)",
|
|
1331
|
+
"host_patterns" => "use allow: [...] (exact hosts and \"*.example.com\" wildcards share one list)",
|
|
1332
|
+
"inject_headers" => "use substitution: { headers: true|false }",
|
|
1333
|
+
"inject_query" => "use substitution: { query: true|false }",
|
|
1334
|
+
"inject_body" => "use substitution: { body: true|false }",
|
|
1335
|
+
"inject_basic_auth" => "removed in runtime v0.7, which has no Basic-only substitution. The " \
|
|
1336
|
+
"narrowest replacement is substitution: { headers: true, header_fields: [\"Authorization\"], " \
|
|
1337
|
+
"query: false, body: false }: it substitutes only in the Authorization header, but in any " \
|
|
1338
|
+
"scheme there (decoded Basic first, otherwise the literal placeholder, e.g. in a Bearer " \
|
|
1339
|
+
"token). Do not use a bare headers: true, which substitutes in every header. See " \
|
|
1340
|
+
"docs/configuration.md#migrating-secrets-from-017x",
|
|
1341
|
+
"require_tls" => "renamed to require_tls_identity:",
|
|
1342
|
+
"on_violation" => "renamed to violation_action: (:block, :block_and_log, or " \
|
|
1343
|
+
":block_and_terminate); hosts that may receive the unchanged placeholder go in " \
|
|
1344
|
+
"allow_placeholder_for: [...]"
|
|
1345
|
+
}.freeze
|
|
1346
|
+
|
|
1347
|
+
SUBSTITUTION_KEYS = %w[headers header_fields query body].freeze
|
|
1348
|
+
|
|
1349
|
+
# One create-time secret. Required: `env:`, `value:`, and a non-empty
|
|
1350
|
+
# `allow:` (hosts that may receive the real value; `"*.example.com"`
|
|
1351
|
+
# wildcards allowed; `"*"` means ANY host and maps to upstream's
|
|
1352
|
+
# `allow_any_host_dangerous`). Optional: `allow_placeholder_for:` (hosts
|
|
1353
|
+
# that may receive the unchanged placeholder; `passthrough:` is a
|
|
1354
|
+
# deprecated alias, merged), `placeholder:`, `require_tls_identity:`,
|
|
1355
|
+
# `violation_action:`, and `substitution: { headers:, header_fields:,
|
|
1356
|
+
# query:, body: }`.
|
|
1357
|
+
#
|
|
1358
|
+
# Error messages name keys, never values: a spec carries the cleartext
|
|
1359
|
+
# `:value`, and exception messages routinely land in logs.
|
|
1065
1360
|
def normalize_secret(spec)
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1361
|
+
keys = spec.keys.map(&:to_s)
|
|
1362
|
+
removed = keys.find { |k| REMOVED_SECRET_KEYS.key?(k) }
|
|
1363
|
+
if removed
|
|
1364
|
+
raise ArgumentError, "secret key :#{removed} was removed in 0.18.0 (runtime v0.7): #{REMOVED_SECRET_KEYS[removed]}"
|
|
1365
|
+
end
|
|
1366
|
+
unknown = keys - SECRET_KEYS
|
|
1367
|
+
unless unknown.empty?
|
|
1368
|
+
raise ArgumentError,
|
|
1369
|
+
"unknown secret key(s) #{unknown.map { |k| ":#{k}" }.join(", ")} " \
|
|
1370
|
+
"(expected #{SECRET_KEYS.map { |k| ":#{k}" }.join(", ")})"
|
|
1371
|
+
end
|
|
1372
|
+
if keys.size != keys.uniq.size
|
|
1373
|
+
raise ArgumentError, "secret spec gives the same key as both a Symbol and a String (keys: #{spec.keys.inspect})"
|
|
1374
|
+
end
|
|
1375
|
+
env = fetch_opt(spec, :env)
|
|
1376
|
+
value = fetch_opt(spec, :value)
|
|
1377
|
+
if env.nil? || value.nil?
|
|
1072
1378
|
raise ArgumentError, "secret spec needs :env and :value (got keys: #{spec.keys.inspect})"
|
|
1073
1379
|
end
|
|
1074
1380
|
out = {"env" => env.to_s, "value" => value.to_s}
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
hosts << single.to_s if single
|
|
1078
|
-
patterns = Array(spec[:host_patterns] || spec["host_patterns"]).map(&:to_s)
|
|
1079
|
-
if hosts.empty? && patterns.empty?
|
|
1080
|
-
# Keys only — this branch runs after :value is confirmed present, so
|
|
1081
|
-
# spec.inspect would always embed the cleartext secret value.
|
|
1381
|
+
allow = secret_host_list(fetch_opt(spec, :allow), "allow")
|
|
1382
|
+
if allow.empty?
|
|
1082
1383
|
raise ArgumentError,
|
|
1083
|
-
"secret
|
|
1384
|
+
"secret #{env.to_s.inspect} needs a non-empty allow: list of hosts that may receive the value " \
|
|
1385
|
+
"(use allow: [\"*\"] to allow any host)"
|
|
1084
1386
|
end
|
|
1085
|
-
out["
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1387
|
+
out["allow"] = allow
|
|
1388
|
+
placeholder_hosts = secret_host_list(fetch_opt(spec, :allow_placeholder_for), "allow_placeholder_for")
|
|
1389
|
+
passthrough = fetch_opt(spec, :passthrough)
|
|
1390
|
+
unless passthrough.nil?
|
|
1391
|
+
warn "Microsandbox: secret passthrough: is deprecated; use allow_placeholder_for:", uplevel: 4
|
|
1392
|
+
placeholder_hosts |= secret_host_list(passthrough, "passthrough")
|
|
1393
|
+
end
|
|
1394
|
+
out["allow_placeholder_for"] = placeholder_hosts unless placeholder_hosts.empty?
|
|
1395
|
+
pl = fetch_opt(spec, :placeholder)
|
|
1396
|
+
out["placeholder"] = pl.to_s unless pl.nil?
|
|
1397
|
+
set_bool(out, "require_tls_identity", fetch_opt(spec, :require_tls_identity))
|
|
1398
|
+
action = fetch_opt(spec, :violation_action)
|
|
1399
|
+
out["violation_action"] = normalize_violation_action(action, "violation_action") unless action.nil?
|
|
1400
|
+
sub = fetch_opt(spec, :substitution)
|
|
1401
|
+
out["substitution"] = normalize_substitution(sub, env) unless sub.nil?
|
|
1402
|
+
out
|
|
1403
|
+
end
|
|
1404
|
+
|
|
1405
|
+
# A host list (String or Array of Strings), as Strings. Empty entries are
|
|
1406
|
+
# rejected: an empty host pattern matches nothing the caller meant.
|
|
1407
|
+
def secret_host_list(hosts, key)
|
|
1408
|
+
return [] if hosts.nil?
|
|
1409
|
+
list = Array(hosts).map(&:to_s)
|
|
1410
|
+
if list.any?(&:empty?)
|
|
1411
|
+
raise ArgumentError, "secret #{key}: entries must be non-empty host names"
|
|
1412
|
+
end
|
|
1413
|
+
list
|
|
1414
|
+
end
|
|
1415
|
+
|
|
1416
|
+
# `substitution: { headers:, header_fields:, query:, body: }` — where the
|
|
1417
|
+
# real value replaces the placeholder. Defaults: headers on, query and
|
|
1418
|
+
# body off. Rejects a spec that would leave no location enabled, and
|
|
1419
|
+
# `header_fields:` together with `headers: false` (the upstream builder
|
|
1420
|
+
# and validator refuse both; checked here so neither reaches the core).
|
|
1421
|
+
def normalize_substitution(sub, env)
|
|
1422
|
+
raise ArgumentError, "secret #{env.to_s.inspect}: substitution: must be a Hash" unless sub.is_a?(Hash)
|
|
1423
|
+
unknown = sub.keys.map(&:to_s) - SUBSTITUTION_KEYS
|
|
1424
|
+
unless unknown.empty?
|
|
1425
|
+
raise ArgumentError,
|
|
1426
|
+
"secret #{env.to_s.inspect}: unknown substitution key(s) #{unknown.map { |k| ":#{k}" }.join(", ")} " \
|
|
1427
|
+
"(expected :headers, :header_fields, :query, :body)"
|
|
1428
|
+
end
|
|
1429
|
+
out = {}
|
|
1430
|
+
%i[headers query body].each { |k| set_bool(out, k.to_s, fetch_opt(sub, k)) }
|
|
1431
|
+
fields = fetch_opt(sub, :header_fields)
|
|
1432
|
+
unless fields.nil?
|
|
1433
|
+
fields = Array(fields).map(&:to_s)
|
|
1434
|
+
if !fields.empty? && out["headers"] == false
|
|
1435
|
+
raise ArgumentError,
|
|
1436
|
+
"secret #{env.to_s.inspect}: substitution header_fields: requires headers substitution (drop headers: false)"
|
|
1437
|
+
end
|
|
1438
|
+
out["header_fields"] = fields
|
|
1439
|
+
end
|
|
1440
|
+
headers = out.fetch("headers") { true }
|
|
1441
|
+
unless headers || out["query"] || out["body"]
|
|
1442
|
+
raise ArgumentError,
|
|
1443
|
+
"secret #{env.to_s.inspect}: substitution must leave at least one of headers, query, or body enabled"
|
|
1093
1444
|
end
|
|
1094
|
-
ov = spec[:on_violation] || spec["on_violation"]
|
|
1095
|
-
out["on_violation"] = normalize_violation(ov) if ov
|
|
1096
1445
|
out
|
|
1097
1446
|
end
|
|
1098
1447
|
|
|
@@ -1112,57 +1461,26 @@ module Microsandbox
|
|
|
1112
1461
|
out[key] = (value ? true : false) unless value.nil?
|
|
1113
1462
|
end
|
|
1114
1463
|
|
|
1115
|
-
#
|
|
1116
|
-
# layer: a String/Symbol block variant ("block"/"block_and_log"/
|
|
1117
|
-
# "block_and_terminate"), or a Hash describing a passthrough action
|
|
1118
|
-
# ({ passthrough_hosts:, passthrough_host_patterns:, passthrough_all_hosts: }).
|
|
1119
|
-
def normalize_violation(spec)
|
|
1120
|
-
case spec
|
|
1121
|
-
when String, Symbol
|
|
1122
|
-
# The bare "passthrough" string maps to passthrough-all-hosts, matching
|
|
1123
|
-
# the Python/Node SDKs (so a string-form policy copied from another SDK
|
|
1124
|
-
# ports over unchanged); block variants stay as their action string.
|
|
1125
|
-
if spec.to_s.strip.downcase.tr("-", "_") == "passthrough"
|
|
1126
|
-
{"passthrough_all_hosts" => true}
|
|
1127
|
-
else
|
|
1128
|
-
normalize_violation_action(spec)
|
|
1129
|
-
end
|
|
1130
|
-
when Hash
|
|
1131
|
-
hosts = Array(spec[:passthrough_hosts] || spec["passthrough_hosts"]).map(&:to_s)
|
|
1132
|
-
patterns = Array(spec[:passthrough_host_patterns] || spec["passthrough_host_patterns"]).map(&:to_s)
|
|
1133
|
-
all = !!(spec[:passthrough_all_hosts] || spec["passthrough_all_hosts"])
|
|
1134
|
-
# An empty passthrough (no hosts, no patterns, not all) passes nothing
|
|
1135
|
-
# through — a no-op the native builder silently degrades to its default
|
|
1136
|
-
# action. Reject it with actionable guidance rather than accept a spec
|
|
1137
|
-
# that does nothing the caller intended.
|
|
1138
|
-
if hosts.empty? && patterns.empty? && !all
|
|
1139
|
-
raise ArgumentError,
|
|
1140
|
-
"passthrough on_violation needs at least one of :passthrough_hosts, " \
|
|
1141
|
-
":passthrough_host_patterns, or :passthrough_all_hosts (use \"block\" " \
|
|
1142
|
-
"if blocking is the intent)"
|
|
1143
|
-
end
|
|
1144
|
-
out = {}
|
|
1145
|
-
out["passthrough_hosts"] = hosts unless hosts.empty?
|
|
1146
|
-
out["passthrough_host_patterns"] = patterns unless patterns.empty?
|
|
1147
|
-
out["passthrough_all_hosts"] = true if all
|
|
1148
|
-
out
|
|
1149
|
-
else
|
|
1150
|
-
raise ArgumentError, "on_violation must be a String or a Hash (got #{spec.inspect})"
|
|
1151
|
-
end
|
|
1152
|
-
end
|
|
1153
|
-
|
|
1154
|
-
# Map a block-variant action onto the canonical underscore spelling the
|
|
1464
|
+
# Map a secret-leak action onto the canonical underscore spelling the
|
|
1155
1465
|
# native layer expects. Also accepts the upstream kebab-case wire spellings
|
|
1156
1466
|
# ("block-and-log"/"block-and-terminate") used by the CLI, Go SDK, and
|
|
1157
1467
|
# sandbox config files, so a policy copied from another SDK ports over
|
|
1158
|
-
# unchanged instead of being rejected.
|
|
1159
|
-
|
|
1468
|
+
# unchanged instead of being rejected. Runtime v0.7 has no sandbox-wide
|
|
1469
|
+
# passthrough action; per-secret `allow_placeholder_for:` replaces it.
|
|
1470
|
+
def normalize_violation_action(spec, key)
|
|
1471
|
+
unless spec.is_a?(String) || spec.is_a?(Symbol)
|
|
1472
|
+
raise ArgumentError, "#{key}: must be a String or Symbol (got #{spec.class})"
|
|
1473
|
+
end
|
|
1160
1474
|
action = spec.to_s.strip.downcase.tr("-", "_")
|
|
1475
|
+
if action == "passthrough"
|
|
1476
|
+
raise ArgumentError,
|
|
1477
|
+
"#{key}: :passthrough was removed in 0.18.0 (runtime v0.7); list the hosts that may " \
|
|
1478
|
+
"receive the unchanged placeholder in each secret's allow_placeholder_for: instead"
|
|
1479
|
+
end
|
|
1161
1480
|
unless %w[block block_and_log block_and_terminate].include?(action)
|
|
1162
1481
|
raise ArgumentError,
|
|
1163
|
-
"unknown
|
|
1164
|
-
"block_and_log/block-and-log, block_and_terminate/block-and-terminate
|
|
1165
|
-
"passthrough, or a Hash with :passthrough_hosts/:passthrough_host_patterns/:passthrough_all_hosts)"
|
|
1482
|
+
"unknown #{key} #{spec.inspect} (expected block, " \
|
|
1483
|
+
"block_and_log/block-and-log, or block_and_terminate/block-and-terminate)"
|
|
1166
1484
|
end
|
|
1167
1485
|
action
|
|
1168
1486
|
end
|
|
@@ -1244,6 +1562,44 @@ module Microsandbox
|
|
|
1244
1562
|
out
|
|
1245
1563
|
end
|
|
1246
1564
|
|
|
1565
|
+
HTTP_KEYS = %i[deny_response format network_message secret_message].freeze
|
|
1566
|
+
private_constant :HTTP_KEYS
|
|
1567
|
+
|
|
1568
|
+
# Normalize the `http:` deny-response Hash (runtime v0.7). Validation
|
|
1569
|
+
# mirrors the Python SDK's HttpConfig; the two message keys additionally
|
|
1570
|
+
# need JSON responses that are switched on, the only mode that uses them.
|
|
1571
|
+
def normalize_http(http)
|
|
1572
|
+
unless http.is_a?(Hash)
|
|
1573
|
+
raise ArgumentError, "http: must be a Hash (deny_response:, format:, network_message:, secret_message:)"
|
|
1574
|
+
end
|
|
1575
|
+
given = http.to_h { |key, value| [key.to_sym, value] }.compact
|
|
1576
|
+
unknown = given.keys - HTTP_KEYS
|
|
1577
|
+
unless unknown.empty?
|
|
1578
|
+
raise ArgumentError, "unknown http: key(s) #{unknown.join(", ")} (expected #{HTTP_KEYS.join(", ")})"
|
|
1579
|
+
end
|
|
1580
|
+
out = {}
|
|
1581
|
+
if given.key?(:deny_response)
|
|
1582
|
+
value = given[:deny_response]
|
|
1583
|
+
raise ArgumentError, "http: deny_response: must be true or false" unless value == true || value == false
|
|
1584
|
+
out["deny_response"] = value
|
|
1585
|
+
end
|
|
1586
|
+
if given.key?(:format)
|
|
1587
|
+
value = given[:format]
|
|
1588
|
+
format = (value.is_a?(Symbol) || value.is_a?(String)) ? value.to_s.downcase : nil
|
|
1589
|
+
raise ArgumentError, "http: format: must be :json or :text, got #{value.inspect}" unless %w[json text].include?(format)
|
|
1590
|
+
out["format"] = format
|
|
1591
|
+
end
|
|
1592
|
+
%i[network_message secret_message].each do |key|
|
|
1593
|
+
next unless given.key?(key)
|
|
1594
|
+
value = given[key]
|
|
1595
|
+
raise ArgumentError, "http: #{key}: must be a String" unless value.is_a?(String)
|
|
1596
|
+
raise ArgumentError, "http: #{key}: needs the JSON format (it is the JSON `message`)" if out["format"] == "text"
|
|
1597
|
+
raise ArgumentError, "http: #{key}: has no effect with deny_response: false" if out["deny_response"] == false
|
|
1598
|
+
out[key.to_s] = value
|
|
1599
|
+
end
|
|
1600
|
+
out
|
|
1601
|
+
end
|
|
1602
|
+
|
|
1247
1603
|
# Normalize the `tls:` interception-tuning Hash for the native layer.
|
|
1248
1604
|
def normalize_tls(tls)
|
|
1249
1605
|
raise ArgumentError, "tls: must be a Hash" unless tls.is_a?(Hash)
|
|
@@ -1739,13 +2095,12 @@ module Microsandbox
|
|
|
1739
2095
|
|
|
1740
2096
|
# Latest resource-usage snapshot.
|
|
1741
2097
|
#
|
|
1742
|
-
# Raises a {Microsandbox::Error} ("sandbox N has no live metrics
|
|
1743
|
-
# called in the brief window right after
|
|
1744
|
-
#
|
|
1745
|
-
#
|
|
1746
|
-
#
|
|
1747
|
-
#
|
|
1748
|
-
# as fatal.
|
|
2098
|
+
# Raises a {Microsandbox::Error} ("sandbox N has no verified live metrics
|
|
2099
|
+
# slot" since runtime v0.7) when called in the brief window right after
|
|
2100
|
+
# {Sandbox.create} returns, before the runtime has registered the
|
|
2101
|
+
# sandbox's metrics slot: create does not wait for the first sample, so the
|
|
2102
|
+
# slot goes live a beat *after* boot (within a few hundred milliseconds);
|
|
2103
|
+
# retry for that window rather than treating the first failure as fatal.
|
|
1749
2104
|
# @return [Metrics]
|
|
1750
2105
|
def metrics
|
|
1751
2106
|
Metrics.new(@native.metrics)
|
|
@@ -1829,7 +2184,8 @@ module Microsandbox
|
|
|
1829
2184
|
#
|
|
1830
2185
|
# The first tick fires immediately, so opening the stream right after
|
|
1831
2186
|
# {Sandbox.create} can hit the same metrics-slot startup window as {#metrics}
|
|
1832
|
-
# and yield a transient "no live metrics slot" error on that first
|
|
2187
|
+
# and yield a transient "no verified live metrics slot" error on that first
|
|
2188
|
+
# tick.
|
|
1833
2189
|
# Because the stream is single-pass (a drained or errored stream is spent),
|
|
1834
2190
|
# make sure the slot is live *before* opening it — e.g. retry {#metrics}
|
|
1835
2191
|
# until it succeeds (the slot goes live within a few hundred milliseconds of
|
|
@@ -1860,9 +2216,11 @@ module Microsandbox
|
|
|
1860
2216
|
LogStream.new(@native.log_stream(opts))
|
|
1861
2217
|
end
|
|
1862
2218
|
|
|
1863
|
-
#
|
|
1864
|
-
#
|
|
1865
|
-
#
|
|
2219
|
+
# Request a graceful shutdown and wait, without a deadline, until the
|
|
2220
|
+
# runtime has released the sandbox. Since runtime v0.7 nothing escalates to
|
|
2221
|
+
# a kill: bound the wait with {#stop_with_timeout}, force it with {#kill}.
|
|
2222
|
+
# For fire-and-return `request_*` control, fetch a {SandboxHandle} via
|
|
2223
|
+
# {Sandbox.get}.
|
|
1866
2224
|
#
|
|
1867
2225
|
# Scoped to *this exact* sandbox: as of runtime v0.6.16 the stop carries this
|
|
1868
2226
|
# object's {#id}, so if the name has since been removed and recreated the
|
|
@@ -1882,13 +2240,39 @@ module Microsandbox
|
|
|
1882
2240
|
ExitStatus.new(@native.stop_and_wait)
|
|
1883
2241
|
end
|
|
1884
2242
|
|
|
1885
|
-
#
|
|
2243
|
+
# Request a graceful shutdown and wait at most `timeout` seconds (one
|
|
2244
|
+
# budget for dispatch and the runtime's release; runtime v0.7). Expiry
|
|
2245
|
+
# raises {StopTimeoutError} and kills nothing — the shutdown may still
|
|
2246
|
+
# complete later; call {#kill} if it must end now. A zero budget times out
|
|
2247
|
+
# before the request is sent. Scoped to this sandbox's {#id}, like {#stop}.
|
|
2248
|
+
# @param timeout [Numeric] seconds
|
|
2249
|
+
# @raise [StopTimeoutError] when the budget runs out
|
|
2250
|
+
# @return [nil]
|
|
2251
|
+
def stop_with_timeout(timeout)
|
|
2252
|
+
@native.stop_with_timeout(coerce_duration(timeout, "timeout"))
|
|
2253
|
+
nil
|
|
2254
|
+
end
|
|
2255
|
+
|
|
2256
|
+
# Force-kill the sandbox, then wait up to 5 seconds to observe it stopped.
|
|
2257
|
+
# Taking the name's transition lock first has no deadline: while another
|
|
2258
|
+
# lifecycle operation holds it, this waits. Use {#kill_with_timeout} for
|
|
2259
|
+
# one bound over the whole call.
|
|
1886
2260
|
# @return [nil]
|
|
1887
2261
|
def kill
|
|
1888
2262
|
@native.kill
|
|
1889
2263
|
nil
|
|
1890
2264
|
end
|
|
1891
2265
|
|
|
2266
|
+
# Force-kill under one budget of `timeout` seconds that covers the
|
|
2267
|
+
# transition lock, the kill request and observing the stop. Expiry raises
|
|
2268
|
+
# {Error}; the sandbox may then still be running.
|
|
2269
|
+
# @param timeout [Numeric]
|
|
2270
|
+
# @return [nil]
|
|
2271
|
+
def kill_with_timeout(timeout)
|
|
2272
|
+
@native.kill_with_timeout(coerce_duration(timeout, "timeout"))
|
|
2273
|
+
nil
|
|
2274
|
+
end
|
|
2275
|
+
|
|
1892
2276
|
# Trigger a graceful drain (SIGUSR1).
|
|
1893
2277
|
# @return [nil]
|
|
1894
2278
|
def drain
|
|
@@ -1928,9 +2312,10 @@ module Microsandbox
|
|
|
1928
2312
|
# Stop and start *this exact* sandbox, returning the new live sandbox
|
|
1929
2313
|
# (runtime v0.6.16). A created/stopped/crashed sandbox is started directly.
|
|
1930
2314
|
# This handle is spent afterwards — use the returned one.
|
|
1931
|
-
# @param force [Boolean]
|
|
1932
|
-
# @param timeout [Numeric, nil] graceful-shutdown seconds
|
|
1933
|
-
#
|
|
2315
|
+
# @param force [Boolean] force-kill instead of requesting a graceful shutdown
|
|
2316
|
+
# @param timeout [Numeric, nil] graceful-shutdown budget in seconds (the
|
|
2317
|
+
# core's default is 10); expiry raises {StopTimeoutError} and kills
|
|
2318
|
+
# nothing (runtime v0.7)
|
|
1934
2319
|
# @param detached [Boolean] start the replacement detached
|
|
1935
2320
|
# @raise [SandboxReplacedError] if the name now refers to a different sandbox
|
|
1936
2321
|
# @return [Sandbox]
|
|
@@ -1945,9 +2330,10 @@ module Microsandbox
|
|
|
1945
2330
|
# Stop and remove *this exact* sandbox (runtime v0.6.16) — the convergent
|
|
1946
2331
|
# equivalent of {#stop} followed by {Sandbox.remove}, with an identity check
|
|
1947
2332
|
# that refuses to remove a same-name replacement.
|
|
1948
|
-
# @param force [Boolean]
|
|
1949
|
-
# @param timeout [Numeric, nil] graceful-shutdown seconds
|
|
1950
|
-
#
|
|
2333
|
+
# @param force [Boolean] force-kill instead of requesting a graceful shutdown
|
|
2334
|
+
# @param timeout [Numeric, nil] graceful-shutdown budget in seconds (the
|
|
2335
|
+
# core's default is 10); expiry raises {StopTimeoutError} and kills
|
|
2336
|
+
# nothing (runtime v0.7)
|
|
1951
2337
|
# @raise [SandboxReplacedError] if the name now refers to a different sandbox
|
|
1952
2338
|
# @return [nil]
|
|
1953
2339
|
def destroy(force: false, timeout: nil)
|