kobako 0.31.0 → 0.32.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.
Files changed (133) 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 +125 -0
  5. data/Cargo.lock +457 -494
  6. data/README.md +2 -3
  7. data/ROADMAP.md +0 -1
  8. data/crates/kobako-runtime/CHANGELOG.md +90 -0
  9. data/crates/kobako-runtime/Cargo.toml +14 -15
  10. data/crates/kobako-runtime/README.md +1 -1
  11. data/crates/kobako-runtime/src/cred.rs +32 -20
  12. data/crates/kobako-runtime/src/filesystem/bind/fid.rs +300 -22
  13. data/crates/kobako-runtime/src/filesystem/bind/lookup.rs +56 -22
  14. data/crates/kobako-runtime/src/filesystem/bind/unicode.rs +109 -0
  15. data/crates/kobako-runtime/src/filesystem/bind/walk.rs +33 -14
  16. data/crates/kobako-runtime/src/filesystem/bind.rs +393 -220
  17. data/crates/kobako-runtime/src/filesystem/overlay/stack/copy_up.rs +2 -0
  18. data/crates/kobako-runtime/src/filesystem/overlay/stack.rs +9 -10
  19. data/crates/kobako-runtime/src/filesystem/overlay.rs +277 -46
  20. data/crates/kobako-runtime/src/filesystem/rdir.rs +8 -27
  21. data/crates/kobako-runtime/src/filesystem/testing.rs +31 -0
  22. data/crates/kobako-runtime/src/filesystem/tmpfs.rs +47 -13
  23. data/crates/kobako-runtime/src/filesystem.rs +2 -0
  24. data/crates/kobako-runtime/src/fork.rs +239 -16
  25. data/crates/kobako-runtime/src/limits.rs +17 -41
  26. data/crates/kobako-runtime/src/locking/seqlock.rs +29 -3
  27. data/crates/kobako-runtime/src/locking.rs +508 -113
  28. data/crates/kobako-runtime/src/memcg.rs +83 -160
  29. data/crates/kobako-runtime/src/mount.rs +0 -30
  30. data/crates/kobako-runtime/src/net/connections.rs +53 -13
  31. data/crates/kobako-runtime/src/net/egress.rs +44 -24
  32. data/crates/kobako-runtime/src/net/http.rs +888 -456
  33. data/crates/kobako-runtime/src/net/lookup.rs +150 -50
  34. data/crates/kobako-runtime/src/net/namespace.rs +97 -95
  35. data/crates/kobako-runtime/src/net/reactor.rs +298 -203
  36. data/crates/kobako-runtime/src/net/resolv/darwin.rs +8 -3
  37. data/crates/kobako-runtime/src/net/resolv/stub/tests.rs +50 -0
  38. data/crates/kobako-runtime/src/net/resolv/stub.rs +29 -23
  39. data/crates/kobako-runtime/src/net/resolv/windows.rs +14 -44
  40. data/crates/kobako-runtime/src/net/resolv.rs +39 -15
  41. data/crates/kobako-runtime/src/net/skbuff.rs +109 -0
  42. data/crates/kobako-runtime/src/net/socket.rs +51 -52
  43. data/crates/kobako-runtime/src/net/task.rs +223 -0
  44. data/crates/kobako-runtime/src/net/tcp.rs +410 -158
  45. data/crates/kobako-runtime/src/net/tls.rs +65 -3
  46. data/crates/kobako-runtime/src/net/transport.rs +72 -47
  47. data/crates/kobako-runtime/src/net/udp.rs +231 -129
  48. data/crates/kobako-runtime/src/net.rs +3 -0
  49. data/crates/kobako-runtime/src/sched.rs +244 -58
  50. data/crates/kobako-runtime/src/security.rs +27 -16
  51. data/crates/kobako-runtime/src/vfs/dentry.rs +80 -41
  52. data/crates/kobako-runtime/src/vfs/file.rs +52 -53
  53. data/crates/kobako-runtime/src/vfs/kern_path.rs +24 -11
  54. data/crates/kobako-runtime/src/vfs/namei.rs +399 -184
  55. data/crates/kobako-runtime/src/vfs/namespace.rs +123 -40
  56. data/crates/kobako-runtime/src/vfs/stat.rs +105 -16
  57. data/crates/kobako-runtime/src/vfs.rs +1 -0
  58. data/crates/kobako-runtime/src/wait.rs +75 -50
  59. data/crates/kobako-transport/CHANGELOG.md +7 -0
  60. data/crates/kobako-transport/Cargo.toml +1 -1
  61. data/crates/kobako-transport/README.md +1 -1
  62. data/crates/kobako-wasmtime/CHANGELOG.md +47 -0
  63. data/crates/kobako-wasmtime/Cargo.toml +27 -6
  64. data/crates/kobako-wasmtime/README.md +3 -3
  65. data/crates/kobako-wasmtime/src/abi.rs +2 -1
  66. data/crates/kobako-wasmtime/src/ambient.rs +11 -2
  67. data/crates/kobako-wasmtime/src/cache/unix.rs +95 -0
  68. data/crates/kobako-wasmtime/src/cache/windows.rs +359 -0
  69. data/crates/kobako-wasmtime/src/cache.rs +88 -103
  70. data/crates/kobako-wasmtime/src/driver.rs +40 -27
  71. data/crates/kobako-wasmtime/src/invocation.rs +21 -7
  72. data/crates/kobako-wasmtime/src/lib.rs +2 -0
  73. data/crates/kobako-wasmtime/src/limiter.rs +78 -25
  74. data/crates/kobako-wasmtime/src/preview1/descriptors.rs +13 -17
  75. data/crates/kobako-wasmtime/src/preview1/differential/mount.rs +4 -5
  76. data/crates/kobako-wasmtime/src/preview1/differential.rs +1 -1
  77. data/crates/kobako-wasmtime/src/preview1/fd.rs +23 -19
  78. data/crates/kobako-wasmtime/src/preview1/mount_view.rs +130 -197
  79. data/crates/kobako-wasmtime/src/preview1/path.rs +3 -3
  80. data/crates/kobako-wasmtime/src/preview1/poll.rs +28 -22
  81. data/crates/kobako-wasmtime/src/preview1/random.rs +125 -0
  82. data/crates/kobako-wasmtime/src/preview1/testing.rs +31 -0
  83. data/crates/kobako-wasmtime/src/preview1.rs +85 -9
  84. data/crates/kobako-wasmtime/src/preview2/filesystem.rs +2 -2
  85. data/crates/kobako-wasmtime/src/preview2/host.rs +609 -249
  86. data/crates/kobako-wasmtime/src/preview2/http.rs +299 -215
  87. data/crates/kobako-wasmtime/src/preview2/io.rs +17 -4
  88. data/crates/kobako-wasmtime/src/preview2/table.rs +24 -72
  89. data/crates/kobako-wasmtime/src/trap.rs +68 -23
  90. data/crates/kobako-wasmtime/src/waits.rs +59 -0
  91. data/crates/kobako-wasmtime/src/wasi.rs +91 -10
  92. data/crates/kobako-wasmtime/witx/wasi_snapshot_preview1.witx +13 -0
  93. data/data/kobako.wasm +0 -0
  94. data/ext/kobako/Cargo.toml +6 -2
  95. data/ext/kobako/src/escape.rs +332 -26
  96. data/ext/kobako/src/filesystem/grants.rs +5 -7
  97. data/ext/kobako/src/filesystem/ruby.rs +10 -3
  98. data/ext/kobako/src/filesystem.rs +47 -8
  99. data/ext/kobako/src/fork.rs +72 -0
  100. data/ext/kobako/src/gvl.rs +499 -76
  101. data/ext/kobako/src/handoff.rs +490 -0
  102. data/ext/kobako/src/lib.rs +10 -0
  103. data/ext/kobako/src/network.rs +5 -3
  104. data/ext/kobako/src/pinned_value.rs +28 -15
  105. data/ext/kobako/src/runtime/bridge.rs +32 -25
  106. data/ext/kobako/src/runtime.rs +74 -43
  107. data/lib/kobako/catalog/handles.rb +9 -5
  108. data/lib/kobako/codec/decoder.rb +1 -1
  109. data/lib/kobako/codec/state.rb +2 -18
  110. data/lib/kobako/codec/value_budget.rb +4 -4
  111. data/lib/kobako/codec.rb +5 -6
  112. data/lib/kobako/errors.rb +4 -7
  113. data/lib/kobako/filesystem.rb +1 -1
  114. data/lib/kobako/fork.rb +42 -0
  115. data/lib/kobako/handle.rb +1 -2
  116. data/lib/kobako/sandbox.rb +17 -36
  117. data/lib/kobako/sandbox_options.rb +7 -9
  118. data/lib/kobako/usage.rb +4 -2
  119. data/lib/kobako/version.rb +1 -1
  120. data/lib/kobako.rb +2 -2
  121. data/sig/kobako/catalog/handles.rbs +2 -0
  122. data/sig/kobako/codec/state.rbs +0 -4
  123. data/sig/kobako/codec/value_budget.rbs +1 -1
  124. data/sig/kobako/codec.rbs +2 -2
  125. data/sig/kobako/errors.rbs +0 -3
  126. data/sig/kobako/fork.rbs +17 -0
  127. data/sig/kobako/runtime.rbs +2 -2
  128. data/sig/kobako/sandbox.rbs +3 -12
  129. data/sig/kobako/sandbox_options.rbs +0 -2
  130. metadata +15 -4
  131. data/lib/kobako/pool.rb +0 -162
  132. data/sig/core/thread.rbs +0 -6
  133. data/sig/kobako/pool.rbs +0 -46
@@ -1,15 +1,14 @@
1
- //! The memory one Invocation may take, as Linux's memory cgroup counts a
2
- //! task's pages and the memory the kernel holds for it, socket buffers among
3
- //! them, in one `memory.current` against `memory.max`.
1
+ //! The memory one Invocation's guest may take, as a virtual machine's RAM is
2
+ //! bounded apart from what its runtime holds for it: the guest's pages count
3
+ //! in one `memory.current` against `memory.max`, and what the host holds for
4
+ //! the guest is bounded by counts and fixed sizes instead.
4
5
 
5
6
  use std::sync::{Arc, Mutex, PoisonError};
6
7
 
7
- use crate::Errno;
8
-
9
- /// What one Invocation has taken against its `memory_limit`: the guest's
10
- /// memory grown past where the run began, and what the host holds on its
11
- /// behalf between calls. `None` bounds neither, while both are still counted
12
- /// so the peak is reported either way.
8
+ /// What one Invocation's guest has taken against its `memory_limit`: its
9
+ /// memories, tables, and heaps grown past what its Guest Binary declares.
10
+ /// `None` bounds nothing, while the growth is still counted so the peak is
11
+ /// reported either way.
13
12
  pub struct MemoryBudget {
14
13
  limit: Option<usize>,
15
14
  charged: Mutex<Charged>,
@@ -17,18 +16,21 @@ pub struct MemoryBudget {
17
16
 
18
17
  #[derive(Default)]
19
18
  struct Charged {
20
- /// Whether the guest's growth is charged; it is not before the run
21
- /// begins, as the image's own allocation must pass.
19
+ /// Whether the guest's growth is charged; it is not before the run's
20
+ /// Store opens, nor once the run returns.
22
21
  armed: bool,
23
- baseline: usize,
22
+ /// What the Guest Binary declares, which the growth that creates its
23
+ /// memories and tables fills without charge.
24
+ declared: usize,
25
+ /// Every growth since the budget was armed, whichever memory, table, or
26
+ /// heap it lands in.
24
27
  grown: usize,
25
- held: usize,
26
28
  peak: usize,
27
29
  }
28
30
 
29
31
  impl Charged {
30
32
  fn total(&self) -> usize {
31
- self.grown.saturating_add(self.held)
33
+ self.grown.saturating_sub(self.declared)
32
34
  }
33
35
  }
34
36
 
@@ -40,15 +42,20 @@ impl MemoryBudget {
40
42
  })
41
43
  }
42
44
 
43
- /// Charge the guest's memory past `baseline` from now on, as the run
44
- /// begins, so the image's allocation and what earlier runs left behind
45
- /// take none of it.
46
- pub fn arm(&self, baseline: usize) {
45
+ /// The `memory_limit` the budget holds the run to; `None` lifts it.
46
+ pub fn limit(&self) -> Option<usize> {
47
+ self.limit
48
+ }
49
+
50
+ /// Charge the guest's growth from now on, as the run's Store opens, past
51
+ /// the `declared` bytes its Guest Binary's memories and tables start
52
+ /// with, so what the binary declares takes none of it.
53
+ pub fn arm(&self, declared: usize) {
47
54
  let mut charged = self.charged();
48
55
  charged.armed = true;
49
- charged.baseline = baseline;
56
+ charged.declared = declared;
50
57
  charged.grown = 0;
51
- charged.peak = charged.held;
58
+ charged.peak = 0;
52
59
  }
53
60
 
54
61
  /// Stop charging the guest's growth once the run returns, so reading its
@@ -57,31 +64,30 @@ impl MemoryBudget {
57
64
  self.charged().armed = false;
58
65
  }
59
66
 
60
- /// The most the run held at once. A charge the budget refused never
61
- /// raises it, so it never passes `memory_limit`.
67
+ /// The most the run held at once, never past `memory_limit`, since a
68
+ /// growth the budget refused never raises it.
62
69
  pub fn peak(&self) -> usize {
63
70
  self.charged().peak
64
71
  }
65
72
 
66
- /// Charge the guest's memory growing to `desired` bytes, refused where it
67
- /// and what the host holds would pass the limit. What it answers gives the
68
- /// charge back should the growth then fail.
69
- pub fn charge_growth(&self, desired: usize) -> Result<GrowthCharge, MemoryLimitExceeded> {
73
+ /// Charge `bytes` the guest's memory, table, or heap grows by, refused
74
+ /// where they and what is already taken would pass the limit, as each
75
+ /// page a cgroup's task faults in adds to one `memory.current`. What it
76
+ /// answers gives the charge back should the growth then fail.
77
+ pub fn charge_growth(&self, bytes: usize) -> Result<GrowthCharge, MemoryLimitExceeded> {
70
78
  let mut charged = self.charged();
71
- let before = GrowthCharge {
72
- grown: charged.grown,
73
- };
74
79
  if !charged.armed {
75
- return Ok(before);
80
+ return Ok(GrowthCharge { bytes: 0 });
76
81
  }
77
- let grown = desired.saturating_sub(charged.baseline);
78
- let total = grown.saturating_add(charged.held);
82
+ let before = charged.grown;
83
+ charged.grown = before.saturating_add(bytes);
84
+ let total = charged.total();
79
85
  if let Some(limit) = self.limit.filter(|&limit| total > limit) {
80
- return Err(MemoryLimitExceeded::new(desired, limit));
86
+ charged.grown = before;
87
+ return Err(MemoryLimitExceeded::new(total, limit));
81
88
  }
82
- charged.grown = grown;
83
89
  charged.peak = charged.peak.max(total);
84
- Ok(before)
90
+ Ok(GrowthCharge { bytes })
85
91
  }
86
92
 
87
93
  /// Give back `charge`, a growth the Engine failed to make once the budget
@@ -89,29 +95,8 @@ impl MemoryBudget {
89
95
  /// `page_counter_cancel` gives a charge back. The peak keeps it, as the
90
96
  /// watermark the charge raised stays.
91
97
  pub fn cancel_growth(&self, charge: GrowthCharge) {
92
- self.charged().grown = charge.grown;
93
- }
94
-
95
- /// Charge `bytes` the host holds for the guest, refused as ENOMEM where
96
- /// they would pass the limit, as `try_charge_memcg` refuses a charge past
97
- /// `memory.max`.
98
- pub(crate) fn try_charge(&self, bytes: usize) -> Result<(), Errno> {
99
98
  let mut charged = self.charged();
100
- let total = charged
101
- .total()
102
- .checked_add(bytes)
103
- .filter(|&total| self.limit.is_none_or(|limit| total <= limit))
104
- .ok_or(Errno::OutOfMemory)?;
105
- charged.held += bytes;
106
- charged.peak = charged.peak.max(total);
107
- Ok(())
108
- }
109
-
110
- /// `bytes` charged earlier are held no more, as `memcg_uncharge` gives
111
- /// them back.
112
- fn uncharge(&self, bytes: usize) {
113
- let mut charged = self.charged();
114
- charged.held = charged.held.saturating_sub(bytes);
99
+ charged.grown = charged.grown.saturating_sub(charge.bytes);
115
100
  }
116
101
 
117
102
  fn charged(&self) -> std::sync::MutexGuard<'_, Charged> {
@@ -119,77 +104,26 @@ impl MemoryBudget {
119
104
  }
120
105
  }
121
106
 
122
- /// What the guest's growth stood at before one charge, which a growth the
123
- /// Engine fails to make gives back through `MemoryBudget::cancel_growth`.
107
+ /// The bytes one growth charged, which a growth the Engine fails to make
108
+ /// gives back through `MemoryBudget::cancel_growth`.
124
109
  #[must_use]
125
110
  pub struct GrowthCharge {
126
- grown: usize,
127
- }
128
-
129
- /// Memory the host holds for a guest, charged to its budget as it is taken
130
- /// and given back as it is let go, as `obj_cgroup_charge` and
131
- /// `obj_cgroup_uncharge` count what the kernel holds for a cgroup by the byte:
132
- /// a socket's queues, a listing, or a part of a request the guest builds.
133
- pub struct MemoryCharge {
134
- budget: Arc<MemoryBudget>,
135
111
  bytes: usize,
136
112
  }
137
113
 
138
- impl MemoryCharge {
139
- /// Charge `bytes` to `budget`, refused past its limit as `ENOMEM`.
140
- pub fn new(budget: &Arc<MemoryBudget>, bytes: usize) -> Result<Self, Errno> {
141
- budget.try_charge(bytes)?;
142
- Ok(Self {
143
- budget: budget.clone(),
144
- bytes,
145
- })
146
- }
147
-
148
- /// A charge to `budget` that holds nothing yet.
149
- pub fn empty(budget: &Arc<MemoryBudget>) -> Self {
150
- Self {
151
- budget: budget.clone(),
152
- bytes: 0,
153
- }
154
- }
155
-
156
- /// The bytes it holds.
157
- pub fn bytes(&self) -> usize {
158
- self.bytes
159
- }
160
-
161
- /// Hold `bytes` in place of what it held, charging only the growth and
162
- /// giving back the rest; refused past the limit as `ENOMEM`, keeping what
163
- /// it held.
164
- pub fn resize(&mut self, bytes: usize) -> Result<(), Errno> {
165
- match bytes.checked_sub(self.bytes) {
166
- Some(growth) => self.budget.try_charge(growth)?,
167
- None => self.budget.uncharge(self.bytes - bytes),
168
- }
169
- self.bytes = bytes;
170
- Ok(())
171
- }
172
- }
173
-
174
- impl Drop for MemoryCharge {
175
- fn drop(&mut self) {
176
- self.budget.uncharge(self.bytes);
177
- }
178
- }
179
-
180
114
  /// A growth past the per-invocation memory budget. An Engine ends the
181
115
  /// invocation with it, and a Wasm Driver finds it again to classify the
182
116
  /// failure as a memory-limit `Trap`. Callers use the `Display` impl below — no
183
117
  /// field is read directly — so the inner state stays private.
184
- #[derive(Debug)]
118
+ #[derive(Clone, Debug)]
185
119
  pub struct MemoryLimitExceeded {
186
- desired: usize,
120
+ requested: usize,
187
121
  limit: usize,
188
122
  }
189
123
 
190
124
  impl MemoryLimitExceeded {
191
- pub fn new(desired: usize, limit: usize) -> Self {
192
- Self { desired, limit }
125
+ pub fn new(requested: usize, limit: usize) -> Self {
126
+ Self { requested, limit }
193
127
  }
194
128
  }
195
129
 
@@ -199,7 +133,7 @@ impl std::fmt::Display for MemoryLimitExceeded {
199
133
  f,
200
134
  "memory usage exceeded memory_limit: \
201
135
  requested={} bytes, limit={} bytes",
202
- self.desired, self.limit
136
+ self.requested, self.limit
203
137
  )
204
138
  }
205
139
  }
@@ -210,30 +144,48 @@ impl std::error::Error for MemoryLimitExceeded {}
210
144
  mod tests {
211
145
  //! The arithmetic of one budget, so a regression that breaks the baseline
212
146
  //! (dropping its subtraction, or letting `arm` carry stale state across
213
- //! invocations) or counts the guest and the host apart is caught without
214
- //! an Engine.
147
+ //! invocations) is caught without a wasmtime `Engine`.
215
148
  use super::MemoryBudget;
216
- use crate::Errno;
217
149
 
218
- fn assert_charged(budget: &MemoryBudget, desired: usize, what: &str) {
150
+ fn assert_charged(budget: &MemoryBudget, bytes: usize, what: &str) {
219
151
  assert!(
220
- budget.charge_growth(desired).is_ok(),
152
+ budget.charge_growth(bytes).is_ok(),
221
153
  "{what} through MemoryBudget::charge_growth must be allowed"
222
154
  );
223
155
  }
224
156
 
225
- fn assert_refused(budget: &MemoryBudget, desired: usize, what: &str) {
157
+ fn assert_refused(budget: &MemoryBudget, bytes: usize, what: &str) {
226
158
  assert!(
227
- budget.charge_growth(desired).is_err(),
159
+ budget.charge_growth(bytes).is_err(),
228
160
  "{what} through MemoryBudget::charge_growth must be refused"
229
161
  );
230
162
  }
231
163
 
232
164
  // @behavior S-113
233
165
  #[test]
234
- fn a_growth_before_the_budget_is_armed_is_not_bounded() {
166
+ fn what_the_guest_binary_declares_takes_none_of_the_budget() {
167
+ let budget = MemoryBudget::new(Some(1 << 20));
168
+ budget.arm(2 << 20);
169
+ assert_charged(&budget, 2 << 20, "creating 2 MiB a guest binary declares");
170
+ assert_eq!(
171
+ budget.peak(),
172
+ 0,
173
+ "creating the 2 MiB a guest binary declares under a 1 MiB limit must leave the \
174
+ peak memory at 0"
175
+ );
176
+ }
177
+
178
+ // @behavior S-256
179
+ #[test]
180
+ fn growths_of_apart_memories_add_up() {
235
181
  let budget = MemoryBudget::new(Some(1 << 20));
236
- assert_charged(&budget, 100 << 20, "a 100 MiB growth before arm");
182
+ budget.arm(0);
183
+ assert_charged(&budget, 3 << 18, "a 768 KiB growth of one memory");
184
+ assert_refused(
185
+ &budget,
186
+ 3 << 18,
187
+ "a 768 KiB growth of another memory beside it under a 1 MiB limit",
188
+ );
237
189
  }
238
190
 
239
191
  // @behavior S-114
@@ -260,34 +212,6 @@ mod tests {
260
212
  );
261
213
  }
262
214
 
263
- // @behavior S-209
264
- #[test]
265
- fn a_growth_past_what_the_host_left_of_the_limit_is_refused() {
266
- let budget = MemoryBudget::new(Some(1 << 20));
267
- budget.arm(2 << 20);
268
- budget
269
- .try_charge(3 << 18)
270
- .expect("768 KiB of socket buffers under a 1 MiB limit must be charged");
271
- assert_refused(
272
- &budget,
273
- (2 << 20) + (1 << 19),
274
- "a 512 KiB growth beside 768 KiB the host holds under a 1 MiB limit",
275
- );
276
- }
277
-
278
- // @behavior S-209
279
- #[test]
280
- fn a_host_charge_past_what_the_guest_left_of_the_limit_is_refused() {
281
- let budget = MemoryBudget::new(Some(1 << 20));
282
- budget.arm(2 << 20);
283
- assert_charged(&budget, (2 << 20) + (3 << 18), "a 768 KiB growth");
284
- assert_eq!(
285
- budget.try_charge(1 << 19),
286
- Err(Errno::OutOfMemory),
287
- "512 KiB of host buffers beside a 768 KiB growth under a 1 MiB limit must answer ENOMEM"
288
- );
289
- }
290
-
291
215
  // @behavior S-008
292
216
  #[test]
293
217
  fn each_arming_charges_from_its_own_baseline() {
@@ -327,16 +251,15 @@ mod tests {
327
251
  let budget = MemoryBudget::new(Some(1 << 20));
328
252
  budget.arm(2 << 20);
329
253
  assert_charged(&budget, (2 << 20) + (1 << 18), "a 256 KiB growth");
330
- assert_charged(&budget, (2 << 20) + (1 << 19), "a 512 KiB growth");
331
- budget
332
- .try_charge(1 << 17)
333
- .expect("128 KiB of host buffers must be charged");
334
- budget.uncharge(1 << 17);
254
+ let failed = budget
255
+ .charge_growth(1 << 18)
256
+ .expect("another 256 KiB growth within the limit must be allowed");
257
+ budget.cancel_growth(failed);
335
258
  assert_eq!(
336
259
  budget.peak(),
337
- (1 << 19) + (1 << 17),
338
- "a 512 KiB growth beside 128 KiB the host held for a while through \
339
- MemoryBudget::peak must report 640 KiB"
260
+ 1 << 19,
261
+ "a 256 KiB growth, then one wasmtime failed to make, must leave the peak memory \
262
+ at the 512 KiB the watermark reached"
340
263
  );
341
264
  }
342
265
 
@@ -131,33 +131,3 @@ impl fmt::Display for UnplacedMountError {
131
131
  }
132
132
 
133
133
  impl std::error::Error for UnplacedMountError {}
134
-
135
- /// The Mounts among `mounts` no other one's path holds, the roots every guest
136
- /// path starts from. One beneath another is reached only by a walk into it, so
137
- /// each spelling of its path meets what Linux's mount namespace holds there.
138
- pub fn outermost_of<'a>(mounts: &[&'a Mount]) -> Vec<&'a Mount> {
139
- mounts
140
- .iter()
141
- .copied()
142
- .filter(|mount| {
143
- outermost_holder_of(&mount.at, mounts.iter().map(|other| (other.at(), ()))).is_none()
144
- })
145
- .collect()
146
- }
147
-
148
- /// The outermost of `holders`, each a guest path with what stands there,
149
- /// holding the guest path `at` strictly beneath it; none where none holds it.
150
- pub(crate) fn outermost_holder_of<'a, T>(
151
- at: &str,
152
- holders: impl IntoIterator<Item = (&'a str, T)>,
153
- ) -> Option<(&'a str, T)> {
154
- holders
155
- .into_iter()
156
- .filter(|(above, _)| {
157
- *above != at
158
- && at
159
- .strip_prefix(above)
160
- .is_some_and(|rest| *above == "/" || rest.starts_with('/'))
161
- })
162
- .min_by_key(|(above, _)| above.len())
163
- }
@@ -1,23 +1,23 @@
1
1
  //! The connections a guest holds open, counted against its Sandbox and the
2
- //! process, as a cgroup's `pids.max` bounds the tasks beneath it, so one
3
- //! tenant cannot starve another of host sockets. A socket and an HTTP request
4
- //! each hold one place until released, and a request's connection still
5
- //! sending holds it until it closes; a name lookup holds one until it answers
6
- //! or is dropped, which cancels its query.
2
+ //! process, as a cgroup's `pids.max` bounds the tasks beneath it. A socket
3
+ //! and an HTTP request each hold one place until released, and a request's
4
+ //! connection still sending holds it until it closes; a name lookup holds one
5
+ //! until it answers or is dropped, which cancels its query. A budget bounds
6
+ //! how many one Invocation makes in all.
7
7
 
8
+ use std::sync::atomic::{AtomicUsize, Ordering};
8
9
  use std::sync::{Arc, LazyLock, Mutex, PoisonError};
9
10
 
10
11
  use crate::fork::{Pid, ProcessLocal};
12
+ use crate::Errno;
11
13
 
12
- /// The process's limit until a Host App sets its own, as tokio caps its
13
- /// blocking pool.
14
- const DEFAULT_PROCESS_LIMIT: usize = 512;
14
+ /// The process's own count, which bounds nothing until a Host App sets a
15
+ /// limit: what its Sandboxes hold together is the Host App's to size, as the
16
+ /// host's descriptors are shared with every other program on it.
17
+ static PROCESS: LazyLock<Arc<OpenConnections>> = LazyLock::new(|| OpenConnections::new(None));
15
18
 
16
- static PROCESS: LazyLock<Arc<OpenConnections>> =
17
- LazyLock::new(|| OpenConnections::new(Some(DEFAULT_PROCESS_LIMIT)));
18
-
19
- /// Every connection the process's Sandboxes hold open together, 512 at most
20
- /// until `set_limit` moves it.
19
+ /// Every connection the process's Sandboxes hold open together, unbounded
20
+ /// until `set_limit` bounds it.
21
21
  pub fn process_connections() -> &'static Arc<OpenConnections> {
22
22
  &PROCESS
23
23
  }
@@ -112,6 +112,33 @@ pub(super) fn open_within(
112
112
  })
113
113
  }
114
114
 
115
+ /// The connections one Invocation may still make, as a Worker spends its
116
+ /// subrequests: one is spent as a lookup or a dial is about to leave the host,
117
+ /// and none comes back, whether that attempt fails or the connection closes.
118
+ pub(crate) struct ConnectionBudget {
119
+ /// What is left; `None` lifts the budget.
120
+ left: Option<AtomicUsize>,
121
+ }
122
+
123
+ impl ConnectionBudget {
124
+ /// A budget of `limit` connections; `None` lifts it.
125
+ pub(crate) fn new(limit: Option<usize>) -> Arc<Self> {
126
+ Arc::new(Self {
127
+ left: limit.map(AtomicUsize::new),
128
+ })
129
+ }
130
+
131
+ /// Spend one, or answer `WouldBlock`, spending nothing, once none is left.
132
+ pub(crate) fn spend(&self) -> Result<(), Errno> {
133
+ let Some(left) = &self.left else {
134
+ return Ok(());
135
+ };
136
+ left.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_sub(1))
137
+ .map(drop)
138
+ .map_err(|_| Errno::WouldBlock)
139
+ }
140
+ }
141
+
115
142
  #[cfg(test)]
116
143
  mod tests {
117
144
  use super::*;
@@ -176,4 +203,17 @@ mod tests {
176
203
  the next, and None must lift the limit"
177
204
  );
178
205
  }
206
+
207
+ // @behavior NW-060
208
+ #[test]
209
+ fn the_processs_limit_starts_lifted() {
210
+ assert_eq!(
211
+ *process_connections()
212
+ .limit
213
+ .lock()
214
+ .unwrap_or_else(PoisonError::into_inner),
215
+ None,
216
+ "process_connections must bound nothing until a Host App sets a limit"
217
+ );
218
+ }
179
219
  }
@@ -24,11 +24,19 @@ use crate::policy::Policy;
24
24
  /// passes the ruleset as itself, so a virtual one is refused, and an IPv6 one
25
25
  /// reaches nothing. A header the guest may not set is refused too, so the
26
26
  /// seam frames every request itself, and each name goes on in lower case,
27
- /// as a request policy reads it. So is a method that is not a token,
28
- /// which HTTP cannot carry, and a target not in origin form, which a proxy
29
- /// would forward past the judged authority, and a bound credential's header
30
- /// carrying its placeholder more than once. Any refusal answers `Denied`, and
31
- /// nothing is sent.
27
+ /// as a request policy reads it. So is each request below:
28
+ ///
29
+ /// - a method that is not a token, which HTTP cannot carry;
30
+ /// - a target not in origin form, which a proxy would forward past the
31
+ /// judged authority;
32
+ /// - CONNECT, which takes no origin form and opens a tunnel no rule judges;
33
+ /// - a TRACE with content, which RFC 9110 § 9.3.8 bars; content written
34
+ /// once it is sent is refused as `EPIPE`;
35
+ /// - a bound credential's header carrying its placeholder more than once.
36
+ ///
37
+ /// A TRACE takes no credential, as a request in clear takes none, since the
38
+ /// server echoes what it reads. Any refusal answers `Denied`, and nothing is
39
+ /// sent.
32
40
  pub fn send(
33
41
  net: &Namespace,
34
42
  cred: &Arc<Cred>,
@@ -36,7 +44,12 @@ pub fn send(
36
44
  ) -> Result<Arc<Exchange>, HttpError> {
37
45
  let in_origin_form = to_origin_form(&request.path_with_query).as_deref()
38
46
  == Some(request.path_with_query.as_str());
39
- if !in_origin_form || !is_token(&request.method) {
47
+ let is_trace = reads_as(&request.method, "TRACE");
48
+ if !in_origin_form
49
+ || !is_token(&request.method)
50
+ || reads_as(&request.method, "CONNECT")
51
+ || (is_trace && request.body.has_content())
52
+ {
40
53
  return Err(HttpError::Denied);
41
54
  }
42
55
  request.headers = std::mem::take(&mut request.headers)
@@ -82,23 +95,29 @@ pub fn send(
82
95
  return Err(HttpError::Denied);
83
96
  }
84
97
  let swaps = match request.scheme {
85
- Scheme::Https => proxy
98
+ Scheme::Https if !is_trace => proxy
86
99
  .swaps_of(&policy_request, &request.headers)
87
100
  .ok_or(HttpError::Denied)?,
88
- Scheme::Http => Vec::new(),
101
+ Scheme::Https | Scheme::Http => Vec::new(),
89
102
  };
90
103
  request.authority = join_authority(&host, port, request.scheme);
91
104
  request.swaps = swaps;
105
+ if is_trace {
106
+ request.body.refuse_content();
107
+ }
108
+
109
+ Exchange::start(
110
+ net.outbound().clone(),
111
+ request,
112
+ |place| Connector::new(net, judged, port, place),
113
+ net.open_connections(),
114
+ )
115
+ }
92
116
 
93
- net.within_connection_budget(HttpError::ConnectionLimitReached, || {
94
- Exchange::start(
95
- net.outbound().clone(),
96
- request,
97
- |place| Connector::new(net, cred, judged, port, place),
98
- net.open_connections(),
99
- cred,
100
- )
101
- })
117
+ /// Whether a lenient server reads `method` as `name`, ignoring case as a deny
118
+ /// rule is matched, so no spelling escapes what holds for that method.
119
+ fn reads_as(method: &str, name: &str) -> bool {
120
+ method.eq_ignore_ascii_case(name)
102
121
  }
103
122
 
104
123
  /// The entries' request policies, which judge a request `send` found its
@@ -115,13 +134,14 @@ impl EgressProxy {
115
134
  self.request.iter().all(|policy| policy.allows(request))
116
135
  }
117
136
 
118
- /// The credentials bound to `request`, one over `https`: an entry's own
119
- /// endpoint names its exact host and allows it, and the placement's header
120
- /// carries the placeholder once. `None` is a request to refuse: one whose
121
- /// header carries a placeholder more than once, as OpenShell's leaves no
122
- /// second placeholder resolved, so a swap grows a request by one secret at
123
- /// most; or one whose credential's source could not answer. Each source answers here, on the guest thread, so its time counts
124
- /// against the deadline.
137
+ /// The credentials bound to `request`, one over `https` and no TRACE: an
138
+ /// entry's own endpoint names its exact host and allows it, and the
139
+ /// placement's header carries the placeholder once. `None` is a request to
140
+ /// refuse: one whose header carries a placeholder more than once, as
141
+ /// OpenShell's leaves no second placeholder resolved, so a swap grows a
142
+ /// request by one secret at most; or one whose credential's source could
143
+ /// not answer. Each source answers here, on the guest thread, so its time
144
+ /// counts against the deadline.
125
145
  pub(crate) fn swaps_of(
126
146
  &self,
127
147
  request: &Request<'_>,