kobako 0.30.0 → 0.31.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 (266) hide show
  1. checksums.yaml +4 -4
  2. data/.release-please-manifest.json +1 -1
  3. data/CHANGELOG.md +335 -0
  4. data/Cargo.lock +469 -11
  5. data/README.md +43 -3
  6. data/ROADMAP.md +1 -1
  7. data/crates/kobako-runtime/CHANGELOG.md +219 -0
  8. data/crates/kobako-runtime/Cargo.toml +51 -3
  9. data/crates/kobako-runtime/README.md +7 -4
  10. data/crates/kobako-runtime/src/cred.rs +124 -0
  11. data/crates/kobako-runtime/src/dispatch.rs +4 -5
  12. data/crates/kobako-runtime/src/endpoint/buffer.rs +153 -44
  13. data/crates/kobako-runtime/src/endpoint/dispatch.rs +80 -41
  14. data/crates/kobako-runtime/src/endpoint/invoke.rs +23 -36
  15. data/crates/kobako-runtime/src/endpoint.rs +137 -36
  16. data/crates/kobako-runtime/src/errno.rs +391 -0
  17. data/crates/kobako-runtime/src/error.rs +31 -10
  18. data/crates/kobako-runtime/src/filesystem/anon_inodes.rs +52 -0
  19. data/crates/kobako-runtime/src/filesystem/bind/lookup.rs +52 -14
  20. data/crates/kobako-runtime/src/filesystem/bind/walk.rs +19 -20
  21. data/crates/kobako-runtime/src/filesystem/bind.rs +437 -245
  22. data/crates/kobako-runtime/src/filesystem/overlay/file.rs +6 -6
  23. data/crates/kobako-runtime/src/filesystem/overlay/path.rs +43 -65
  24. data/crates/kobako-runtime/src/filesystem/overlay/stack/copy_up.rs +9 -16
  25. data/crates/kobako-runtime/src/filesystem/overlay/stack/dir.rs +47 -72
  26. data/crates/kobako-runtime/src/filesystem/overlay/stack/namei.rs +12 -12
  27. data/crates/kobako-runtime/src/filesystem/overlay/stack/readdir.rs +4 -7
  28. data/crates/kobako-runtime/src/filesystem/overlay/stack.rs +121 -37
  29. data/crates/kobako-runtime/src/filesystem/overlay.rs +302 -343
  30. data/crates/kobako-runtime/src/filesystem/pipe.rs +12 -9
  31. data/crates/kobako-runtime/src/filesystem/rdir.rs +15 -32
  32. data/crates/kobako-runtime/src/filesystem/tmpfs/seed.rs +32 -0
  33. data/crates/kobako-runtime/src/filesystem/tmpfs/tmpfile.rs +3 -3
  34. data/crates/kobako-runtime/src/filesystem/tmpfs/whiteout.rs +57 -35
  35. data/crates/kobako-runtime/src/filesystem/tmpfs/xattr.rs +2 -2
  36. data/crates/kobako-runtime/src/filesystem/tmpfs.rs +172 -160
  37. data/crates/kobako-runtime/src/filesystem/wrap.rs +36 -52
  38. data/crates/kobako-runtime/src/filesystem.rs +6 -3
  39. data/crates/kobako-runtime/src/fork.rs +96 -0
  40. data/crates/kobako-runtime/src/grant.rs +3 -0
  41. data/crates/kobako-runtime/src/hashtable.rs +4 -2
  42. data/crates/kobako-runtime/src/lib.rs +18 -7
  43. data/crates/kobako-runtime/src/limits.rs +195 -0
  44. data/crates/kobako-runtime/src/locking.rs +10 -0
  45. data/crates/kobako-runtime/src/memcg.rs +383 -0
  46. data/crates/kobako-runtime/src/mount.rs +67 -9
  47. data/crates/kobako-runtime/src/net/backends.rs +43 -0
  48. data/crates/kobako-runtime/src/net/connections.rs +179 -0
  49. data/crates/kobako-runtime/src/net/credential.rs +125 -0
  50. data/crates/kobako-runtime/src/net/egress.rs +160 -0
  51. data/crates/kobako-runtime/src/net/family.rs +181 -0
  52. data/crates/kobako-runtime/src/net/http.rs +2733 -0
  53. data/crates/kobako-runtime/src/net/lookup.rs +285 -0
  54. data/crates/kobako-runtime/src/net/mock.rs +251 -0
  55. data/crates/kobako-runtime/src/net/namespace.rs +1366 -0
  56. data/crates/kobako-runtime/src/net/reactor.rs +531 -0
  57. data/crates/kobako-runtime/src/net/resolv/darwin.rs +275 -0
  58. data/crates/kobako-runtime/src/net/resolv/stub/tests.rs +469 -0
  59. data/crates/kobako-runtime/src/net/resolv/stub.rs +536 -0
  60. data/crates/kobako-runtime/src/net/resolv/windows.rs +248 -0
  61. data/crates/kobako-runtime/src/net/resolv.rs +227 -0
  62. data/crates/kobako-runtime/src/net/socket.rs +870 -0
  63. data/crates/kobako-runtime/src/net/tcp.rs +1588 -0
  64. data/crates/kobako-runtime/src/net/tls.rs +58 -0
  65. data/crates/kobako-runtime/src/net/transport.rs +279 -0
  66. data/crates/kobako-runtime/src/net/udp.rs +1003 -0
  67. data/crates/kobako-runtime/src/net.rs +42 -0
  68. data/crates/kobako-runtime/src/network/builder.rs +177 -0
  69. data/crates/kobako-runtime/src/network/ruleset.rs +777 -0
  70. data/crates/kobako-runtime/src/network.rs +551 -0
  71. data/crates/kobako-runtime/src/policy.rs +16 -0
  72. data/crates/kobako-runtime/src/profile.rs +29 -144
  73. data/crates/kobako-runtime/src/runtime.rs +3 -5
  74. data/crates/kobako-runtime/src/sched.rs +130 -29
  75. data/crates/kobako-runtime/src/security/entry_policy.rs +22 -0
  76. data/crates/kobako-runtime/src/{vfs/cred.rs → security/hooks.rs} +52 -144
  77. data/crates/kobako-runtime/src/security/mount_policy.rs +158 -0
  78. data/crates/kobako-runtime/src/security.rs +101 -196
  79. data/crates/kobako-runtime/src/snapshot.rs +121 -2
  80. data/crates/kobako-runtime/src/vfs/attr.rs +5 -5
  81. data/crates/kobako-runtime/src/vfs/dentry.rs +143 -89
  82. data/crates/kobako-runtime/src/vfs/file.rs +199 -203
  83. data/crates/kobako-runtime/src/vfs/inode.rs +41 -45
  84. data/crates/kobako-runtime/src/vfs/kern_path.rs +38 -42
  85. data/crates/kobako-runtime/src/vfs/mount.rs +10 -9
  86. data/crates/kobako-runtime/src/vfs/namei.rs +829 -700
  87. data/crates/kobako-runtime/src/vfs/namespace.rs +162 -0
  88. data/crates/kobako-runtime/src/vfs/open_files.rs +69 -0
  89. data/crates/kobako-runtime/src/vfs/openat2.rs +3 -3
  90. data/crates/kobako-runtime/src/vfs/path.rs +6 -6
  91. data/crates/kobako-runtime/src/vfs/readdir.rs +6 -6
  92. data/crates/kobako-runtime/src/vfs/stat.rs +159 -23
  93. data/crates/kobako-runtime/src/vfs/super_block.rs +18 -14
  94. data/crates/kobako-runtime/src/vfs/utimes.rs +37 -27
  95. data/crates/kobako-runtime/src/vfs.rs +9 -6
  96. data/crates/kobako-runtime/src/wait.rs +356 -0
  97. data/crates/kobako-transport/CHANGELOG.md +31 -0
  98. data/crates/kobako-transport/Cargo.toml +1 -1
  99. data/crates/kobako-transport/README.md +3 -4
  100. data/crates/kobako-transport/src/abi.rs +78 -72
  101. data/crates/kobako-transport/src/envelope/bytes.rs +17 -6
  102. data/crates/kobako-transport/src/envelope/call.rs +32 -4
  103. data/crates/kobako-transport/src/envelope/error_record.rs +21 -0
  104. data/crates/kobako-transport/src/envelope/name.rs +99 -0
  105. data/crates/kobako-transport/src/envelope/outcome.rs +9 -9
  106. data/crates/kobako-transport/src/envelope/preamble.rs +24 -21
  107. data/crates/kobako-transport/src/envelope/reply.rs +27 -27
  108. data/crates/kobako-transport/src/envelope/unsupported.rs +10 -10
  109. data/crates/kobako-transport/src/envelope.rs +13 -8
  110. data/crates/kobako-wasmtime/CHANGELOG.md +161 -0
  111. data/crates/kobako-wasmtime/Cargo.toml +26 -7
  112. data/crates/kobako-wasmtime/README.md +3 -2
  113. data/crates/kobako-wasmtime/build/preview2.rs +1339 -0
  114. data/crates/kobako-wasmtime/build.rs +16 -0
  115. data/crates/kobako-wasmtime/src/abi.rs +17 -37
  116. data/crates/kobako-wasmtime/src/ambient.rs +33 -18
  117. data/crates/kobako-wasmtime/src/cache.rs +23 -15
  118. data/crates/kobako-wasmtime/src/config.rs +52 -68
  119. data/crates/kobako-wasmtime/src/driver.rs +48 -63
  120. data/crates/kobako-wasmtime/src/exports.rs +143 -17
  121. data/crates/kobako-wasmtime/src/guest.rs +12 -6
  122. data/crates/kobako-wasmtime/src/guest_binary.rs +14 -0
  123. data/crates/kobako-wasmtime/src/imports.rs +42 -18
  124. data/crates/kobako-wasmtime/src/instance_pre.rs +4 -4
  125. data/crates/kobako-wasmtime/src/invocation.rs +74 -12
  126. data/crates/kobako-wasmtime/src/lib.rs +5 -3
  127. data/crates/kobako-wasmtime/src/limiter.rs +70 -5
  128. data/crates/kobako-wasmtime/src/preview1/descriptors.rs +309 -0
  129. data/crates/kobako-wasmtime/src/preview1/differential/mount.rs +5 -15
  130. data/crates/kobako-wasmtime/src/preview1/differential.rs +27 -31
  131. data/crates/kobako-wasmtime/src/preview1/errno.rs +55 -66
  132. data/crates/kobako-wasmtime/src/preview1/fd.rs +327 -296
  133. data/crates/kobako-wasmtime/src/preview1/memory.rs +21 -12
  134. data/crates/kobako-wasmtime/src/preview1/mount_view/wrap.rs +34 -53
  135. data/crates/kobako-wasmtime/src/preview1/mount_view.rs +231 -217
  136. data/crates/kobako-wasmtime/src/preview1/path.rs +56 -121
  137. data/crates/kobako-wasmtime/src/preview1/poll.rs +244 -120
  138. data/crates/kobako-wasmtime/src/preview1/sock.rs +10 -8
  139. data/crates/kobako-wasmtime/src/preview1/testsuite.rs +5 -15
  140. data/crates/kobako-wasmtime/src/preview1.rs +46 -42
  141. data/crates/kobako-wasmtime/src/preview2/abi.rs +227 -0
  142. data/crates/kobako-wasmtime/src/preview2/error.rs +118 -0
  143. data/crates/kobako-wasmtime/src/preview2/filesystem.rs +122 -0
  144. data/crates/kobako-wasmtime/src/preview2/host.rs +3959 -0
  145. data/crates/kobako-wasmtime/src/preview2/http.rs +1503 -0
  146. data/crates/kobako-wasmtime/src/preview2/io.rs +315 -0
  147. data/crates/kobako-wasmtime/src/preview2/sockets.rs +379 -0
  148. data/crates/kobako-wasmtime/src/preview2/table.rs +305 -0
  149. data/crates/kobako-wasmtime/src/preview2.rs +57 -0
  150. data/crates/kobako-wasmtime/src/trap.rs +24 -9
  151. data/crates/kobako-wasmtime/src/wasi.rs +210 -81
  152. data/crates/kobako-wasmtime/wit/deps/cli.wit +233 -0
  153. data/crates/kobako-wasmtime/wit/deps/clocks.wit +162 -0
  154. data/crates/kobako-wasmtime/wit/deps/filesystem.wit +589 -0
  155. data/crates/kobako-wasmtime/wit/deps/http.wit +733 -0
  156. data/crates/kobako-wasmtime/wit/deps/io.wit +299 -0
  157. data/crates/kobako-wasmtime/wit/deps/random.wit +92 -0
  158. data/crates/kobako-wasmtime/wit/deps/sockets.wit +949 -0
  159. data/data/kobako.wasm +0 -0
  160. data/ext/kobako/Cargo.toml +1 -1
  161. data/ext/kobako/src/{runtime/errors.rs → errors.rs} +34 -26
  162. data/ext/kobako/src/{runtime/escape.rs → escape.rs} +42 -11
  163. data/ext/kobako/src/{runtime/filesystem → filesystem}/grants.rs +30 -26
  164. data/ext/kobako/src/{runtime/filesystem → filesystem}/ruby.rs +149 -168
  165. data/ext/kobako/src/{runtime/filesystem.rs → filesystem.rs} +24 -15
  166. data/ext/kobako/src/gvl.rs +306 -0
  167. data/ext/kobako/src/lib.rs +64 -3
  168. data/ext/kobako/src/network/mock.rs +187 -0
  169. data/ext/kobako/src/network.rs +591 -0
  170. data/ext/kobako/src/runtime/bridge.rs +30 -29
  171. data/ext/kobako/src/runtime/snapshot.rs +4 -4
  172. data/ext/kobako/src/runtime.rs +221 -143
  173. data/ext/kobako/src/wire.rs +42 -0
  174. data/lib/kobako/catalog/extensions.rb +14 -2
  175. data/lib/kobako/catalog/flags.rb +3 -5
  176. data/lib/kobako/catalog/grants.rb +5 -4
  177. data/lib/kobako/catalog/handles.rb +5 -27
  178. data/lib/kobako/catalog/mount.rb +11 -3
  179. data/lib/kobako/catalog/network.rb +35 -0
  180. data/lib/kobako/catalog/replacements.rb +28 -0
  181. data/lib/kobako/catalog/services.rb +5 -19
  182. data/lib/kobako/catalog/snippets.rb +3 -18
  183. data/lib/kobako/catalog.rb +3 -0
  184. data/lib/kobako/codec/{utils.rb → boundary.rb} +4 -2
  185. data/lib/kobako/codec/decoder.rb +4 -4
  186. data/lib/kobako/codec/ext_types.rb +3 -3
  187. data/lib/kobako/codec/handle_walk.rb +3 -43
  188. data/lib/kobako/codec/value_budget.rb +132 -40
  189. data/lib/kobako/codec.rb +1 -1
  190. data/lib/kobako/context.rb +24 -11
  191. data/lib/kobako/errors.rb +15 -12
  192. data/lib/kobako/extension.rb +3 -2
  193. data/lib/kobako/filesystem.rb +9 -2
  194. data/lib/kobako/handle.rb +2 -2
  195. data/lib/kobako/names.rb +28 -0
  196. data/lib/kobako/network.rb +210 -0
  197. data/lib/kobako/outcome.rb +7 -7
  198. data/lib/kobako/pool.rb +45 -23
  199. data/lib/kobako/runtime.rb +3 -2
  200. data/lib/kobako/sandbox.rb +92 -35
  201. data/lib/kobako/sandbox_options.rb +41 -106
  202. data/lib/kobako/transport/argument_wrap.rb +64 -0
  203. data/lib/kobako/transport/block_failure.rb +1 -1
  204. data/lib/kobako/transport/dispatcher.rb +6 -6
  205. data/lib/kobako/transport/exposure.rb +26 -15
  206. data/lib/kobako/transport/reflection.rb +21 -4
  207. data/lib/kobako/transport/run.rb +8 -23
  208. data/lib/kobako/transport/yielder.rb +2 -9
  209. data/lib/kobako/transport.rb +1 -0
  210. data/lib/kobako/version.rb +1 -1
  211. data/lib/kobako.rb +6 -2
  212. data/release-please-config.json +15 -0
  213. data/sig/core/thread.rbs +6 -0
  214. data/sig/kobako/catalog/extensions.rbs +2 -0
  215. data/sig/kobako/catalog/grants.rbs +7 -4
  216. data/sig/kobako/catalog/handles.rbs +0 -2
  217. data/sig/kobako/catalog/mount.rbs +3 -1
  218. data/sig/kobako/catalog/network.rbs +20 -0
  219. data/sig/kobako/catalog/replacements.rbs +14 -0
  220. data/sig/kobako/catalog/services.rbs +0 -4
  221. data/sig/kobako/catalog/snippets.rbs +0 -2
  222. data/sig/kobako/codec/{utils.rbs → boundary.rbs} +2 -2
  223. data/sig/kobako/codec/handle_walk.rbs +0 -6
  224. data/sig/kobako/codec/value_budget.rbs +47 -4
  225. data/sig/kobako/context.rbs +3 -1
  226. data/sig/kobako/errors.rbs +4 -4
  227. data/sig/kobako/filesystem.rbs +21 -3
  228. data/sig/kobako/network.rbs +115 -0
  229. data/sig/kobako/outcome.rbs +1 -1
  230. data/sig/kobako/pool.rbs +7 -3
  231. data/sig/kobako/runtime.rbs +32 -3
  232. data/sig/kobako/sandbox.rbs +19 -2
  233. data/sig/kobako/sandbox_options.rbs +29 -38
  234. data/sig/kobako/transport/argument_wrap.rbs +15 -0
  235. data/sig/kobako/transport/error.rbs +1 -1
  236. data/sig/kobako/transport/exposure.rbs +2 -4
  237. data/sig/kobako/transport/reflection.rbs +10 -0
  238. data/sig/kobako/transport/run.rbs +0 -2
  239. data/sig/kobako/transport/yielder.rbs +0 -3
  240. data/sig/kobako/transport.rbs +1 -1
  241. data/sig/kobako.rbs +13 -0
  242. metadata +84 -35
  243. data/crates/kobako-runtime/src/endpoint/capture.rs +0 -115
  244. data/crates/kobako-runtime/src/endpoint/memory_cap.rs +0 -238
  245. data/crates/kobako-runtime/src/filesystem/path.rs +0 -21
  246. data/crates/kobako-runtime/src/vfs/errno.rs +0 -153
  247. data/crates/kobako-runtime/tests/linux_baseline/calls.rs +0 -171
  248. data/crates/kobako-runtime/tests/linux_baseline/concurrent.rs +0 -276
  249. data/crates/kobako-runtime/tests/linux_baseline/kobako.rs +0 -323
  250. data/crates/kobako-runtime/tests/linux_baseline/linux-baseline-expected.txt +0 -16
  251. data/crates/kobako-runtime/tests/linux_baseline/linux.rs +0 -449
  252. data/crates/kobako-runtime/tests/linux_baseline/main.rs +0 -611
  253. data/crates/kobako-runtime/tests/linux_baseline/permissions.rs +0 -236
  254. data/crates/kobako-wasmtime/src/descriptors.rs +0 -200
  255. data/crates/kobako-wasmtime/tests/integration/compile_posture.rs +0 -43
  256. data/crates/kobako-wasmtime/tests/integration/guest_file.rs +0 -1085
  257. data/crates/kobako-wasmtime/tests/integration/main.rs +0 -29
  258. data/crates/kobako-wasmtime/tests/integration/preamble_flags.rs +0 -70
  259. data/crates/kobako-wasmtime/tests/integration/snippet_compile.rs +0 -95
  260. data/crates/kobako-wasmtime/tests/integration/support/mod.rs +0 -30
  261. data/crates/kobako-wasmtime/tests/integration/unanswered_call.rs +0 -86
  262. data/crates/kobako-wasmtime/tests/integration/unsupported_call.rs +0 -51
  263. data/ext/kobako/src/runtime/gvl.rs +0 -147
  264. data/lib/kobako/constant_name.rb +0 -8
  265. data/sig/kobako/constant_name.rbs +0 -3
  266. /data/ext/kobako/src/{runtime/pinned_value.rs → pinned_value.rs} +0 -0
@@ -0,0 +1,1366 @@
1
+ //! The network namespace one Invocation's entries make, as Linux's `struct
2
+ //! net` holds the rules every socket of a namespace passes, the ports its
3
+ //! sockets hold, and the family that dials it. It also holds the virtual
4
+ //! addresses a lookup hands out, one for each real address the name resolved
5
+ //! to, which the socket layer's `connect4` reads, so no name is ever resolved
6
+ //! twice.
7
+
8
+ use std::net::{IpAddr, Ipv4Addr, SocketAddr};
9
+ use std::sync::{Arc, Mutex, PoisonError, Weak};
10
+
11
+ use super::egress::EgressProxy;
12
+ use super::http::{HyperOutbound, Outbound};
13
+ use super::lookup::{LookupError, NameLookup, Resolver};
14
+ use super::socket::{BindHash, LOCAL_ADDRESS, VIRTUAL_BASE, VIRTUAL_SIZE};
15
+ use super::{Backends, OpenConnections, ProtocolFamily, TcpSock};
16
+ use crate::cred::Cred;
17
+ use crate::memcg::MemoryCharge;
18
+ use crate::network::{EntryError, Name, Network, Protocol, Ruleset};
19
+ use crate::policy::Policy;
20
+
21
+ /// How many virtual addresses lookups may take: those below the guest's own,
22
+ /// `LOCAL_ADDRESS`, which leaves out it and the broadcast one above it.
23
+ const MAX_NAMED_ADDRESSES: u32 = LOCAL_ADDRESS.to_bits() - VIRTUAL_BASE;
24
+
25
+ /// What the guest may reach, which policies judge each lookup, the backends
26
+ /// that dial and resolve, the connections this Invocation holds open and
27
+ /// those left to it, the ports its sockets hold, and the virtual
28
+ /// addresses handed out.
29
+ pub struct Namespace {
30
+ ruleset: Arc<Ruleset>,
31
+ resolve: Vec<Arc<dyn for<'a> Policy<Name<'a>>>>,
32
+ /// The HTTP layer's request policies and bound credentials.
33
+ egress: EgressProxy,
34
+ family: Arc<dyn ProtocolFamily>,
35
+ resolver: Arc<dyn Resolver>,
36
+ outbound: Arc<dyn Outbound>,
37
+ open_connections: Arc<OpenConnections>,
38
+ /// How many more connections this Invocation may make, worked out from
39
+ /// its connection limit; `None` makes no count.
40
+ connection_budget: Mutex<Option<usize>>,
41
+ translations: Mutex<Translations>,
42
+ /// The virtual ports TCP sockets hold, and those UDP sockets hold, as
43
+ /// TCP keeps its `bhash` and UDP its `udp_table`.
44
+ tcp_ports: Arc<BindHash>,
45
+ udp_ports: Arc<BindHash>,
46
+ /// Every TCP socket made here, so an orphan still sending ends with the
47
+ /// Invocation.
48
+ tcp_sockets: Arc<TcpSockets>,
49
+ }
50
+
51
+ /// Each real address a name looked up resolved to, with the name, at its
52
+ /// virtual address's offset from the bottom of the range, and the memory
53
+ /// they hold against the Invocation's, given back as the namespace goes.
54
+ #[derive(Default)]
55
+ struct Translations {
56
+ entries: Vec<(String, IpAddr)>,
57
+ memory: Option<MemoryCharge>,
58
+ }
59
+
60
+ impl Translations {
61
+ /// The offsets of `name`'s entries and the real addresses they hold, in
62
+ /// the order its lookup answered them.
63
+ fn entries_by_name<'a>(&'a self, name: &'a str) -> impl Iterator<Item = (u32, IpAddr)> + 'a {
64
+ (0u32..)
65
+ .zip(&self.entries)
66
+ .filter(move |(_, (known, _))| known == name)
67
+ .map(|(offset, (_, real))| (offset, *real))
68
+ }
69
+ }
70
+
71
+ /// Every TCP socket an Invocation made, the guest's and the L7 proxy's
72
+ /// upstream ones alike, so each one still open ends with the Invocation.
73
+ #[derive(Default)]
74
+ pub(crate) struct TcpSockets(Mutex<Vec<Weak<TcpSock>>>);
75
+
76
+ impl TcpSockets {
77
+ /// Hold `sock`, so it ends with the Invocation should it still be open,
78
+ /// as a namespace's exit ends its sockets.
79
+ pub(crate) fn hold(&self, sock: &Arc<TcpSock>) {
80
+ let mut sockets = self.0.lock().unwrap_or_else(PoisonError::into_inner);
81
+ sockets.retain(|sock| sock.strong_count() > 0);
82
+ sockets.push(Arc::downgrade(sock));
83
+ }
84
+
85
+ /// Every socket still held, so a test reaches one a proxy dialed.
86
+ #[cfg(test)]
87
+ pub(crate) fn held(&self) -> Vec<Arc<TcpSock>> {
88
+ let sockets = self.0.lock().unwrap_or_else(PoisonError::into_inner);
89
+ sockets.iter().filter_map(Weak::upgrade).collect()
90
+ }
91
+ }
92
+
93
+ /// The Invocation's end aborts every socket still open, so nothing it made
94
+ /// outlives it and nothing waits on one for good.
95
+ impl Drop for Namespace {
96
+ fn drop(&mut self) {
97
+ let sockets = std::mem::take(
98
+ &mut *self
99
+ .tcp_sockets
100
+ .0
101
+ .lock()
102
+ .unwrap_or_else(PoisonError::into_inner),
103
+ );
104
+ for sock in sockets.iter().filter_map(Weak::upgrade) {
105
+ sock.abort();
106
+ }
107
+ }
108
+ }
109
+
110
+ impl Namespace {
111
+ /// The namespace every entry of `networks` makes together, dialing and
112
+ /// looking names up through `backends` and sending HTTP through kobako's
113
+ /// own L7 proxy, refused for an endpoint the ruleset cannot compile. Each
114
+ /// socket, request, and lookup counts against `open_connections` while
115
+ /// open, and the Invocation makes at most `connection_limit` connections
116
+ /// in all.
117
+ pub fn new<'a>(
118
+ networks: impl IntoIterator<Item = &'a Network>,
119
+ backends: &Backends,
120
+ open_connections: Arc<OpenConnections>,
121
+ connection_limit: Option<usize>,
122
+ ) -> Result<Self, EntryError> {
123
+ let networks = networks.into_iter().collect::<Vec<_>>();
124
+ // Each entry's endpoints are read once, so its credentials bind to the
125
+ // very endpoints that judge reach.
126
+ let endpoints = networks
127
+ .iter()
128
+ .map(|network| network.endpoints())
129
+ .collect::<Vec<_>>();
130
+ let ruleset = Ruleset::new(endpoints.iter().flatten().cloned())?;
131
+ let bindings = networks
132
+ .iter()
133
+ .zip(&endpoints)
134
+ .map(|(network, endpoints)| (endpoints, network.credentials()))
135
+ .filter(|(_, credentials)| !credentials.is_empty())
136
+ .map(|(endpoints, credentials)| Ok((Ruleset::new(endpoints.clone())?, credentials)))
137
+ .collect::<Result<Vec<_>, EntryError>>()?;
138
+ let policies = networks
139
+ .iter()
140
+ .map(|network| network.policies())
141
+ .collect::<Vec<_>>();
142
+ Ok(Self {
143
+ ruleset: Arc::new(ruleset),
144
+ resolve: policies.iter().filter_map(|p| p.resolve.clone()).collect(),
145
+ egress: EgressProxy {
146
+ request: policies.iter().filter_map(|p| p.request.clone()).collect(),
147
+ bindings,
148
+ },
149
+ family: backends.family().clone(),
150
+ resolver: backends.resolver().clone(),
151
+ outbound: Arc::new(HyperOutbound::new()),
152
+ open_connections,
153
+ connection_budget: Mutex::new(connection_limit),
154
+ translations: Mutex::default(),
155
+ tcp_ports: BindHash::new(),
156
+ udp_ports: BindHash::new(),
157
+ tcp_sockets: Arc::default(),
158
+ })
159
+ }
160
+
161
+ /// The entries' request policies and bound credentials, which the L7
162
+ /// proxy judges each request by.
163
+ pub(crate) fn egress(&self) -> &EgressProxy {
164
+ &self.egress
165
+ }
166
+
167
+ /// The seam every HTTP request this namespace admits is sent through.
168
+ pub(crate) fn outbound(&self) -> &Arc<dyn Outbound> {
169
+ &self.outbound
170
+ }
171
+
172
+ /// The entries' `resolve` policies, which judge each lookup.
173
+ pub(crate) fn resolve_policies(&self) -> &[Arc<dyn for<'a> Policy<Name<'a>>>] {
174
+ &self.resolve
175
+ }
176
+
177
+ /// The Resolver this namespace's lookups ask.
178
+ pub(crate) fn resolver(&self) -> &Arc<dyn Resolver> {
179
+ &self.resolver
180
+ }
181
+
182
+ /// The real addresses `name` was translated to, in the order its lookup
183
+ /// answered; none for a name never looked up here.
184
+ pub(crate) fn real_addresses_of(&self, name: &str) -> Vec<IpAddr> {
185
+ self.translations
186
+ .lock()
187
+ .unwrap_or_else(PoisonError::into_inner)
188
+ .entries_by_name(name)
189
+ .map(|(_, real)| real)
190
+ .collect()
191
+ }
192
+
193
+ /// `connect`, made only while the Invocation has a connection left and
194
+ /// counted once it is, as a budget of subrequests is spent;
195
+ /// `refused`, dialing nothing, once none is left.
196
+ pub(crate) fn within_connection_budget<T, E>(
197
+ &self,
198
+ refused: E,
199
+ connect: impl FnOnce() -> Result<T, E>,
200
+ ) -> Result<T, E> {
201
+ let mut left = self
202
+ .connection_budget
203
+ .lock()
204
+ .unwrap_or_else(PoisonError::into_inner);
205
+ if *left == Some(0) {
206
+ return Err(refused);
207
+ }
208
+ let made = connect()?;
209
+ if let Some(n) = left.as_mut() {
210
+ *n -= 1;
211
+ }
212
+ Ok(made)
213
+ }
214
+
215
+ /// The virtual ports `protocol`'s sockets hold here.
216
+ pub(crate) fn ports_of(&self, protocol: Protocol) -> &Arc<BindHash> {
217
+ match protocol {
218
+ Protocol::Udp => &self.udp_ports,
219
+ Protocol::Tcp | Protocol::Http => &self.tcp_ports,
220
+ }
221
+ }
222
+
223
+ /// Allocate the virtual addresses `lookup`'s answer is handed out at, one
224
+ /// for each real address in the order it answered, from the bottom of the
225
+ /// range and never reused; a name already handed them keeps them, as a
226
+ /// fake-IP pool answers a known host; a lookup of an address keeps it as
227
+ /// itself. `None` while the lookup is under way, its failure once it
228
+ /// failed, and `Again` once the range cannot hold them all or
229
+ /// `cred`'s memory cannot hold the entries, which the table keeps until
230
+ /// the Invocation ends.
231
+ pub fn alloc_virtual_addresses(
232
+ &self,
233
+ cred: &Arc<Cred>,
234
+ lookup: &NameLookup,
235
+ ) -> Option<Result<Vec<IpAddr>, LookupError>> {
236
+ let real = match lookup.answer()? {
237
+ Ok(real) if lookup.is_of_address() => return Some(Ok(real)),
238
+ Ok(real) => real,
239
+ Err(err) => return Some(Err(err)),
240
+ };
241
+ let to_virtual = |offset: u32| IpAddr::V4(Ipv4Addr::from(VIRTUAL_BASE + offset));
242
+ let mut translations = self
243
+ .translations
244
+ .lock()
245
+ .unwrap_or_else(PoisonError::into_inner);
246
+ let known = translations
247
+ .entries_by_name(lookup.name())
248
+ .map(|(offset, _)| to_virtual(offset))
249
+ .collect::<Vec<_>>();
250
+ if !known.is_empty() {
251
+ return Some(Ok(known));
252
+ }
253
+ let first = translations.entries.len();
254
+ let Some(end) = u32::try_from(first + real.len())
255
+ .ok()
256
+ .filter(|end| *end <= MAX_NAMED_ADDRESSES)
257
+ else {
258
+ return Some(Err(LookupError::Again));
259
+ };
260
+ let entries = real
261
+ .into_iter()
262
+ .map(|ip| (lookup.name().to_string(), ip))
263
+ .collect::<Vec<_>>();
264
+ let held = entries
265
+ .iter()
266
+ .map(|entry| std::mem::size_of_val(entry) + entry.0.len())
267
+ .sum::<usize>();
268
+ let charged = match &mut translations.memory {
269
+ Some(memory) => memory.resize(memory.bytes() + held),
270
+ None => MemoryCharge::new(cred.memory_budget(), held).map(|memory| {
271
+ translations.memory = Some(memory);
272
+ }),
273
+ };
274
+ if charged.is_err() {
275
+ return Some(Err(LookupError::Again));
276
+ }
277
+ translations.entries.extend(entries);
278
+ let first = u32::try_from(first).expect("below the end of the range");
279
+ Some(Ok((first..end).map(to_virtual).collect()))
280
+ }
281
+
282
+ /// The name a virtual address stands for and the real address it stands
283
+ /// for.
284
+ fn translate(&self, ip: Ipv4Addr) -> Option<(String, IpAddr)> {
285
+ let offset = u32::from(ip).checked_sub(VIRTUAL_BASE)?;
286
+ self.translations
287
+ .lock()
288
+ .unwrap_or_else(PoisonError::into_inner)
289
+ .entries
290
+ .get(usize::try_from(offset).ok()?)
291
+ .cloned()
292
+ }
293
+
294
+ /// The Protocol Family this namespace's sockets reach the host through.
295
+ pub(crate) fn family(&self) -> &Arc<dyn ProtocolFamily> {
296
+ &self.family
297
+ }
298
+
299
+ /// The open connections this namespace's sockets count against.
300
+ pub(crate) fn open_connections(&self) -> &Arc<OpenConnections> {
301
+ &self.open_connections
302
+ }
303
+
304
+ /// The rules every connection made here passes.
305
+ pub(crate) fn ruleset(&self) -> &Arc<Ruleset> {
306
+ &self.ruleset
307
+ }
308
+
309
+ /// The TCP sockets made here, which end with the Invocation.
310
+ pub(crate) fn tcp_sockets(&self) -> &Arc<TcpSockets> {
311
+ &self.tcp_sockets
312
+ }
313
+
314
+ /// What `addr` stands for when it lies in the virtual range: its name and
315
+ /// real address, or `None` inside the range when no name holds it.
316
+ pub(crate) fn translation_of(&self, addr: SocketAddr) -> Option<Option<(String, IpAddr)>> {
317
+ match addr.ip() {
318
+ IpAddr::V4(ip) if u32::from(ip) & !(VIRTUAL_SIZE - 1) == VIRTUAL_BASE => {
319
+ Some(self.translate(ip))
320
+ }
321
+ _ => None,
322
+ }
323
+ }
324
+ }
325
+
326
+ #[cfg(test)]
327
+ impl Namespace {
328
+ /// The namespace `network` alone makes, dialing through `family`, which
329
+ /// also looks names up, and sending through `outbound`, with no
330
+ /// connection limit; its endpoints must compile.
331
+ pub(crate) fn for_network<F: ProtocolFamily + Resolver + 'static>(
332
+ network: &Network,
333
+ family: Arc<F>,
334
+ outbound: Arc<dyn Outbound>,
335
+ ) -> Self {
336
+ Self::new(
337
+ [network],
338
+ &Backends::new(family.clone(), family),
339
+ OpenConnections::new(None),
340
+ None,
341
+ )
342
+ .expect("the endpoints compile")
343
+ .with_outbound(outbound)
344
+ }
345
+
346
+ /// This namespace sending HTTP through `outbound` in place of kobako's
347
+ /// own sender, so a test sees what the L7 proxy hands it.
348
+ pub(crate) fn with_outbound(mut self, outbound: Arc<dyn Outbound>) -> Self {
349
+ self.outbound = outbound;
350
+ self
351
+ }
352
+ }
353
+
354
+ #[cfg(test)]
355
+ mod tests {
356
+ use std::io;
357
+ use std::sync::atomic::{AtomicUsize, Ordering};
358
+ use std::sync::Mutex;
359
+ use std::time::Duration;
360
+
361
+ use super::super::family::testing::CountsDials;
362
+ use super::super::http::{HttpError, OutgoingRequest, Scheme};
363
+ use super::super::lookup::resolve;
364
+ use super::super::socket::{sys_bind, sys_connect, AddressFamily};
365
+ use super::super::UdpSock;
366
+ use super::*;
367
+ use crate::grant::Grant;
368
+ use crate::network::Connection;
369
+ use crate::network::{Addresses, Endpoint, Entry, Policies};
370
+ use crate::security::{prepare_creds, restrict_self, SecurityOperations};
371
+ use crate::Errno;
372
+
373
+ /// Each connection a policy was asked about.
374
+ type AskedConnections = Arc<Mutex<Vec<(String, u16, Protocol)>>>;
375
+
376
+ /// An entry reaching `127.0.0.1:4567` over TCP and `127.0.0.1:4568` over
377
+ /// UDP, its connect policy recording what it saw and answering `allows`.
378
+ struct RecordsConnects {
379
+ allows: bool,
380
+ seen: AskedConnections,
381
+ }
382
+
383
+ impl Entry for RecordsConnects {
384
+ fn endpoints(&self) -> Vec<Endpoint> {
385
+ vec![
386
+ Endpoint::new("127.0.0.1", 4567)
387
+ .unwrap()
388
+ .with_protocol(Protocol::Tcp),
389
+ Endpoint::new("127.0.0.1", 4568)
390
+ .unwrap()
391
+ .with_protocol(Protocol::Udp),
392
+ ]
393
+ }
394
+
395
+ fn policies(&self) -> Policies {
396
+ let (allows, seen) = (self.allows, self.seen.clone());
397
+ Policies::default().with_connect_policy(Arc::new(move |connection: &Connection<'_>| {
398
+ seen.lock().unwrap().push((
399
+ connection.host.to_string(),
400
+ connection.port,
401
+ connection.protocol,
402
+ ));
403
+ allows
404
+ }))
405
+ }
406
+ }
407
+
408
+ /// A namespace of one entry per `allows`, and the Cred its entries'
409
+ /// connect policies restrict.
410
+ fn namespace(allows: &[bool]) -> (Namespace, Arc<Cred>, Arc<CountsDials>, AskedConnections) {
411
+ limited_namespace(allows, None, None, &[])
412
+ }
413
+
414
+ /// A namespace of one entry per `allows`, whose Invocation holds at most
415
+ /// `open` connections at once and makes at most
416
+ /// `total`, and the Cred the Driver makes for it: `modules`, then the
417
+ /// entries' connect policies.
418
+ fn limited_namespace(
419
+ allows: &[bool],
420
+ open: Option<usize>,
421
+ total: Option<usize>,
422
+ modules: &[Arc<dyn SecurityOperations>],
423
+ ) -> (Namespace, Arc<Cred>, Arc<CountsDials>, AskedConnections) {
424
+ let seen = Arc::new(Mutex::new(Vec::new()));
425
+ let networks = allows
426
+ .iter()
427
+ .enumerate()
428
+ .map(|(index, allows)| {
429
+ let entry = RecordsConnects {
430
+ allows: *allows,
431
+ seen: seen.clone(),
432
+ };
433
+ Network::new(format!("entry{index}"), Arc::new(entry)).unwrap()
434
+ })
435
+ .collect::<Vec<_>>();
436
+ let family = Arc::new(CountsDials::default());
437
+ let namespace = Namespace::new(
438
+ &networks,
439
+ &Backends::new(family.clone(), family.clone()),
440
+ OpenConnections::new(open),
441
+ total,
442
+ )
443
+ .expect("the endpoints compile");
444
+ let grants = networks.into_iter().map(Grant::Network).collect::<Vec<_>>();
445
+ let cred =
446
+ restrict_self(&prepare_creds(modules, None), &grants).expect("every Mount stands");
447
+ (namespace, cred, family, seen)
448
+ }
449
+
450
+ /// An http entry for `::1` and `127.0.0.1` with a credential, counting how
451
+ /// often its endpoints are read and its resolve policy is asked; its
452
+ /// connect policy refuses `refused.example`.
453
+ struct CountsReads {
454
+ reads: AtomicUsize,
455
+ resolved: Arc<AtomicUsize>,
456
+ /// Each host the connect policy was asked about.
457
+ judged: Arc<Mutex<Vec<String>>>,
458
+ }
459
+
460
+ impl Entry for CountsReads {
461
+ fn endpoints(&self) -> Vec<Endpoint> {
462
+ self.reads.fetch_add(1, Ordering::SeqCst);
463
+ vec![
464
+ Endpoint::new("::1", 4567).unwrap(),
465
+ Endpoint::new("127.0.0.1", 4567).unwrap(),
466
+ ]
467
+ }
468
+
469
+ fn policies(&self) -> Policies {
470
+ let resolved = self.resolved.clone();
471
+ let judged = self.judged.clone();
472
+ Policies::default()
473
+ .with_connect_policy(Arc::new(move |connection: &Connection<'_>| {
474
+ judged.lock().unwrap().push(connection.host.to_string());
475
+ connection.host != "refused.example"
476
+ }))
477
+ .with_resolve_policy(Arc::new(move |_: &Name<'_>| {
478
+ resolved.fetch_add(1, Ordering::SeqCst);
479
+ true
480
+ }))
481
+ }
482
+
483
+ fn credentials(&self) -> Vec<crate::network::Credential> {
484
+ vec![crate::network::Credential::new(
485
+ crate::network::Placement::Bearer,
486
+ "kobako-token",
487
+ Arc::new(|_: &crate::network::Request<'_>| Ok(None)),
488
+ )]
489
+ }
490
+ }
491
+
492
+ // @behavior NW-077
493
+ #[test]
494
+ fn a_request_is_judged_once_in_order_and_never_over_ipv6() {
495
+ let entry = Arc::new(CountsReads {
496
+ reads: AtomicUsize::new(0),
497
+ resolved: Arc::default(),
498
+ judged: Arc::default(),
499
+ });
500
+ let network = Network::new("watched", entry.clone()).unwrap();
501
+ let namespace = Namespace::for_network(
502
+ &network,
503
+ Arc::new(CountsDials::default()),
504
+ Arc::new(crate::net::HyperOutbound::new()),
505
+ );
506
+ let cred = restrict_self(&prepare_creds(&[], None), [&Grant::Network(network)])
507
+ .expect("every Mount stands");
508
+ let get = |authority: &str| OutgoingRequest::new("GET", Scheme::Http, authority);
509
+ let hooked = crate::net::send(&namespace, &cred, get("refused.example:4567")).err();
510
+ let ipv6 = crate::net::send(&namespace, &cred, get("[::1]:4567")).err();
511
+ assert_eq!(
512
+ (
513
+ entry.reads.load(Ordering::SeqCst),
514
+ hooked,
515
+ entry.resolved.load(Ordering::SeqCst),
516
+ ipv6,
517
+ entry.judged.lock().unwrap().clone()
518
+ ),
519
+ (
520
+ 1,
521
+ Some(HttpError::Denied),
522
+ 0,
523
+ Some(HttpError::Denied),
524
+ vec!["refused.example".to_string(), "::1".to_string()]
525
+ ),
526
+ "a network must read an entry's endpoints once, a guest's request must ask no \
527
+ resolve policy once a connect hook refused, and must let the connect hook judge an \
528
+ IPv6 authority an endpoint names before refusing it, as a socket's connect does"
529
+ );
530
+ }
531
+
532
+ // @behavior NW-022
533
+ #[test]
534
+ fn a_connect_past_the_sandboxs_cap_answers_eagain() {
535
+ let (namespace, cred, family, _) = limited_namespace(&[true], Some(0), None, &[]);
536
+ let answer = dial(&namespace, &cred, "127.0.0.1:4567".parse().unwrap());
537
+ assert!(
538
+ matches!(answer, Err(Errno::WouldBlock)) && family.dials() == 0,
539
+ "a socket's connect past the Sandbox's cap must answer EAGAIN, dialing nothing"
540
+ );
541
+ }
542
+
543
+ // @behavior NW-059
544
+ #[test]
545
+ fn an_invocation_past_its_connection_limit_answers_eagain() {
546
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
547
+ let mut entry = crate::network::Builder::default();
548
+ entry.endpoint(
549
+ Endpoint::new("127.0.0.1", listener.local_addr().unwrap().port())
550
+ .unwrap()
551
+ .with_protocol(Protocol::Tcp),
552
+ );
553
+ let network = Network::new("db", Arc::new(entry)).unwrap();
554
+ let namespace = Namespace::new(
555
+ [&network],
556
+ &Backends::default(),
557
+ OpenConnections::new(None),
558
+ Some(2),
559
+ )
560
+ .unwrap();
561
+ let cred = prepare_creds(&[], None);
562
+ let addr = listener.local_addr().unwrap();
563
+ let made = [dial(&namespace, &cred, addr), dial(&namespace, &cred, addr)];
564
+ drop(made);
565
+ let third = dial(&namespace, &cred, addr);
566
+ assert!(
567
+ matches!(third, Err(Errno::WouldBlock)),
568
+ "a socket's connect past the Invocation's connection limit must answer EAGAIN even \
569
+ once the earlier connections closed"
570
+ );
571
+ }
572
+
573
+ // @behavior NW-059
574
+ #[test]
575
+ fn an_invocations_request_spends_its_connection_limit_too() {
576
+ let mut entry = crate::network::Builder::default();
577
+ entry.endpoint(Endpoint::new("127.0.0.1", 4567).unwrap());
578
+ entry.endpoint(
579
+ Endpoint::new("127.0.0.1", 4568)
580
+ .unwrap()
581
+ .with_protocol(Protocol::Tcp),
582
+ );
583
+ let network = Network::new("web", Arc::new(entry)).unwrap();
584
+ let family = Arc::new(CountsDials::default());
585
+ let namespace = Namespace::new(
586
+ [&network],
587
+ &Backends::new(family.clone(), family.clone()),
588
+ OpenConnections::new(None),
589
+ Some(1),
590
+ )
591
+ .unwrap();
592
+ let cred = prepare_creds(&[], None);
593
+ let mut request = OutgoingRequest::new("GET", Scheme::Http, "127.0.0.1:4567");
594
+ request.path_with_query = "/".to_string();
595
+ let exchange =
596
+ crate::net::send(&namespace, &cred, request).expect("the endpoint admits it");
597
+ while exchange.response().is_none() {
598
+ std::thread::sleep(Duration::from_millis(1));
599
+ }
600
+ let dialed = family.dials();
601
+ let socket = dial(&namespace, &cred, "127.0.0.1:4568".parse().unwrap());
602
+ assert_eq!(
603
+ (dialed, socket.err(), family.dials()),
604
+ (1, Some(Errno::WouldBlock), 1),
605
+ "a socket's connect after an HTTP request spent the Invocation's connection limit of \
606
+ 1 must answer EAGAIN and dial nothing"
607
+ );
608
+ }
609
+
610
+ /// Whether a task waiting here was woken.
611
+ #[derive(Default)]
612
+ struct Woken(std::sync::atomic::AtomicBool);
613
+
614
+ impl std::task::Wake for Woken {
615
+ fn wake(self: Arc<Self>) {
616
+ self.0.store(true, Ordering::SeqCst);
617
+ }
618
+ }
619
+
620
+ // @behavior NW-233
621
+ #[test]
622
+ fn the_invocations_end_aborts_a_socket_something_waits_on() {
623
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
624
+ let mut entry = crate::network::Builder::default();
625
+ entry
626
+ .endpoint(
627
+ Endpoint::new("127.0.0.1", listener.local_addr().unwrap().port())
628
+ .unwrap()
629
+ .with_protocol(Protocol::Tcp),
630
+ )
631
+ .endpoint(Endpoint::new("127.0.0.1", listener.local_addr().unwrap().port()).unwrap());
632
+ let network = Network::new("db", Arc::new(entry)).unwrap();
633
+ let namespace = Namespace::new(
634
+ [&network],
635
+ &Backends::default(),
636
+ OpenConnections::new(None),
637
+ None,
638
+ )
639
+ .unwrap();
640
+ let cred = prepare_creds(&[], None);
641
+ let sock = dial(&namespace, &cred, listener.local_addr().unwrap()).unwrap();
642
+ let (_peer, _) = listener.accept().unwrap();
643
+ settle(&sock);
644
+ let woken = Arc::new(Woken::default());
645
+ sock.sk_sleep().add(&std::task::Waker::from(woken.clone()));
646
+ let mut file = crate::net::sock_alloc_file(sock, &cred);
647
+ let request = crate::net::send(
648
+ &namespace,
649
+ &cred,
650
+ OutgoingRequest::new(
651
+ "GET",
652
+ Scheme::Http,
653
+ listener.local_addr().unwrap().to_string(),
654
+ ),
655
+ )
656
+ .expect("an endpoint names the authority");
657
+ let (_upstream, _) = listener.accept().unwrap();
658
+ drop(namespace);
659
+ let deadline = std::time::Instant::now() + Duration::from_secs(10);
660
+ let answer = loop {
661
+ match request.response() {
662
+ Some(answer) => break answer.err(),
663
+ None if std::time::Instant::now() < deadline => {
664
+ std::thread::sleep(Duration::from_millis(1))
665
+ }
666
+ None => break None,
667
+ }
668
+ };
669
+ assert_eq!(
670
+ (
671
+ woken.0.load(Ordering::SeqCst),
672
+ file.read(&mut [0; 8]).err(),
673
+ answer
674
+ ),
675
+ (
676
+ true,
677
+ Some(Errno::ConnectionAborted),
678
+ Some(HttpError::ConnectionTerminated)
679
+ ),
680
+ "the Invocation's end must wake a task waiting on a connected TCP socket, whose read \
681
+ then answers ECONNABORTED, and fail an HTTP request awaiting its response head with \
682
+ connection-terminated"
683
+ );
684
+ }
685
+
686
+ // @behavior NW-164
687
+ #[test]
688
+ fn the_invocations_end_lets_go_of_a_socket_still_sending() {
689
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
690
+ let mut entry = crate::network::Builder::default();
691
+ entry.endpoint(
692
+ Endpoint::new("127.0.0.1", listener.local_addr().unwrap().port())
693
+ .unwrap()
694
+ .with_protocol(Protocol::Tcp),
695
+ );
696
+ let network = Network::new("db", Arc::new(entry)).unwrap();
697
+ let namespace = Namespace::new(
698
+ [&network],
699
+ &Backends::default(),
700
+ OpenConnections::new(None),
701
+ None,
702
+ )
703
+ .unwrap();
704
+ let cred = prepare_creds(&[], None);
705
+ let mut peers = Vec::new();
706
+ // The host may still take what was queued before the release, under
707
+ // load; each try releases a socket filled again until one holds bytes.
708
+ let held = (0..5)
709
+ .map(|_| {
710
+ let sock = dial(&namespace, &cred, listener.local_addr().unwrap()).unwrap();
711
+ peers.push(listener.accept().unwrap().0);
712
+ settle(&sock);
713
+ let mut file = crate::net::sock_alloc_file(sock.clone(), &cred);
714
+ while file.write(&[7; 16 * 1024]).is_ok() {}
715
+ let held = Arc::downgrade(&sock);
716
+ drop((sock, file));
717
+ held
718
+ })
719
+ .find(|held| held.upgrade().is_some());
720
+ let orphaned = held.is_some();
721
+ drop(namespace);
722
+ let held = held.unwrap_or_default();
723
+ // The reactor may hold the socket a moment longer for an event
724
+ // already under way.
725
+ let deadline = std::time::Instant::now() + Duration::from_secs(2);
726
+ while held.strong_count() > 0 && std::time::Instant::now() < deadline {
727
+ std::thread::sleep(Duration::from_millis(1));
728
+ }
729
+ assert_eq!(
730
+ (orphaned, held.strong_count() > 0),
731
+ (true, false),
732
+ "a socket released with bytes still queued to send must hold itself while it sends, \
733
+ and the Invocation's namespace dropping must let it go"
734
+ );
735
+ }
736
+
737
+ /// A new TCP socket `namespace` connects to `addr` as `cred`.
738
+ fn dial(
739
+ namespace: &Namespace,
740
+ cred: &Arc<Cred>,
741
+ addr: SocketAddr,
742
+ ) -> Result<Arc<TcpSock>, Errno> {
743
+ let sock = TcpSock::create(namespace, cred, AddressFamily::Inet)?;
744
+ sys_connect(namespace, cred, sock.as_ref(), Some(addr)).map(|()| sock)
745
+ }
746
+
747
+ /// A new UDP socket `namespace` connects to `addr` as `cred`.
748
+ fn dial_datagram(
749
+ namespace: &Namespace,
750
+ cred: &Arc<Cred>,
751
+ addr: Option<SocketAddr>,
752
+ ) -> Result<Arc<UdpSock>, Errno> {
753
+ let sock = UdpSock::create(namespace, cred, AddressFamily::Inet)?;
754
+ sys_connect(namespace, cred, sock.as_ref(), addr).map(|()| sock)
755
+ }
756
+
757
+ fn settle(sock: &TcpSock) {
758
+ while matches!(sock.take_connect_outcome(), Err(Errno::WouldBlock)) {
759
+ std::thread::sleep(Duration::from_millis(1));
760
+ }
761
+ }
762
+
763
+ // @behavior NW-018
764
+ #[test]
765
+ fn a_connect_policy_refuses_what_the_endpoints_allow() {
766
+ let (namespace, cred, family, seen) = namespace(&[true, false]);
767
+ let answer = dial(&namespace, &cred, "127.0.0.1:4567".parse().unwrap());
768
+ let datagram = dial_datagram(&namespace, &cred, Some("127.0.0.1:4568".parse().unwrap()));
769
+ assert!(
770
+ matches!(answer, Err(Errno::PermissionDenied))
771
+ && matches!(datagram, Err(Errno::PermissionDenied))
772
+ && family.dials() == 0,
773
+ "a TCP or UDP socket's connect to an address an endpoint admits must refuse with \
774
+ EACCES, dialing nothing, once any entry's connect policy refuses"
775
+ );
776
+ let seen = seen.lock().unwrap();
777
+ assert_eq!(
778
+ (seen[0].clone(), seen.last().cloned()),
779
+ (
780
+ ("127.0.0.1".to_string(), 4567, Protocol::Tcp),
781
+ Some(("127.0.0.1".to_string(), 4568, Protocol::Udp))
782
+ ),
783
+ "a connect policy must see the host the guest named, its port, and its protocol, \
784
+ TCP or UDP"
785
+ );
786
+ }
787
+
788
+ // @behavior NW-018
789
+ #[test]
790
+ fn a_connect_every_policy_allows_dials_the_address() {
791
+ let (namespace, cred, family, _) = namespace(&[true, true]);
792
+ let sock = dial(&namespace, &cred, "127.0.0.1:4567".parse().unwrap())
793
+ .expect("every policy allows");
794
+ settle(&sock);
795
+ assert_eq!(
796
+ family.dials(),
797
+ 1,
798
+ "a socket's connect every connect policy allows must dial the address once"
799
+ );
800
+ }
801
+
802
+ // @behavior NW-151
803
+ #[test]
804
+ fn the_hooks_judge_what_the_guest_named_before_its_family_and_translation() {
805
+ let (namespace, cred, family, seen) = namespace(&[true]);
806
+ let ipv6 = dial(&namespace, &cred, "[::1]:4567".parse().unwrap()).err();
807
+ let unmapped = dial(&namespace, &cred, "198.18.5.5:4567".parse().unwrap()).err();
808
+ let sock = UdpSock::new(&cred).expect("an unbounded socket is made");
809
+ let bound = sys_bind(&namespace, &cred, sock.as_ref(), "[::]:0".parse().unwrap()).err();
810
+ let judged = seen
811
+ .lock()
812
+ .unwrap()
813
+ .iter()
814
+ .map(|(host, _, _)| host.clone())
815
+ .collect::<Vec<_>>();
816
+ assert_eq!(
817
+ (ipv6, unmapped, bound, judged, family.dials()),
818
+ (
819
+ Some(Errno::AddressFamilyNotSupported),
820
+ Some(Errno::PermissionDenied),
821
+ Some(Errno::AddressFamilyNotSupported),
822
+ vec!["::1".to_string(), "198.18.5.5".to_string()],
823
+ 0
824
+ ),
825
+ "a socket's connect must show the connect policy an IPv6 address and an unmapped \
826
+ virtual one before answering EAFNOSUPPORT and EACCES, a socket's bind must answer \
827
+ EAFNOSUPPORT for an IPv6 address, and none may dial"
828
+ );
829
+ }
830
+
831
+ /// A security module refusing every connect.
832
+ struct RefusesConnects;
833
+
834
+ impl SecurityOperations for RefusesConnects {
835
+ fn socket_connect(&self, _connection: &Connection<'_>) -> Result<(), Errno> {
836
+ Err(Errno::PermissionDenied)
837
+ }
838
+ }
839
+
840
+ // @behavior NW-019
841
+ #[test]
842
+ fn a_security_module_refuses_before_any_entry_policy() {
843
+ let (namespace, cred, family, seen) =
844
+ limited_namespace(&[true], None, None, &[Arc::new(RefusesConnects)]);
845
+ let answer = dial(&namespace, &cred, "127.0.0.1:4567".parse().unwrap());
846
+ assert!(
847
+ matches!(answer, Err(Errno::PermissionDenied))
848
+ && seen.lock().unwrap().is_empty()
849
+ && family.dials() == 0,
850
+ "a Wasm Driver's security module refusing socket_connect must refuse before any \
851
+ entry's connect policy is asked, dialing nothing"
852
+ );
853
+ }
854
+
855
+ /// A family resolving every name to what `answers` holds, counting each
856
+ /// lookup, recording each address dialed, and holding `local` as the
857
+ /// host's own addresses, unless `local_unreadable` says it cannot read
858
+ /// them.
859
+ #[derive(Default)]
860
+ struct ResolvesNames {
861
+ answers: Mutex<Vec<IpAddr>>,
862
+ lookups: AtomicUsize,
863
+ dials: Mutex<Vec<SocketAddr>>,
864
+ local: Vec<IpAddr>,
865
+ local_unreadable: bool,
866
+ }
867
+
868
+ impl ProtocolFamily for ResolvesNames {
869
+ fn connect(&self, addr: SocketAddr) -> io::Result<std::net::TcpStream> {
870
+ self.dials.lock().unwrap().push(addr);
871
+ Err(io::ErrorKind::ConnectionRefused.into())
872
+ }
873
+
874
+ fn local_addresses(&self) -> io::Result<Vec<IpAddr>> {
875
+ match self.local_unreadable {
876
+ true => Err(io::ErrorKind::PermissionDenied.into()),
877
+ false => Ok(self.local.clone()),
878
+ }
879
+ }
880
+ }
881
+
882
+ impl Resolver for ResolvesNames {
883
+ fn resolve(&self, _name: &str) -> crate::net::Resolving {
884
+ self.lookups.fetch_add(1, Ordering::SeqCst);
885
+ Box::pin(std::future::ready(Ok(self.answers.lock().unwrap().clone())))
886
+ }
887
+ }
888
+
889
+ /// A namespace of `endpoints` over `family`, its one entry refusing to
890
+ /// resolve `refused`.
891
+ fn resolving_namespace(
892
+ endpoints: Vec<Endpoint>,
893
+ refused: &'static str,
894
+ family: Arc<ResolvesNames>,
895
+ ) -> Namespace {
896
+ let mut entry = crate::network::Builder::default();
897
+ endpoints.into_iter().for_each(|endpoint| {
898
+ entry.endpoint(endpoint);
899
+ });
900
+ entry.resolve_policy(move |name: &Name<'_>| name.name != refused);
901
+ let network = Network::new("names", Arc::new(entry)).unwrap();
902
+ Namespace::for_network(&network, family, Arc::new(crate::net::HyperOutbound::new()))
903
+ }
904
+
905
+ fn tcp(host: &str, port: u16) -> Endpoint {
906
+ Endpoint::new(host, port)
907
+ .unwrap()
908
+ .with_protocol(Protocol::Tcp)
909
+ }
910
+
911
+ /// The answer `lookup` settles on.
912
+ fn wait_for_answer(lookup: &NameLookup) -> Result<Vec<IpAddr>, LookupError> {
913
+ loop {
914
+ if let Some(answer) = lookup.answer() {
915
+ return answer;
916
+ }
917
+ std::thread::sleep(Duration::from_millis(1));
918
+ }
919
+ }
920
+
921
+ #[test]
922
+ fn a_lookup_asks_the_resolver_the_namespace_was_handed_apart_from_its_family() {
923
+ let resolver = Arc::new(ResolvesNames {
924
+ answers: Mutex::new(vec!["10.0.0.1".parse().unwrap()]),
925
+ ..ResolvesNames::default()
926
+ });
927
+ let mut entry = crate::network::Builder::default();
928
+ entry.endpoint(tcp("cache.internal", 6379));
929
+ let network = Network::new("names", Arc::new(entry)).unwrap();
930
+ let namespace = Namespace::new(
931
+ [&network],
932
+ &Backends::new(Arc::new(CountsDials::default()), resolver.clone()),
933
+ OpenConnections::new(None),
934
+ None,
935
+ )
936
+ .expect("the endpoints compile");
937
+ let answer = wait_for_answer(&resolve(&namespace, "cache.internal").unwrap());
938
+ assert_eq!(
939
+ (answer, resolver.lookups.load(Ordering::SeqCst)),
940
+ (Ok(vec!["10.0.0.1".parse().unwrap()]), 1),
941
+ "a guest's lookup must ask the Resolver its network was made with, apart from the \
942
+ Protocol Family that dials, and answer what that Resolver answered"
943
+ );
944
+ }
945
+
946
+ /// The virtual addresses a lookup of `name` hands out, at port 6379.
947
+ fn resolve_virtual_addresses(namespace: &Namespace, name: &str) -> Vec<SocketAddr> {
948
+ let lookup = resolve(namespace, name).expect("the lookup starts");
949
+ wait_for_answer(&lookup).expect("the name resolves");
950
+ namespace
951
+ .alloc_virtual_addresses(&prepare_creds(&[], None), &lookup)
952
+ .expect("the lookup settled")
953
+ .expect("the range has room")
954
+ .into_iter()
955
+ .map(|ip| SocketAddr::new(ip, 6379))
956
+ .collect()
957
+ }
958
+
959
+ /// The one virtual address a lookup of `name`, answering one address,
960
+ /// hands out.
961
+ fn resolve_virtual_address(namespace: &Namespace, name: &str) -> SocketAddr {
962
+ let [at] = resolve_virtual_addresses(namespace, name)[..] else {
963
+ panic!("a lookup answering one address hands out one virtual address");
964
+ };
965
+ at
966
+ }
967
+
968
+ // @behavior NW-024
969
+ #[test]
970
+ fn a_name_no_endpoint_names_or_a_policy_refuses_answers_nxdomain_unasked() {
971
+ let family = Arc::new(ResolvesNames::default());
972
+ let namespace = resolving_namespace(
973
+ vec![tcp("cache.internal", 6379), tcp("*.example.com", 443)],
974
+ "blocked.example.com",
975
+ family.clone(),
976
+ );
977
+ let answers = ["other.internal", "blocked.example.com", "example.com"]
978
+ .map(|name| wait_for_answer(&resolve(&namespace, name).unwrap()));
979
+ assert!(
980
+ answers
981
+ .iter()
982
+ .all(|answer| *answer == Err(LookupError::NoName))
983
+ && family.lookups.load(Ordering::SeqCst) == 0,
984
+ "a guest's lookup of a name no endpoint names, one a resolve policy refuses, or a \
985
+ wildcard's own apex must answer name-unresolvable without asking the resolver, got \
986
+ {answers:?}"
987
+ );
988
+ }
989
+
990
+ /// A resolver failing each name by the kind its first label spells.
991
+ struct FailsByKind;
992
+
993
+ impl Resolver for FailsByKind {
994
+ fn resolve(&self, name: &str) -> crate::net::Resolving {
995
+ let failure = match name.split('.').next() {
996
+ Some("again") => LookupError::Again,
997
+ Some("fail") => LookupError::Fail,
998
+ _ => LookupError::NoName,
999
+ };
1000
+ Box::pin(std::future::ready(Err(failure)))
1001
+ }
1002
+ }
1003
+
1004
+ // @behavior NW-228
1005
+ #[test]
1006
+ fn a_lookup_answers_the_kind_of_failure_its_resolver_names() {
1007
+ let mut entry = crate::network::Builder::default();
1008
+ entry.endpoint(tcp("*.example.com", 443));
1009
+ let network = Network::new("names", Arc::new(entry)).unwrap();
1010
+ let backends = Backends::new(Arc::new(ResolvesNames::default()), Arc::new(FailsByKind));
1011
+ let namespace = Namespace::new([&network], &backends, OpenConnections::new(None), None)
1012
+ .expect("the endpoints compile");
1013
+ let answers = ["gone.example.com", "again.example.com", "fail.example.com"]
1014
+ .map(|name| wait_for_answer(&resolve(&namespace, name).unwrap()));
1015
+ assert_eq!(
1016
+ answers,
1017
+ [
1018
+ Err(LookupError::NoName),
1019
+ Err(LookupError::Again),
1020
+ Err(LookupError::Fail)
1021
+ ],
1022
+ "a guest's lookup must answer name-unresolvable, temporary-resolver-failure, or \
1023
+ permanent-resolver-failure as the resolver finds no address, cannot answer now, or \
1024
+ cannot answer at all"
1025
+ );
1026
+ }
1027
+
1028
+ // @behavior NW-154
1029
+ #[test]
1030
+ fn a_connect_is_refused_when_the_hosts_own_addresses_cannot_be_read() {
1031
+ let family = Arc::new(ResolvesNames {
1032
+ answers: Mutex::new(vec!["8.8.8.8".parse().unwrap()]),
1033
+ local_unreadable: true,
1034
+ ..ResolvesNames::default()
1035
+ });
1036
+ let namespace = resolving_namespace(vec![tcp("api.example.com", 443)], "", family.clone());
1037
+ let cred = prepare_creds(&[], None);
1038
+ let mut at = resolve_virtual_address(&namespace, "api.example.com");
1039
+ at.set_port(443);
1040
+ let answer = dial(&namespace, &cred, at).err();
1041
+ assert_eq!(
1042
+ (answer, family.dials.lock().unwrap().len()),
1043
+ (Some(Errno::PermissionDenied), 0),
1044
+ "a socket's connect must refuse with EACCES, dialing nothing, when the Protocol \
1045
+ Family cannot read the host's own addresses, rather than judge the name's \
1046
+ addresses as if the host had none"
1047
+ );
1048
+ }
1049
+
1050
+ /// A family resolving every name to `8.8.8.8` that does not say the host's
1051
+ /// own addresses, counting how often it dials.
1052
+ #[derive(Default)]
1053
+ struct SaysNoLocalAddresses(AtomicUsize);
1054
+
1055
+ impl ProtocolFamily for SaysNoLocalAddresses {
1056
+ fn connect(&self, _addr: SocketAddr) -> io::Result<std::net::TcpStream> {
1057
+ self.0.fetch_add(1, Ordering::SeqCst);
1058
+ Err(io::ErrorKind::ConnectionRefused.into())
1059
+ }
1060
+ }
1061
+
1062
+ impl Resolver for SaysNoLocalAddresses {
1063
+ fn resolve(&self, _name: &str) -> crate::net::Resolving {
1064
+ Box::pin(std::future::ready(Ok(vec!["8.8.8.8".parse().unwrap()])))
1065
+ }
1066
+ }
1067
+
1068
+ // @behavior NW-154
1069
+ #[test]
1070
+ fn a_connect_is_refused_through_a_family_that_does_not_say_the_hosts_own_addresses() {
1071
+ let family = Arc::new(SaysNoLocalAddresses::default());
1072
+ let mut entry = crate::network::Builder::default();
1073
+ entry.endpoint(tcp("api.example.com", 443));
1074
+ let network = Network::new("names", Arc::new(entry)).unwrap();
1075
+ let namespace = Namespace::for_network(
1076
+ &network,
1077
+ family.clone(),
1078
+ Arc::new(crate::net::HyperOutbound::new()),
1079
+ );
1080
+ let cred = prepare_creds(&[], None);
1081
+ let mut at = resolve_virtual_address(&namespace, "api.example.com");
1082
+ at.set_port(443);
1083
+ let answer = dial(&namespace, &cred, at).err();
1084
+ assert_eq!(
1085
+ (answer, family.0.load(Ordering::SeqCst)),
1086
+ (Some(Errno::PermissionDenied), 0),
1087
+ "a socket's connect through a Protocol Family that leaves the host's own addresses \
1088
+ unsaid must refuse with EACCES, dialing nothing, as one that cannot read them does"
1089
+ );
1090
+ }
1091
+
1092
+ // @behavior NW-154
1093
+ #[test]
1094
+ fn a_request_is_refused_when_the_hosts_own_addresses_cannot_be_read() {
1095
+ let family = Arc::new(ResolvesNames {
1096
+ answers: Mutex::new(vec!["8.8.8.8".parse().unwrap()]),
1097
+ local_unreadable: true,
1098
+ ..ResolvesNames::default()
1099
+ });
1100
+ let endpoint = Endpoint::new("api.example.com", 80).unwrap();
1101
+ let namespace = resolving_namespace(vec![endpoint], "", family.clone());
1102
+ let cred = prepare_creds(&[], None);
1103
+ let exchange = crate::net::send(
1104
+ &namespace,
1105
+ &cred,
1106
+ OutgoingRequest::new("GET", Scheme::Http, "api.example.com:80"),
1107
+ )
1108
+ .expect("the endpoint names the authority");
1109
+ let started = std::time::Instant::now();
1110
+ let answer = loop {
1111
+ if let Some(answer) = exchange.response() {
1112
+ break answer.err();
1113
+ }
1114
+ assert!(
1115
+ started.elapsed() < Duration::from_secs(10),
1116
+ "the request never settles"
1117
+ );
1118
+ std::thread::sleep(Duration::from_millis(1));
1119
+ };
1120
+ assert_eq!(
1121
+ (answer, family.dials.lock().unwrap().len()),
1122
+ (Some(HttpError::Denied), 0),
1123
+ "an HTTP request must answer Denied, dialing nothing, when the Protocol Family \
1124
+ cannot read the host's own addresses"
1125
+ );
1126
+ }
1127
+
1128
+ // @behavior NW-149
1129
+ #[test]
1130
+ fn a_virtual_address_is_held_against_the_invocations_memory() {
1131
+ let family = Arc::new(ResolvesNames {
1132
+ answers: Mutex::new(vec!["127.0.0.1".parse().unwrap()]),
1133
+ ..ResolvesNames::default()
1134
+ });
1135
+ let namespace = resolving_namespace(vec![tcp("cache.internal", 6379)], "", family);
1136
+ let lookup = resolve(&namespace, "cache.internal").expect("the lookup starts");
1137
+ wait_for_answer(&lookup).expect("the name resolves");
1138
+ let full = namespace.alloc_virtual_addresses(&prepare_creds(&[], Some(0)), &lookup);
1139
+ let roomy = namespace.alloc_virtual_addresses(&prepare_creds(&[], None), &lookup);
1140
+ assert_eq!(
1141
+ (full, roomy),
1142
+ (
1143
+ Some(Err(LookupError::Again)),
1144
+ Some(Ok(vec!["198.18.0.0".parse().unwrap()]))
1145
+ ),
1146
+ "a lookup must answer temporary-failure when the Invocation's memory cannot hold \
1147
+ the name's entry, and hand out the bottom of the range once it can"
1148
+ );
1149
+ }
1150
+
1151
+ // @behavior NW-175
1152
+ #[test]
1153
+ fn a_name_keeps_its_virtual_addresses_and_first_answer_for_the_invocation() {
1154
+ let family = Arc::new(ResolvesNames {
1155
+ answers: Mutex::new(vec![
1156
+ "127.0.0.1".parse().unwrap(),
1157
+ "127.0.0.2".parse().unwrap(),
1158
+ ]),
1159
+ ..ResolvesNames::default()
1160
+ });
1161
+ let refusing = Arc::new(std::sync::atomic::AtomicBool::new(false));
1162
+ let mut entry = crate::network::Builder::default();
1163
+ entry.endpoint(tcp("cache.internal", 6379).with_addresses(vec![Addresses::Local]));
1164
+ let refuses = refusing.clone();
1165
+ entry.resolve_policy(move |_: &Name<'_>| !refuses.load(Ordering::SeqCst));
1166
+ let network = Network::new("names", Arc::new(entry)).unwrap();
1167
+ let namespace = Namespace::for_network(
1168
+ &network,
1169
+ family.clone(),
1170
+ Arc::new(crate::net::HyperOutbound::new()),
1171
+ );
1172
+ let first = resolve_virtual_addresses(&namespace, "cache.internal");
1173
+ *family.answers.lock().unwrap() = vec!["10.0.0.1".parse().unwrap()];
1174
+ let again = resolve(&namespace, "Cache.Internal.").expect("the lookup starts");
1175
+ let answer = wait_for_answer(&again);
1176
+ let second = resolve_virtual_addresses(&namespace, "cache.internal");
1177
+ let cred = prepare_creds(&[], None);
1178
+ let sock = dial(&namespace, &cred, second[1]).expect("the endpoint leads there");
1179
+ while matches!(sock.take_connect_outcome(), Err(Errno::WouldBlock)) {
1180
+ std::thread::sleep(Duration::from_millis(1));
1181
+ }
1182
+ refusing.store(true, Ordering::SeqCst);
1183
+ let refused = wait_for_answer(&resolve(&namespace, "cache.internal").expect("it answers"));
1184
+ assert_eq!(
1185
+ (
1186
+ first,
1187
+ second,
1188
+ answer,
1189
+ refused,
1190
+ family.lookups.load(Ordering::SeqCst),
1191
+ namespace.translations.lock().unwrap().entries.len(),
1192
+ family.dials.lock().unwrap().clone()
1193
+ ),
1194
+ (
1195
+ vec![
1196
+ "198.18.0.0:6379".parse().unwrap(),
1197
+ "198.18.0.1:6379".parse().unwrap()
1198
+ ],
1199
+ vec![
1200
+ "198.18.0.0:6379".parse().unwrap(),
1201
+ "198.18.0.1:6379".parse().unwrap()
1202
+ ],
1203
+ Ok(vec![
1204
+ "127.0.0.1".parse().unwrap(),
1205
+ "127.0.0.2".parse().unwrap()
1206
+ ]),
1207
+ Err(LookupError::NoName),
1208
+ 1,
1209
+ 2,
1210
+ vec!["127.0.0.2:6379".parse().unwrap()]
1211
+ ),
1212
+ "a name looked up again in one Invocation, in any spelling of it, must answer the \
1213
+ same virtual addresses, each standing for the same first real address, query the \
1214
+ resolver once, and take no second entries, so a resolver cannot rebind it, while a \
1215
+ resolve policy that refuses it later still answers NXDOMAIN"
1216
+ );
1217
+ }
1218
+
1219
+ // @behavior NW-025
1220
+ #[test]
1221
+ fn a_name_connects_through_its_virtual_address_to_where_its_endpoint_leads() {
1222
+ let family = Arc::new(ResolvesNames {
1223
+ answers: Mutex::new(vec![
1224
+ "127.0.0.1".parse().unwrap(),
1225
+ "10.0.0.1".parse().unwrap(),
1226
+ "127.0.0.1".parse().unwrap(),
1227
+ ]),
1228
+ ..ResolvesNames::default()
1229
+ });
1230
+ let local = tcp("cache.internal", 6379).with_addresses(vec![Addresses::Local]);
1231
+ let namespace =
1232
+ resolving_namespace(vec![local, tcp("api.internal", 6379)], "", family.clone());
1233
+ let cred = prepare_creds(&[], None);
1234
+ let at = resolve_virtual_addresses(&namespace, "Cache.Internal.");
1235
+ let sock = dial(&namespace, &cred, at[0]).expect("the endpoint leads there");
1236
+ while matches!(sock.take_connect_outcome(), Err(Errno::WouldBlock)) {
1237
+ std::thread::sleep(Duration::from_millis(1));
1238
+ }
1239
+ let private = dial(&namespace, &cred, at[1]).err();
1240
+ let public_only = resolve_virtual_addresses(&namespace, "api.internal");
1241
+ let local_refused = dial(&namespace, &cred, public_only[0]).err();
1242
+ assert_eq!(
1243
+ (
1244
+ at,
1245
+ family.dials.lock().unwrap().clone(),
1246
+ private,
1247
+ local_refused
1248
+ ),
1249
+ (
1250
+ vec![
1251
+ "198.18.0.0:6379".parse().unwrap(),
1252
+ "198.18.0.1:6379".parse().unwrap()
1253
+ ],
1254
+ vec!["127.0.0.1:6379".parse().unwrap()],
1255
+ Some(Errno::PermissionDenied),
1256
+ Some(Errno::PermissionDenied)
1257
+ ),
1258
+ "a name's lookup must hand out one virtual address for each real address, one for \
1259
+ a real address its resolver repeats, and a \
1260
+ connect to one must dial only the real address it stands for, refusing one its \
1261
+ endpoint's addresses do not lead to, as an endpoint leading only to public \
1262
+ addresses refuses a local one"
1263
+ );
1264
+ }
1265
+
1266
+ // @behavior NW-026
1267
+ #[test]
1268
+ fn a_virtual_address_no_lookup_handed_out_is_refused() {
1269
+ let namespace = resolving_namespace(vec![tcp("cache.internal", 6379)], "", Arc::default());
1270
+ let cred = prepare_creds(&[], None);
1271
+ assert!(
1272
+ matches!(
1273
+ dial(&namespace, &cred, "198.18.0.9:6379".parse().unwrap()),
1274
+ Err(Errno::PermissionDenied)
1275
+ ),
1276
+ "a connect to a virtual address no lookup handed out must be refused as EACCES"
1277
+ );
1278
+ }
1279
+
1280
+ // @behavior NW-027
1281
+ #[test]
1282
+ fn a_connect_dials_what_the_lookup_answered_never_resolving_again() {
1283
+ let family = Arc::new(ResolvesNames {
1284
+ answers: Mutex::new(vec!["10.0.0.1".parse().unwrap()]),
1285
+ ..ResolvesNames::default()
1286
+ });
1287
+ let private = tcp("cache.internal", 6379).with_addresses(vec![Addresses::Private]);
1288
+ let namespace = resolving_namespace(vec![private], "", family.clone());
1289
+ let at = resolve_virtual_address(&namespace, "cache.internal");
1290
+ *family.answers.lock().unwrap() = vec!["127.0.0.1".parse().unwrap()];
1291
+ let cred = prepare_creds(&[], None);
1292
+ let sock = dial(&namespace, &cred, at).expect("the endpoint leads there");
1293
+ while matches!(sock.take_connect_outcome(), Err(Errno::WouldBlock)) {
1294
+ std::thread::sleep(Duration::from_millis(1));
1295
+ }
1296
+ assert_eq!(
1297
+ (
1298
+ family.lookups.load(Ordering::SeqCst),
1299
+ family.dials.lock().unwrap().clone()
1300
+ ),
1301
+ (1, vec!["10.0.0.1:6379".parse().unwrap()]),
1302
+ "a connect to a virtual address must dial the address its lookup answered, never \
1303
+ resolving the name again"
1304
+ );
1305
+ }
1306
+
1307
+ // @behavior NW-028
1308
+ #[test]
1309
+ fn the_hosts_own_address_is_local_whatever_registry_classes_it() {
1310
+ let own: IpAddr = "93.184.216.34".parse().unwrap();
1311
+ let family = Arc::new(ResolvesNames {
1312
+ answers: Mutex::new(vec![own]),
1313
+ local: vec![own],
1314
+ ..ResolvesNames::default()
1315
+ });
1316
+ let namespace = resolving_namespace(vec![tcp("api.example.com", 6379)], "", family.clone());
1317
+ let at = resolve_virtual_address(&namespace, "api.example.com");
1318
+ let cred = prepare_creds(&[], None);
1319
+ assert!(
1320
+ matches!(dial(&namespace, &cred, at), Err(Errno::PermissionDenied))
1321
+ && family.dials.lock().unwrap().is_empty(),
1322
+ "a name resolving to the host's own public address must be refused by an endpoint \
1323
+ leading only to public addresses, since the host's addresses are local"
1324
+ );
1325
+ }
1326
+
1327
+ // @behavior NW-054
1328
+ #[test]
1329
+ fn a_datagram_stream_passes_only_a_udp_endpoint() {
1330
+ let peer = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1331
+ let port = peer.local_addr().unwrap().port();
1332
+ let udp = Endpoint::new("127.0.0.1", port)
1333
+ .unwrap()
1334
+ .with_protocol(Protocol::Udp);
1335
+ let tcp_only = tcp("127.0.0.2", port);
1336
+ let network = Network::new(
1337
+ "dgram",
1338
+ Arc::new({
1339
+ let mut entry = crate::network::Builder::default();
1340
+ entry.endpoint(udp).endpoint(tcp_only);
1341
+ entry
1342
+ }),
1343
+ )
1344
+ .unwrap();
1345
+ let namespace = Namespace::for_network(
1346
+ &network,
1347
+ Arc::new(crate::net::HostInet),
1348
+ Arc::new(crate::net::HyperOutbound::new()),
1349
+ );
1350
+ let cred = prepare_creds(&[], None);
1351
+ let admitted = dial_datagram(&namespace, &cred, Some(peer.local_addr().unwrap()));
1352
+ let refused = dial_datagram(
1353
+ &namespace,
1354
+ &cred,
1355
+ Some(format!("127.0.0.2:{port}").parse().unwrap()),
1356
+ );
1357
+ if let Ok(sock) = &admitted {
1358
+ crate::net::ProtoOps::release(&**sock);
1359
+ }
1360
+ assert!(
1361
+ admitted.is_ok() && matches!(refused, Err(Errno::PermissionDenied)),
1362
+ "a UDP socket's connect must pass an address a udp endpoint names and refuse one \
1363
+ only a tcp endpoint names"
1364
+ );
1365
+ }
1366
+ }