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,777 @@
1
+ //! What the guest may reach, compiled for one Invocation from every entry's
2
+ //! endpoints, as an nftables ruleset with a default policy of drop. The fixed
3
+ //! sets, `metadata` and `reserved`, are kobako's own and sit in no entry, so no
4
+ //! setting reaches them.
5
+
6
+ use std::fmt;
7
+ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
8
+
9
+ use super::{ensure_nonzero_port, Action, Addresses, Endpoint, EntryError, HttpRule, Protocol};
10
+ use crate::Errno;
11
+
12
+ /// Where an address falls, by IANA's special-purpose registries.
13
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
14
+ pub enum AddressSet {
15
+ /// Globally reachable unicast.
16
+ Public,
17
+ /// RFC 1918, shared address space, and unique local addresses.
18
+ Private,
19
+ /// Loopback and this host's network.
20
+ Local,
21
+ /// Link-local addresses and the cloud metadata endpoints, never reached.
22
+ Metadata,
23
+ /// Multicast, broadcast, documentation, transition, and the virtual
24
+ /// range, never reached.
25
+ Reserved,
26
+ }
27
+
28
+ /// The cloud metadata endpoints beyond link-local, never reached.
29
+ const METADATA_V4: [Ipv4Addr; 2] = [
30
+ Ipv4Addr::new(100, 100, 100, 200),
31
+ Ipv4Addr::new(168, 63, 129, 16),
32
+ ];
33
+
34
+ const METADATA_V6: [Ipv6Addr; 3] = [
35
+ Ipv6Addr::new(0xfd00, 0xec2, 0, 0, 0, 0, 0, 0x254),
36
+ Ipv6Addr::new(0xfd00, 0xec2, 0, 0, 0, 0, 0, 0x23),
37
+ Ipv6Addr::new(0xfd20, 0xce, 0, 0, 0, 0, 0, 0x254),
38
+ ];
39
+
40
+ fn is_within(ip: Ipv4Addr, net: [u8; 4], prefix: u32) -> bool {
41
+ let mask = u32::MAX.checked_shl(32 - prefix).unwrap_or(0);
42
+ u32::from(ip) & mask == u32::from(Ipv4Addr::from(net)) & mask
43
+ }
44
+
45
+ fn is_within_v6(ip: Ipv6Addr, net: Ipv6Addr, prefix: u32) -> bool {
46
+ let mask = u128::MAX.checked_shl(128 - prefix).unwrap_or(0);
47
+ u128::from(ip) & mask == u128::from(net) & mask
48
+ }
49
+
50
+ /// The IPv4 address an IPv6 one carries, as a mapped, compatible, or NAT64
51
+ /// address does, so each is judged as the IPv4 inside. NAT64 takes both the
52
+ /// well-known prefix and the local-use one at its /96, as RFC 8215 lets a
53
+ /// DNS64 synthesize either.
54
+ fn to_v4(ip: Ipv6Addr) -> Option<Ipv4Addr> {
55
+ if let Some(v4) = ip.to_ipv4_mapped() {
56
+ return Some(v4);
57
+ }
58
+ let nat64 = Ipv6Addr::new(0x64, 0xff9b, 0, 0, 0, 0, 0, 0);
59
+ let local_nat64 = Ipv6Addr::new(0x64, 0xff9b, 1, 0, 0, 0, 0, 0);
60
+ let compatible = Ipv6Addr::UNSPECIFIED;
61
+ let carried = Ipv4Addr::from((u128::from(ip) & 0xffff_ffff) as u32);
62
+ match is_within_v6(ip, nat64, 96)
63
+ || is_within_v6(ip, local_nat64, 96)
64
+ || (is_within_v6(ip, compatible, 96) && u32::from(carried) > 1)
65
+ {
66
+ true => Some(carried),
67
+ false => None,
68
+ }
69
+ }
70
+
71
+ /// The set `ip` falls in, judging an IPv6 address carrying an IPv4 one as
72
+ /// that IPv4 address.
73
+ pub fn address_set_of(ip: IpAddr) -> AddressSet {
74
+ match ip {
75
+ IpAddr::V4(ip) => v4_set_of(ip),
76
+ IpAddr::V6(ip) => match to_v4(ip) {
77
+ Some(v4) => v4_set_of(v4),
78
+ None => v6_set_of(ip),
79
+ },
80
+ }
81
+ }
82
+
83
+ fn v4_set_of(ip: Ipv4Addr) -> AddressSet {
84
+ let globally_reachable = [
85
+ ([192, 0, 0, 9], 32),
86
+ ([192, 0, 0, 10], 32),
87
+ ([192, 31, 196, 0], 24),
88
+ ([192, 52, 193, 0], 24),
89
+ ([192, 175, 48, 0], 24),
90
+ ];
91
+ if METADATA_V4.contains(&ip) || is_within(ip, [169, 254, 0, 0], 16) {
92
+ AddressSet::Metadata
93
+ } else if is_within(ip, [127, 0, 0, 0], 8) || is_within(ip, [0, 0, 0, 0], 8) {
94
+ AddressSet::Local
95
+ } else if is_within(ip, [10, 0, 0, 0], 8)
96
+ || is_within(ip, [172, 16, 0, 0], 12)
97
+ || is_within(ip, [192, 168, 0, 0], 16)
98
+ || is_within(ip, [100, 64, 0, 0], 10)
99
+ {
100
+ AddressSet::Private
101
+ } else if globally_reachable
102
+ .iter()
103
+ .any(|(net, prefix)| is_within(ip, *net, *prefix))
104
+ {
105
+ AddressSet::Public
106
+ } else if is_within(ip, [192, 0, 0, 0], 24)
107
+ || is_within(ip, [192, 0, 2, 0], 24)
108
+ || is_within(ip, [192, 88, 99, 0], 24)
109
+ || is_within(ip, [198, 18, 0, 0], 15)
110
+ || is_within(ip, [198, 51, 100, 0], 24)
111
+ || is_within(ip, [203, 0, 113, 0], 24)
112
+ || is_within(ip, [224, 0, 0, 0], 4)
113
+ || is_within(ip, [240, 0, 0, 0], 4)
114
+ {
115
+ AddressSet::Reserved
116
+ } else {
117
+ AddressSet::Public
118
+ }
119
+ }
120
+
121
+ /// An IPv6 address's set. Only global unicast, `2000::/3`, is routed, so any
122
+ /// other address is reserved; within it, each block IANA's registry says no
123
+ /// route reaches is reserved, save the ones inside `2001::/23` it marks
124
+ /// globally reachable.
125
+ fn v6_set_of(ip: Ipv6Addr) -> AddressSet {
126
+ let net = |a: u16, b: u16, c: u16| Ipv6Addr::new(a, b, c, 0, 0, 0, 0, 0);
127
+ let globally_reachable = [
128
+ (Ipv6Addr::new(0x2001, 1, 0, 0, 0, 0, 0, 1), 128),
129
+ (Ipv6Addr::new(0x2001, 1, 0, 0, 0, 0, 0, 2), 128),
130
+ (Ipv6Addr::new(0x2001, 1, 0, 0, 0, 0, 0, 3), 128),
131
+ (net(0x2001, 3, 0), 32),
132
+ (net(0x2001, 4, 0x112), 48),
133
+ (net(0x2001, 0x20, 0), 28),
134
+ (net(0x2001, 0x30, 0), 28),
135
+ ];
136
+ if METADATA_V6.contains(&ip) || is_within_v6(ip, net(0xfe80, 0, 0), 10) {
137
+ AddressSet::Metadata
138
+ } else if ip == Ipv6Addr::LOCALHOST || ip == Ipv6Addr::UNSPECIFIED {
139
+ AddressSet::Local
140
+ } else if is_within_v6(ip, net(0xfc00, 0, 0), 7) {
141
+ AddressSet::Private
142
+ } else if !is_within_v6(ip, net(0x2000, 0, 0), 3)
143
+ || is_within_v6(ip, net(0x2001, 0xdb8, 0), 32)
144
+ || is_within_v6(ip, net(0x2002, 0, 0), 16)
145
+ || is_within_v6(ip, net(0x3fff, 0, 0), 20)
146
+ || (is_within_v6(ip, net(0x2001, 0, 0), 23)
147
+ && !globally_reachable
148
+ .iter()
149
+ .any(|(block, prefix)| is_within_v6(ip, *block, *prefix)))
150
+ {
151
+ AddressSet::Reserved
152
+ } else {
153
+ AddressSet::Public
154
+ }
155
+ }
156
+
157
+ /// A host the guest names, as wasmtime-wasi's lookup reads one with the URL
158
+ /// host parser, so the hooks, the endpoints, and the resolver judge one
159
+ /// spelling of it.
160
+ #[derive(Clone, Debug, PartialEq, Eq)]
161
+ pub(crate) enum Host {
162
+ /// An address, from any IPv4 spelling the parser reads or a bare IPv6 one.
163
+ Address(IpAddr),
164
+ /// A name as its A-label: lowercase, with no trailing dot for the root.
165
+ Name(String),
166
+ }
167
+
168
+ impl Host {
169
+ /// `host` as the URL host parser reads it; `None` for one it refuses, as
170
+ /// for a code point no host holds, and for a name left ending in an empty
171
+ /// label once the root's one dot is dropped.
172
+ pub(crate) fn parse(host: &str) -> Option<Self> {
173
+ match url::Host::parse(host) {
174
+ Ok(url::Host::Ipv4(ip)) => Some(Self::Address(ip.into())),
175
+ Ok(url::Host::Ipv6(ip)) => Some(Self::Address(ip.into())),
176
+ Ok(url::Host::Domain(name)) => {
177
+ let name = name.strip_suffix('.').unwrap_or(&name);
178
+ (!name.is_empty() && !name.ends_with('.')).then(|| Self::Name(name.to_string()))
179
+ }
180
+ // The parser reads an IPv6 address only in brackets.
181
+ Err(_) => host
182
+ .parse::<Ipv6Addr>()
183
+ .ok()
184
+ .map(|ip| Self::Address(ip.into())),
185
+ }
186
+ }
187
+ }
188
+
189
+ impl fmt::Display for Host {
190
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191
+ match self {
192
+ Self::Address(ip) => ip.fmt(f),
193
+ Self::Name(name) => f.write_str(name),
194
+ }
195
+ }
196
+ }
197
+
198
+ /// What an endpoint's host matches.
199
+ #[derive(Clone, Debug, PartialEq, Eq)]
200
+ enum Pattern {
201
+ /// An exact name.
202
+ Name(String),
203
+ /// Every name ending in this suffix on a label boundary, as `*.` gives it.
204
+ Wildcard(String),
205
+ /// An address or a prefix, reaching what it names.
206
+ Cidr(IpAddr, u8),
207
+ }
208
+
209
+ /// Why `address/prefix` text names no CIDR.
210
+ pub(crate) enum CidrFault {
211
+ NoAddress,
212
+ OutOfRange,
213
+ }
214
+
215
+ /// The address and prefix `address/prefix` spells, the prefix within its
216
+ /// address's width; `None` for text holding no `/`.
217
+ pub(crate) fn parse_cidr(text: &str) -> Option<Result<(IpAddr, u8), CidrFault>> {
218
+ let (ip, prefix) = text.split_once('/')?;
219
+ let Ok(ip) = ip.parse::<IpAddr>() else {
220
+ return Some(Err(CidrFault::NoAddress));
221
+ };
222
+ Some(
223
+ prefix
224
+ .parse::<u8>()
225
+ .ok()
226
+ .filter(|p| *p <= full_prefix_of(ip))
227
+ .map(|prefix| (ip, prefix))
228
+ .ok_or(CidrFault::OutOfRange),
229
+ )
230
+ }
231
+
232
+ fn parse_host(host: &str) -> Result<Pattern, EntryError> {
233
+ if let Some(cidr) = parse_cidr(host) {
234
+ return match cidr {
235
+ Ok((ip, prefix)) => Ok(Pattern::Cidr(ip, prefix)),
236
+ Err(CidrFault::NoAddress) => Err(EntryError(format!(
237
+ "an endpoint's prefix is no address: {host}"
238
+ ))),
239
+ Err(CidrFault::OutOfRange) => Err(EntryError(format!(
240
+ "an endpoint's prefix is out of range: {host}"
241
+ ))),
242
+ };
243
+ }
244
+ // A host is read as the guest's is, so an address in any spelling, and
245
+ // an IDN as its A-label, matches what the guest names.
246
+ let no_host = || EntryError(format!("an endpoint's host is no address or name: {host}"));
247
+ match host.strip_prefix("*.") {
248
+ Some(suffix) if !suffix.is_empty() => match Host::parse(suffix) {
249
+ Some(Host::Name(name)) => Ok(Pattern::Wildcard(name)),
250
+ _ => Err(no_host()),
251
+ },
252
+ _ => match Host::parse(host).ok_or_else(no_host)? {
253
+ Host::Address(ip) => Ok(Pattern::Cidr(ip, full_prefix_of(ip))),
254
+ Host::Name(name) => Ok(Pattern::Name(name)),
255
+ },
256
+ }
257
+ }
258
+
259
+ /// The address an endpoint judges `ip` as, the IPv4 one an IPv6 address
260
+ /// carries in its place; `None` for an address in a fixed set, which no
261
+ /// endpoint opens.
262
+ fn to_screened(ip: IpAddr) -> Option<IpAddr> {
263
+ if matches!(
264
+ address_set_of(ip),
265
+ AddressSet::Metadata | AddressSet::Reserved
266
+ ) {
267
+ return None;
268
+ }
269
+ Some(match ip {
270
+ IpAddr::V6(v6) => to_v4(v6).map_or(ip, IpAddr::V4),
271
+ v4 => v4,
272
+ })
273
+ }
274
+
275
+ /// The longest prefix an address of `ip`'s family takes.
276
+ fn full_prefix_of(ip: IpAddr) -> u8 {
277
+ match ip {
278
+ IpAddr::V4(_) => 32,
279
+ IpAddr::V6(_) => 128,
280
+ }
281
+ }
282
+
283
+ /// Whether `ip` is within `net` at `prefix`, an address of another family
284
+ /// never, read in `is_within`'s order.
285
+ fn is_within_net(ip: IpAddr, net: IpAddr, prefix: u8) -> bool {
286
+ match (net, ip) {
287
+ (IpAddr::V4(net), IpAddr::V4(ip)) => is_within(ip, net.octets(), u32::from(prefix)),
288
+ (IpAddr::V6(net), IpAddr::V6(ip)) => is_within_v6(ip, net, u32::from(prefix)),
289
+ _ => false,
290
+ }
291
+ }
292
+
293
+ struct Rule {
294
+ host: Pattern,
295
+ port: u16,
296
+ protocol: Protocol,
297
+ addresses: Vec<Addresses>,
298
+ rules: Vec<HttpRule>,
299
+ }
300
+
301
+ /// Whether `path` reads as one path to every server: a `.` or `..` segment,
302
+ /// an empty one inside the path, an encoded slash or backslash, an encoded
303
+ /// unreserved character, a backslash, or a `;` lets servers normalize or split
304
+ /// it differently (RFC 3986 § 5.2.4, § 6.2.2.2), so a rule matching one
305
+ /// spelling would pass another.
306
+ fn is_unambiguous(path: &str) -> bool {
307
+ let lower = path.to_ascii_lowercase();
308
+ !(path
309
+ .split('/')
310
+ .any(|segment| segment == "." || segment == "..")
311
+ || path.contains("//")
312
+ || ["%2f", "%5c", "\\", ";"]
313
+ .iter()
314
+ .any(|sign| lower.contains(sign))
315
+ || lower
316
+ .split('%')
317
+ .skip(1)
318
+ .any(|escape| escape.get(..2).is_some_and(encodes_unreserved)))
319
+ }
320
+
321
+ /// Whether the two hex digits `hex` encode a character RFC 3986 calls
322
+ /// unreserved, which a server may decode before it matches.
323
+ fn encodes_unreserved(hex: &str) -> bool {
324
+ u8::from_str_radix(hex, 16)
325
+ .is_ok_and(|byte| byte.is_ascii_alphanumeric() || b"-._~".contains(&byte))
326
+ }
327
+
328
+ impl Rule {
329
+ /// Whether this rule speaks `protocol` at `port`.
330
+ fn serves(&self, port: u16, protocol: Protocol) -> bool {
331
+ self.port == port && self.protocol == protocol
332
+ }
333
+
334
+ /// Whether this rule's host holds `host`, a name or a literal address.
335
+ fn holds(&self, host: &Host) -> bool {
336
+ match host {
337
+ Host::Address(ip) => self.holds_address(*ip),
338
+ Host::Name(name) => self.names(name),
339
+ }
340
+ }
341
+
342
+ /// Whether this rule's address host holds `ip`, a literal the guest named,
343
+ /// judged as the address it stands for and never in the fixed sets.
344
+ fn holds_address(&self, ip: IpAddr) -> bool {
345
+ to_screened(ip).is_some_and(
346
+ |ip| matches!(self.host, Pattern::Cidr(net, prefix) if is_within_net(ip, net, prefix)),
347
+ )
348
+ }
349
+
350
+ /// Whether this endpoint's rules allow `method` on `path`: with none,
351
+ /// every request; with some, one allowing it exactly and none denying it
352
+ /// in any spelling a lenient server routes the same.
353
+ fn allows_request(&self, method: &str, path: &str) -> bool {
354
+ self.rules.is_empty()
355
+ || (is_unambiguous(path)
356
+ && self
357
+ .rules
358
+ .iter()
359
+ .any(|rule| rule.action == Action::Allow && rule.matches(method, path))
360
+ && !self.rules.iter().any(|rule| {
361
+ rule.action == Action::Deny && rule.matches_leniently(method, path)
362
+ }))
363
+ }
364
+
365
+ /// Whether this rule's host names `name`, exactly or beneath its wildcard
366
+ /// on a label boundary.
367
+ fn names(&self, name: &str) -> bool {
368
+ match &self.host {
369
+ Pattern::Name(host) => host == name,
370
+ Pattern::Wildcard(suffix) => name
371
+ .strip_suffix(suffix.as_str())
372
+ .is_some_and(|head| head.len() > 1 && head.ends_with('.')),
373
+ Pattern::Cidr(..) => false,
374
+ }
375
+ }
376
+
377
+ /// Whether `ip`, a real address the endpoint's host resolved to, falls
378
+ /// where this rule's `addresses` let it lead. `local` holds the host's own
379
+ /// addresses, which are local whatever registry classes them.
380
+ fn leads_to(&self, ip: IpAddr, local: &[IpAddr]) -> bool {
381
+ let own = local.contains(&ip);
382
+ self.addresses.iter().any(|addresses| match addresses {
383
+ Addresses::Public => !own && address_set_of(ip) == AddressSet::Public,
384
+ Addresses::Private => !own && address_set_of(ip) == AddressSet::Private,
385
+ Addresses::Local => own || address_set_of(ip) == AddressSet::Local,
386
+ Addresses::Cidr(net, prefix) => is_within_net(ip, *net, *prefix),
387
+ })
388
+ }
389
+ }
390
+
391
+ /// Every endpoint one Invocation's entries let the guest reach.
392
+ pub struct Ruleset {
393
+ rules: Vec<Rule>,
394
+ }
395
+
396
+ impl Ruleset {
397
+ /// The ruleset of `endpoints`, refused for an endpoint whose host names no
398
+ /// address, prefix, or name, or whose port is zero, and for a wildcard
399
+ /// leading to `private` or `local`, where a guest-controlled name beneath
400
+ /// it could reach.
401
+ pub fn new(endpoints: impl IntoIterator<Item = Endpoint>) -> Result<Self, EntryError> {
402
+ let rules = endpoints
403
+ .into_iter()
404
+ .map(|endpoint| {
405
+ let host = parse_host(&endpoint.host)?;
406
+ ensure_nonzero_port(&endpoint.host, endpoint.port)?;
407
+ if matches!(host, Pattern::Wildcard(_))
408
+ && endpoint
409
+ .addresses
410
+ .iter()
411
+ .any(|a| matches!(a, Addresses::Private | Addresses::Local))
412
+ {
413
+ return Err(EntryError(format!(
414
+ "a wildcard endpoint may lead only to public addresses or a CIDR: {}",
415
+ endpoint.host
416
+ )));
417
+ }
418
+ if endpoint.addresses.iter().any(|a| match a {
419
+ Addresses::Cidr(ip, prefix) => *prefix > full_prefix_of(*ip),
420
+ _ => false,
421
+ }) {
422
+ return Err(EntryError(format!(
423
+ "an endpoint's addresses hold a prefix out of range: {}",
424
+ endpoint.host
425
+ )));
426
+ }
427
+ Ok(Rule {
428
+ host,
429
+ port: endpoint.port,
430
+ protocol: endpoint.protocol,
431
+ addresses: endpoint.addresses,
432
+ rules: endpoint.rules,
433
+ })
434
+ })
435
+ .collect::<Result<_, EntryError>>()?;
436
+ Ok(Self { rules })
437
+ }
438
+
439
+ /// Whether any endpoint's host names `name`, so a lookup of it may run.
440
+ pub fn admits_name(&self, name: &str) -> bool {
441
+ self.rules.iter().any(|rule| rule.names(name))
442
+ }
443
+
444
+ /// Whether a credential of these endpoints' entry is bound to a request to
445
+ /// `host` at `port` by `method` on `path`: an `http` endpoint names that
446
+ /// exact host, never through a wildcard or an address, and allows the
447
+ /// request, on a path every server reads alike. The scheme is the caller's
448
+ /// to hold to `https`.
449
+ pub fn binds(&self, host: &str, port: u16, method: &str, path: &str) -> bool {
450
+ is_unambiguous(path)
451
+ && self.rules.iter().any(|rule| {
452
+ rule.serves(port, Protocol::Http)
453
+ && matches!(&rule.host, Pattern::Name(name) if name == host)
454
+ && rule.allows_request(method, path)
455
+ })
456
+ }
457
+
458
+ /// Whether an `http` endpoint holding `host` at `port` allows `method` on
459
+ /// `path`, the path with no query: endpoints join, so any one allowing it
460
+ /// admits the request.
461
+ pub(crate) fn admits_request(&self, host: &Host, port: u16, method: &str, path: &str) -> bool {
462
+ self.rules.iter().any(|rule| {
463
+ rule.serves(port, Protocol::Http)
464
+ && rule.holds(host)
465
+ && rule.allows_request(method, path)
466
+ })
467
+ }
468
+
469
+ /// The addresses at `port`, of `real` that the name the guest looked up
470
+ /// resolved to, it may open a `protocol` connection to, in their order;
471
+ /// the host's own addresses, `local`, count as local. The fixed sets
472
+ /// refuse whatever an endpoint says; otherwise an endpoint naming the name
473
+ /// at that port and protocol must lead to the address, so another allowed
474
+ /// name answering the same address never borrows it.
475
+ pub fn admitted_addresses_of(
476
+ &self,
477
+ name: &str,
478
+ real: &[IpAddr],
479
+ port: u16,
480
+ protocol: Protocol,
481
+ local: &[IpAddr],
482
+ ) -> Vec<SocketAddr> {
483
+ real.iter()
484
+ .map(|ip| SocketAddr::new(*ip, port))
485
+ .filter(|addr| self.admits_resolved(name, *addr, protocol, local))
486
+ .collect()
487
+ }
488
+
489
+ fn admits_resolved(
490
+ &self,
491
+ name: &str,
492
+ addr: SocketAddr,
493
+ protocol: Protocol,
494
+ local: &[IpAddr],
495
+ ) -> bool {
496
+ let Some(ip) = to_screened(addr.ip()) else {
497
+ return false;
498
+ };
499
+ self.rules.iter().any(|rule| {
500
+ rule.serves(addr.port(), protocol) && rule.names(name) && rule.leads_to(ip, local)
501
+ })
502
+ }
503
+
504
+ /// Whether the guest may open a `protocol` connection to `addr`, the
505
+ /// literal address it named, as nftables judges each address: refused
506
+ /// unless an endpoint with an address host holds it, and refused in the
507
+ /// fixed sets whatever an endpoint says. An `http` endpoint never admits
508
+ /// raw TCP, so its rules cannot be framed around.
509
+ pub fn admit_literal(&self, addr: SocketAddr, protocol: Protocol) -> Result<(), Errno> {
510
+ let matched = self
511
+ .rules
512
+ .iter()
513
+ .any(|rule| rule.serves(addr.port(), protocol) && rule.holds_address(addr.ip()));
514
+ match matched {
515
+ true => Ok(()),
516
+ false => Err(Errno::PermissionDenied),
517
+ }
518
+ }
519
+ }
520
+
521
+ #[cfg(test)]
522
+ mod tests {
523
+ use super::*;
524
+
525
+ // @behavior NW-012
526
+ #[test]
527
+ fn each_address_falls_in_its_set() {
528
+ let set = |ip: &str| address_set_of(ip.parse().unwrap());
529
+ assert_eq!(
530
+ [
531
+ set("93.184.216.34"),
532
+ set("10.1.2.3"),
533
+ set("100.64.0.1"),
534
+ set("127.0.0.1"),
535
+ set("::1"),
536
+ set("169.254.169.254"),
537
+ set("fd00:ec2::254"),
538
+ set("100.100.100.200"),
539
+ set("224.0.0.1"),
540
+ set("198.18.0.1"),
541
+ set("255.255.255.255"),
542
+ set("::ffff:169.254.169.254"),
543
+ set("64:ff9b::a9fe:a9fe"),
544
+ set("64:ff9b:1::a9fe:a9fe"),
545
+ set("64:ff9b:1:1::1"),
546
+ set("2001:2::1"),
547
+ set("2001:20::1"),
548
+ set("3fff::1"),
549
+ set("5f00::1"),
550
+ set("fec0::1"),
551
+ set("2606:4700::1111"),
552
+ ],
553
+ [
554
+ AddressSet::Public,
555
+ AddressSet::Private,
556
+ AddressSet::Private,
557
+ AddressSet::Local,
558
+ AddressSet::Local,
559
+ AddressSet::Metadata,
560
+ AddressSet::Metadata,
561
+ AddressSet::Metadata,
562
+ AddressSet::Reserved,
563
+ AddressSet::Reserved,
564
+ AddressSet::Reserved,
565
+ AddressSet::Metadata,
566
+ AddressSet::Metadata,
567
+ AddressSet::Metadata,
568
+ AddressSet::Reserved,
569
+ AddressSet::Reserved,
570
+ AddressSet::Public,
571
+ AddressSet::Reserved,
572
+ AddressSet::Reserved,
573
+ AddressSet::Reserved,
574
+ AddressSet::Public,
575
+ ],
576
+ "each address must fall in the address set IANA's registries give it, an IPv6 address \
577
+ carrying an IPv4 one judged as the IPv4 inside, and an IPv6 address public only \
578
+ within 2000::/3 and outside every block the registry says no route reaches"
579
+ );
580
+ }
581
+
582
+ fn ruleset(endpoints: &[(&str, u16, Protocol)]) -> Ruleset {
583
+ Ruleset::new(endpoints.iter().map(|(host, port, protocol)| {
584
+ Endpoint::new(*host, *port)
585
+ .unwrap()
586
+ .with_protocol(*protocol)
587
+ }))
588
+ .expect("each host parses")
589
+ }
590
+
591
+ // @behavior NW-013
592
+ #[test]
593
+ fn a_literal_passes_only_an_endpoint_naming_its_address() {
594
+ let rules = ruleset(&[
595
+ ("127.0.0.1", 4567, Protocol::Tcp),
596
+ ("10.0.0.0/8", 6379, Protocol::Tcp),
597
+ ]);
598
+ let admit =
599
+ |addr: &str, protocol| rules.admit_literal(addr.parse().unwrap(), protocol).is_ok();
600
+ assert_eq!(
601
+ [
602
+ admit("127.0.0.1:4567", Protocol::Tcp),
603
+ admit("10.9.9.9:6379", Protocol::Tcp),
604
+ admit("127.0.0.1:4568", Protocol::Tcp),
605
+ admit("127.0.0.2:4567", Protocol::Tcp),
606
+ admit("127.0.0.1:4567", Protocol::Udp),
607
+ ],
608
+ [true, true, false, false, false],
609
+ "a connect to an address must pass only through an endpoint whose address host holds \
610
+ it, at its port and protocol"
611
+ );
612
+ }
613
+
614
+ // @behavior NW-014
615
+ #[test]
616
+ fn the_fixed_sets_refuse_whatever_an_endpoint_names() {
617
+ let rules = ruleset(&[
618
+ ("169.254.169.254", 80, Protocol::Tcp),
619
+ ("224.0.0.1", 80, Protocol::Tcp),
620
+ ]);
621
+ assert!(
622
+ rules
623
+ .admit_literal("169.254.169.254:80".parse().unwrap(), Protocol::Tcp)
624
+ .is_err()
625
+ && rules
626
+ .admit_literal("224.0.0.1:80".parse().unwrap(), Protocol::Tcp)
627
+ .is_err(),
628
+ "a connect to a metadata or reserved address must be refused though an endpoint \
629
+ names it"
630
+ );
631
+ }
632
+
633
+ // @behavior NW-015
634
+ #[test]
635
+ fn an_http_endpoint_admits_no_raw_tcp() {
636
+ let rules = ruleset(&[("127.0.0.1", 8080, Protocol::Http)]);
637
+ assert!(
638
+ rules
639
+ .admit_literal("127.0.0.1:8080".parse().unwrap(), Protocol::Tcp)
640
+ .is_err(),
641
+ "a raw TCP connect to an http endpoint's address must be refused"
642
+ );
643
+ }
644
+
645
+ // @behavior NW-075
646
+ #[test]
647
+ fn an_endpoint_names_an_idn_by_its_a_label() {
648
+ let rules = Ruleset::new([
649
+ Endpoint::new("bücher.example", 443).unwrap(),
650
+ Endpoint::new("*.例え.jp", 443).unwrap(),
651
+ Endpoint::new("rooted.example.", 443).unwrap(),
652
+ ])
653
+ .unwrap();
654
+ let empty_label = Ruleset::new([Endpoint::new("empty.example..", 443).unwrap()]);
655
+ assert_eq!(
656
+ [
657
+ rules.admits_name("xn--bcher-kva.example"),
658
+ rules.admits_name("www.xn--r8jz45g.jp"),
659
+ Host::parse("Rooted.Example.").is_some_and(
660
+ |host| matches!(host, Host::Name(name) if rules.admits_name(&name))
661
+ ),
662
+ empty_label.is_err(),
663
+ Host::parse("empty.example..").is_none(),
664
+ ],
665
+ [true, true, true, true, true],
666
+ "Ruleset::admits_name must match an endpoint written as an IDN, and a wildcard over \
667
+ one, against the A-label the guest's lookup asks for; an endpoint and a lookup must \
668
+ drop the root's one trailing dot alike, and both refuse a name left ending in an \
669
+ empty label"
670
+ );
671
+ }
672
+
673
+ // @behavior NW-029
674
+ #[test]
675
+ fn a_wildcard_leading_to_private_or_local_addresses_is_refused() {
676
+ let wildcard = |addresses| {
677
+ Ruleset::new([Endpoint::new("*.example.com", 443)
678
+ .unwrap()
679
+ .with_addresses(addresses)])
680
+ .is_ok()
681
+ };
682
+ assert_eq!(
683
+ [
684
+ wildcard(vec![Addresses::Private]),
685
+ wildcard(vec![Addresses::Local]),
686
+ wildcard(vec![
687
+ Addresses::Public,
688
+ Addresses::Cidr("10.0.0.0".parse().unwrap(), 8)
689
+ ]),
690
+ ],
691
+ [false, false, true],
692
+ "an invocation's ruleset must refuse a wildcard endpoint leading to private or local \
693
+ addresses, and keep one leading to public addresses or a CIDR"
694
+ );
695
+ }
696
+
697
+ // @behavior NW-008
698
+ #[test]
699
+ fn an_endpoint_whose_port_turns_zero_is_refused() {
700
+ let mut endpoint = Endpoint::new("api.example.com", 443).unwrap();
701
+ endpoint.port = 0;
702
+ assert!(
703
+ Ruleset::new([endpoint]).is_err(),
704
+ "an invocation's ruleset must refuse an endpoint whose port was set to zero after \
705
+ Endpoint::new built it"
706
+ );
707
+ }
708
+
709
+ // @behavior NW-150
710
+ #[test]
711
+ fn an_address_prefix_out_of_range_is_refused() {
712
+ let leading_to = |ip: &str, prefix| {
713
+ Ruleset::new([Endpoint::new("api.example.com", 443)
714
+ .unwrap()
715
+ .with_addresses(vec![Addresses::Cidr(ip.parse().unwrap(), prefix)])])
716
+ .is_ok()
717
+ };
718
+ assert_eq!(
719
+ [
720
+ leading_to("10.0.0.0", 32),
721
+ leading_to("10.0.0.0", 40),
722
+ leading_to("fd00::", 128),
723
+ leading_to("fd00::", 129),
724
+ ],
725
+ [true, false, true, false],
726
+ "Ruleset::new must refuse an endpoint whose addresses hold a CIDR prefix longer than \
727
+ its family's address, and keep one at the full length"
728
+ );
729
+ }
730
+
731
+ // @behavior NW-044
732
+ #[test]
733
+ fn an_http_endpoints_rules_admit_only_the_methods_and_paths_they_allow() {
734
+ let rules = Ruleset::new([
735
+ Endpoint::new("api.example.com", 443)
736
+ .unwrap()
737
+ .with_rules(vec![
738
+ HttpRule::new(Action::Allow, Some("get"), "/repos/**"),
739
+ HttpRule::new(Action::Allow, None, "/status"),
740
+ HttpRule::new(Action::Deny, None, "/repos/*/secrets"),
741
+ ]),
742
+ Endpoint::new("open.example.com", 443).unwrap(),
743
+ ])
744
+ .unwrap();
745
+ let admit = |host, method, path| {
746
+ rules.admits_request(&Host::parse(host).unwrap(), 443, method, path)
747
+ };
748
+ assert_eq!(
749
+ [
750
+ admit("api.example.com", "GET", "/repos/a/b"),
751
+ admit("api.example.com", "POST", "/repos/a/b"),
752
+ admit("api.example.com", "DELETE", "/status"),
753
+ admit("api.example.com", "GET", "/repos/a/secrets"),
754
+ admit("api.example.com", "GET", "/repos/../admin"),
755
+ admit("api.example.com", "GET", "/repos/a%2fb"),
756
+ admit("api.example.com", "GET", "/repos/a/./secrets"),
757
+ admit("api.example.com", "GET", "/repos/a//secrets"),
758
+ admit("api.example.com", "GET", "/repos/a/%73ecrets"),
759
+ admit("api.example.com", "GET", "/repos/a/b%20c/"),
760
+ admit("api.example.com", "GET", "/repos/a/secrets/"),
761
+ admit("api.example.com", "GET", "/repos/a/SECRETS"),
762
+ admit("api.example.com", "GET", "/STATUS"),
763
+ admit("open.example.com", "PUT", "/anything/at/all"),
764
+ ],
765
+ [
766
+ true, false, true, false, false, false, false, false, false, true, false, false,
767
+ false, true
768
+ ],
769
+ "Ruleset::admits_request must pass only what an http endpoint's rules allow and none \
770
+ denies, refuse a path servers may split or normalize differently (a . segment, an \
771
+ empty one, an encoded unreserved character) while passing an encoded space and a \
772
+ trailing slash, refuse a denied path however a lenient server spells it (a trailing \
773
+ slash, another case) while an allow matches exactly, and pass any request to an \
774
+ endpoint with no rules"
775
+ );
776
+ }
777
+ }