kobako 0.29.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 (291) hide show
  1. checksums.yaml +4 -4
  2. data/.release-please-manifest.json +1 -1
  3. data/CHANGELOG.md +552 -10
  4. data/Cargo.lock +595 -139
  5. data/README.md +126 -564
  6. data/ROADMAP.md +3 -2
  7. data/crates/kobako-runtime/CHANGELOG.md +488 -1
  8. data/crates/kobako-runtime/Cargo.toml +73 -15
  9. data/crates/kobako-runtime/README.md +11 -4
  10. data/crates/kobako-runtime/src/cred.rs +124 -0
  11. data/crates/kobako-runtime/src/dispatch.rs +5 -6
  12. data/crates/kobako-runtime/src/endpoint/buffer.rs +301 -0
  13. data/crates/kobako-runtime/src/endpoint/dispatch.rs +292 -0
  14. data/crates/kobako-runtime/src/endpoint/invoke.rs +181 -0
  15. data/crates/kobako-runtime/src/endpoint.rs +267 -0
  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/fid.rs +82 -0
  20. data/crates/kobako-runtime/src/filesystem/bind/lookup.rs +274 -0
  21. data/crates/kobako-runtime/src/filesystem/bind/walk.rs +248 -0
  22. data/crates/kobako-runtime/src/filesystem/bind.rs +2857 -0
  23. data/crates/kobako-runtime/src/filesystem/overlay/file.rs +89 -0
  24. data/crates/kobako-runtime/src/filesystem/overlay/inode.rs +106 -0
  25. data/crates/kobako-runtime/src/filesystem/overlay/path.rs +263 -0
  26. data/crates/kobako-runtime/src/filesystem/overlay/stack/copy_up.rs +128 -0
  27. data/crates/kobako-runtime/src/filesystem/overlay/stack/dir.rs +238 -0
  28. data/crates/kobako-runtime/src/filesystem/overlay/stack/namei.rs +135 -0
  29. data/crates/kobako-runtime/src/filesystem/overlay/stack/readdir.rs +54 -0
  30. data/crates/kobako-runtime/src/filesystem/overlay/stack.rs +316 -739
  31. data/crates/kobako-runtime/src/filesystem/overlay.rs +2627 -1154
  32. data/crates/kobako-runtime/src/filesystem/pipe.rs +224 -0
  33. data/crates/kobako-runtime/src/filesystem/rdir.rs +84 -0
  34. data/crates/kobako-runtime/src/filesystem/tmpfs/seed.rs +32 -0
  35. data/crates/kobako-runtime/src/filesystem/tmpfs/tmpfile.rs +32 -0
  36. data/crates/kobako-runtime/src/filesystem/tmpfs/whiteout.rs +107 -0
  37. data/crates/kobako-runtime/src/filesystem/tmpfs/xattr.rs +22 -0
  38. data/crates/kobako-runtime/src/filesystem/tmpfs.rs +1997 -0
  39. data/crates/kobako-runtime/src/filesystem/wrap.rs +208 -0
  40. data/crates/kobako-runtime/src/filesystem.rs +25 -388
  41. data/crates/kobako-runtime/src/fork.rs +96 -0
  42. data/crates/kobako-runtime/src/grant.rs +3 -0
  43. data/crates/kobako-runtime/src/hashtable.rs +46 -0
  44. data/crates/kobako-runtime/src/lib.rs +27 -11
  45. data/crates/kobako-runtime/src/limits.rs +195 -0
  46. data/crates/kobako-runtime/src/locking/seqlock.rs +66 -0
  47. data/crates/kobako-runtime/src/locking.rs +228 -0
  48. data/crates/kobako-runtime/src/memcg.rs +383 -0
  49. data/crates/kobako-runtime/src/mount.rs +86 -101
  50. data/crates/kobako-runtime/src/net/backends.rs +43 -0
  51. data/crates/kobako-runtime/src/net/connections.rs +179 -0
  52. data/crates/kobako-runtime/src/net/credential.rs +125 -0
  53. data/crates/kobako-runtime/src/net/egress.rs +160 -0
  54. data/crates/kobako-runtime/src/net/family.rs +181 -0
  55. data/crates/kobako-runtime/src/net/http.rs +2733 -0
  56. data/crates/kobako-runtime/src/net/lookup.rs +285 -0
  57. data/crates/kobako-runtime/src/net/mock.rs +251 -0
  58. data/crates/kobako-runtime/src/net/namespace.rs +1366 -0
  59. data/crates/kobako-runtime/src/net/reactor.rs +531 -0
  60. data/crates/kobako-runtime/src/net/resolv/darwin.rs +275 -0
  61. data/crates/kobako-runtime/src/net/resolv/stub/tests.rs +469 -0
  62. data/crates/kobako-runtime/src/net/resolv/stub.rs +536 -0
  63. data/crates/kobako-runtime/src/net/resolv/windows.rs +248 -0
  64. data/crates/kobako-runtime/src/net/resolv.rs +227 -0
  65. data/crates/kobako-runtime/src/net/socket.rs +870 -0
  66. data/crates/kobako-runtime/src/net/tcp.rs +1588 -0
  67. data/crates/kobako-runtime/src/net/tls.rs +58 -0
  68. data/crates/kobako-runtime/src/net/transport.rs +279 -0
  69. data/crates/kobako-runtime/src/net/udp.rs +1003 -0
  70. data/crates/kobako-runtime/src/net.rs +42 -0
  71. data/crates/kobako-runtime/src/network/builder.rs +177 -0
  72. data/crates/kobako-runtime/src/network/ruleset.rs +777 -0
  73. data/crates/kobako-runtime/src/network.rs +551 -0
  74. data/crates/kobako-runtime/src/policy.rs +16 -0
  75. data/crates/kobako-runtime/src/profile.rs +37 -16
  76. data/crates/kobako-runtime/src/runtime.rs +3 -5
  77. data/crates/kobako-runtime/src/sched.rs +311 -0
  78. data/crates/kobako-runtime/src/security/entry_policy.rs +22 -0
  79. data/crates/kobako-runtime/src/security/hooks.rs +242 -0
  80. data/crates/kobako-runtime/src/security/mount_policy.rs +158 -0
  81. data/crates/kobako-runtime/src/security.rs +601 -0
  82. data/crates/kobako-runtime/src/snapshot.rs +121 -2
  83. data/crates/kobako-runtime/src/vfs/attr.rs +162 -0
  84. data/crates/kobako-runtime/src/vfs/dentry.rs +1466 -0
  85. data/crates/kobako-runtime/src/vfs/file.rs +1911 -0
  86. data/crates/kobako-runtime/src/vfs/inode.rs +425 -0
  87. data/crates/kobako-runtime/src/vfs/kern_path.rs +213 -0
  88. data/crates/kobako-runtime/src/vfs/mount.rs +60 -0
  89. data/crates/kobako-runtime/src/vfs/namei.rs +5837 -0
  90. data/crates/kobako-runtime/src/vfs/namespace.rs +162 -0
  91. data/crates/kobako-runtime/src/vfs/open_files.rs +69 -0
  92. data/crates/kobako-runtime/src/vfs/openat2.rs +116 -0
  93. data/crates/kobako-runtime/src/vfs/path.rs +64 -0
  94. data/crates/kobako-runtime/src/vfs/readdir.rs +163 -0
  95. data/crates/kobako-runtime/src/vfs/stat.rs +293 -0
  96. data/crates/kobako-runtime/src/vfs/super_block.rs +126 -0
  97. data/crates/kobako-runtime/src/vfs/utimes.rs +299 -0
  98. data/crates/kobako-runtime/src/vfs.rs +63 -0
  99. data/crates/kobako-runtime/src/wait.rs +356 -0
  100. data/crates/kobako-transport/CHANGELOG.md +39 -2
  101. data/crates/kobako-transport/Cargo.toml +3 -3
  102. data/crates/kobako-transport/README.md +8 -8
  103. data/crates/kobako-transport/src/abi.rs +78 -72
  104. data/crates/kobako-transport/src/envelope/bytes.rs +49 -30
  105. data/crates/kobako-transport/src/envelope/call.rs +37 -9
  106. data/crates/kobako-transport/src/envelope/compile_reply.rs +2 -2
  107. data/crates/kobako-transport/src/envelope/error_record.rs +24 -3
  108. data/crates/kobako-transport/src/envelope/fault.rs +2 -2
  109. data/crates/kobako-transport/src/envelope/name.rs +99 -0
  110. data/crates/kobako-transport/src/envelope/outcome.rs +11 -11
  111. data/crates/kobako-transport/src/envelope/preamble.rs +34 -31
  112. data/crates/kobako-transport/src/envelope/reply.rs +29 -29
  113. data/crates/kobako-transport/src/envelope/request.rs +2 -2
  114. data/crates/kobako-transport/src/envelope/run.rs +1 -1
  115. data/crates/kobako-transport/src/envelope/unsupported.rs +12 -12
  116. data/crates/kobako-transport/src/envelope.rs +15 -10
  117. data/crates/kobako-wasmtime/CHANGELOG.md +315 -8
  118. data/crates/kobako-wasmtime/Cargo.toml +35 -15
  119. data/crates/kobako-wasmtime/README.md +11 -6
  120. data/crates/kobako-wasmtime/build/preview2.rs +1339 -0
  121. data/crates/kobako-wasmtime/build.rs +16 -0
  122. data/crates/kobako-wasmtime/src/abi.rs +19 -47
  123. data/crates/kobako-wasmtime/src/ambient.rs +33 -19
  124. data/crates/kobako-wasmtime/src/cache.rs +28 -20
  125. data/crates/kobako-wasmtime/src/config.rs +59 -60
  126. data/crates/kobako-wasmtime/src/driver.rs +63 -145
  127. data/crates/kobako-wasmtime/src/exports.rs +147 -32
  128. data/crates/kobako-wasmtime/src/guest.rs +44 -0
  129. data/crates/kobako-wasmtime/src/guest_binary.rs +14 -0
  130. data/crates/kobako-wasmtime/src/imports.rs +48 -18
  131. data/crates/kobako-wasmtime/src/instance_pre.rs +7 -7
  132. data/crates/kobako-wasmtime/src/invocation.rs +93 -51
  133. data/crates/kobako-wasmtime/src/lib.rs +6 -7
  134. data/crates/kobako-wasmtime/src/limiter.rs +52 -211
  135. data/crates/kobako-wasmtime/src/preview1/descriptors.rs +309 -0
  136. data/crates/kobako-wasmtime/src/preview1/differential/mount.rs +70 -57
  137. data/crates/kobako-wasmtime/src/preview1/differential.rs +137 -27
  138. data/crates/kobako-wasmtime/src/preview1/errno.rs +90 -233
  139. data/crates/kobako-wasmtime/src/preview1/fd.rs +1301 -522
  140. data/crates/kobako-wasmtime/src/preview1/memory.rs +126 -150
  141. data/crates/kobako-wasmtime/src/preview1/mount_view/wrap.rs +192 -0
  142. data/crates/kobako-wasmtime/src/preview1/mount_view.rs +1989 -708
  143. data/crates/kobako-wasmtime/src/preview1/path.rs +181 -365
  144. data/crates/kobako-wasmtime/src/preview1/poll.rs +345 -173
  145. data/crates/kobako-wasmtime/src/preview1/sock.rs +10 -25
  146. data/crates/kobako-wasmtime/src/preview1/testsuite-expected.txt +6 -0
  147. data/crates/kobako-wasmtime/src/preview1/testsuite.rs +147 -0
  148. data/crates/kobako-wasmtime/src/preview1.rs +471 -416
  149. data/crates/kobako-wasmtime/src/preview2/abi.rs +227 -0
  150. data/crates/kobako-wasmtime/src/preview2/error.rs +118 -0
  151. data/crates/kobako-wasmtime/src/preview2/filesystem.rs +122 -0
  152. data/crates/kobako-wasmtime/src/preview2/host.rs +3959 -0
  153. data/crates/kobako-wasmtime/src/preview2/http.rs +1503 -0
  154. data/crates/kobako-wasmtime/src/preview2/io.rs +315 -0
  155. data/crates/kobako-wasmtime/src/preview2/sockets.rs +379 -0
  156. data/crates/kobako-wasmtime/src/preview2/table.rs +305 -0
  157. data/crates/kobako-wasmtime/src/preview2.rs +57 -0
  158. data/crates/kobako-wasmtime/src/trap.rs +31 -16
  159. data/crates/kobako-wasmtime/src/wasi.rs +238 -93
  160. data/crates/kobako-wasmtime/wit/deps/cli.wit +233 -0
  161. data/crates/kobako-wasmtime/wit/deps/clocks.wit +162 -0
  162. data/crates/kobako-wasmtime/wit/deps/filesystem.wit +589 -0
  163. data/crates/kobako-wasmtime/wit/deps/http.wit +733 -0
  164. data/crates/kobako-wasmtime/wit/deps/io.wit +299 -0
  165. data/crates/kobako-wasmtime/wit/deps/random.wit +92 -0
  166. data/crates/kobako-wasmtime/wit/deps/sockets.wit +949 -0
  167. data/crates/kobako-wasmtime/witx/typenames.witx +750 -0
  168. data/crates/kobako-wasmtime/witx/wasi_snapshot_preview1.witx +441 -0
  169. data/data/kobako.wasm +0 -0
  170. data/ext/kobako/Cargo.toml +1 -1
  171. data/ext/kobako/src/{runtime/errors.rs → errors.rs} +35 -27
  172. data/ext/kobako/src/escape.rs +98 -0
  173. data/ext/kobako/src/{runtime/filesystem → filesystem}/grants.rs +36 -16
  174. data/ext/kobako/src/filesystem/ruby.rs +689 -0
  175. data/ext/kobako/src/filesystem.rs +217 -0
  176. data/ext/kobako/src/gvl.rs +306 -0
  177. data/ext/kobako/src/lib.rs +64 -3
  178. data/ext/kobako/src/network/mock.rs +187 -0
  179. data/ext/kobako/src/network.rs +591 -0
  180. data/ext/kobako/src/runtime/bridge.rs +31 -30
  181. data/ext/kobako/src/runtime/snapshot.rs +5 -5
  182. data/ext/kobako/src/runtime.rs +221 -138
  183. data/ext/kobako/src/wire.rs +42 -0
  184. data/lib/kobako/catalog/extensions.rb +19 -7
  185. data/lib/kobako/catalog/flags.rb +4 -6
  186. data/lib/kobako/catalog/grants.rb +5 -4
  187. data/lib/kobako/catalog/handles.rb +9 -31
  188. data/lib/kobako/catalog/mount.rb +12 -12
  189. data/lib/kobako/catalog/network.rb +35 -0
  190. data/lib/kobako/catalog/replacements.rb +28 -0
  191. data/lib/kobako/catalog/services.rb +7 -21
  192. data/lib/kobako/catalog/snippets.rb +10 -25
  193. data/lib/kobako/catalog.rb +4 -1
  194. data/lib/kobako/codec/{utils.rb → boundary.rb} +5 -3
  195. data/lib/kobako/codec/decoder.rb +12 -12
  196. data/lib/kobako/codec/ext_types.rb +5 -7
  197. data/lib/kobako/codec/handle_walk.rb +5 -47
  198. data/lib/kobako/codec/nesting.rb +7 -7
  199. data/lib/kobako/codec/value_budget.rb +134 -42
  200. data/lib/kobako/codec.rb +1 -1
  201. data/lib/kobako/context.rb +28 -15
  202. data/lib/kobako/errors.rb +15 -12
  203. data/lib/kobako/extension.rb +3 -2
  204. data/lib/kobako/filesystem.rb +53 -15
  205. data/lib/kobako/handle.rb +2 -2
  206. data/lib/kobako/names.rb +28 -0
  207. data/lib/kobako/network.rb +210 -0
  208. data/lib/kobako/outcome.rb +7 -7
  209. data/lib/kobako/payload/arguments.rb +2 -2
  210. data/lib/kobako/pool.rb +47 -25
  211. data/lib/kobako/runtime.rb +3 -2
  212. data/lib/kobako/sandbox.rb +113 -56
  213. data/lib/kobako/sandbox_options.rb +41 -107
  214. data/lib/kobako/snippet/bytecode.rb +1 -1
  215. data/lib/kobako/snippet/source.rb +1 -1
  216. data/lib/kobako/transport/argument_wrap.rb +64 -0
  217. data/lib/kobako/transport/block_failure.rb +1 -1
  218. data/lib/kobako/transport/dispatcher.rb +10 -10
  219. data/lib/kobako/transport/exposure.rb +28 -17
  220. data/lib/kobako/transport/reflection.rb +28 -11
  221. data/lib/kobako/transport/run.rb +13 -28
  222. data/lib/kobako/transport/yielder.rb +3 -10
  223. data/lib/kobako/transport.rb +1 -0
  224. data/lib/kobako/version.rb +1 -1
  225. data/lib/kobako.rb +38 -0
  226. data/release-please-config.json +16 -0
  227. data/sig/core/thread.rbs +6 -0
  228. data/sig/kobako/catalog/extensions.rbs +5 -3
  229. data/sig/kobako/catalog/grants.rbs +7 -4
  230. data/sig/kobako/catalog/handles.rbs +2 -4
  231. data/sig/kobako/catalog/mount.rbs +3 -5
  232. data/sig/kobako/catalog/network.rbs +20 -0
  233. data/sig/kobako/catalog/replacements.rbs +14 -0
  234. data/sig/kobako/catalog/services.rbs +1 -5
  235. data/sig/kobako/catalog/snippets.rbs +3 -5
  236. data/sig/kobako/catalog.rbs +1 -1
  237. data/sig/kobako/codec/boundary.rbs +9 -0
  238. data/sig/kobako/codec/decoder.rbs +1 -1
  239. data/sig/kobako/codec/handle_walk.rbs +0 -6
  240. data/sig/kobako/codec/nesting.rbs +2 -2
  241. data/sig/kobako/codec/value_budget.rbs +48 -5
  242. data/sig/kobako/codec.rbs +1 -2
  243. data/sig/kobako/context.rbs +4 -2
  244. data/sig/kobako/errors.rbs +4 -4
  245. data/sig/kobako/filesystem.rbs +38 -15
  246. data/sig/kobako/guest_yielder.rbs +1 -1
  247. data/sig/kobako/network.rbs +115 -0
  248. data/sig/kobako/outcome.rbs +1 -1
  249. data/sig/kobako/payload/arguments.rbs +1 -1
  250. data/sig/kobako/pool.rbs +8 -4
  251. data/sig/kobako/runtime.rbs +32 -3
  252. data/sig/kobako/sandbox.rbs +22 -7
  253. data/sig/kobako/sandbox_options.rbs +29 -38
  254. data/sig/kobako/transport/argument_wrap.rbs +15 -0
  255. data/sig/kobako/transport/dispatcher.rbs +2 -2
  256. data/sig/kobako/transport/error.rbs +1 -1
  257. data/sig/kobako/transport/exposure.rbs +3 -5
  258. data/sig/kobako/transport/reflection.rbs +12 -2
  259. data/sig/kobako/transport/run.rbs +3 -5
  260. data/sig/kobako/transport/yielder.rbs +0 -3
  261. data/sig/kobako/transport.rbs +2 -2
  262. data/sig/kobako.rbs +13 -0
  263. metadata +131 -34
  264. data/crates/kobako-runtime/src/filesystem/directory/spelling.rs +0 -194
  265. data/crates/kobako-runtime/src/filesystem/directory.rs +0 -1082
  266. data/crates/kobako-runtime/src/filesystem/memory.rs +0 -1100
  267. data/crates/kobako-runtime/src/filesystem/overlay/exclusive.rs +0 -88
  268. data/crates/kobako-runtime/src/filesystem/path.rs +0 -60
  269. data/crates/kobako-runtime/src/filesystem/temporary.rs +0 -167
  270. data/crates/kobako-wasmtime/src/capture.rs +0 -96
  271. data/crates/kobako-wasmtime/src/descriptors.rs +0 -167
  272. data/crates/kobako-wasmtime/src/dispatch.rs +0 -125
  273. data/crates/kobako-wasmtime/src/guest_mem.rs +0 -271
  274. data/crates/kobako-wasmtime/src/io.rs +0 -89
  275. data/crates/kobako-wasmtime/src/preview1/args.rs +0 -60
  276. data/crates/kobako-wasmtime/src/preview1/beneath.rs +0 -188
  277. data/crates/kobako-wasmtime/tests/compile_posture.rs +0 -43
  278. data/crates/kobako-wasmtime/tests/guest_file.rs +0 -1054
  279. data/crates/kobako-wasmtime/tests/preamble_flags.rs +0 -70
  280. data/crates/kobako-wasmtime/tests/snippet_compile.rs +0 -95
  281. data/crates/kobako-wasmtime/tests/support/mod.rs +0 -30
  282. data/crates/kobako-wasmtime/tests/unanswered_call.rs +0 -86
  283. data/crates/kobako-wasmtime/tests/unsupported_call.rs +0 -51
  284. data/ext/kobako/src/runtime/escape.rs +0 -53
  285. data/ext/kobako/src/runtime/filesystem/ruby.rs +0 -400
  286. data/ext/kobako/src/runtime/filesystem.rs +0 -236
  287. data/ext/kobako/src/runtime/gvl.rs +0 -112
  288. data/lib/kobako/constant_name.rb +0 -8
  289. data/sig/kobako/codec/utils.rbs +0 -9
  290. data/sig/kobako/constant_name.rbs +0 -3
  291. /data/ext/kobako/src/{runtime/pinned_value.rs → pinned_value.rs} +0 -0
@@ -2,86 +2,86 @@
2
2
  //! path, the files a Filesystem holds, and the refusals the runtime
3
3
  //! answers before the Filesystem is asked.
4
4
 
5
+ mod wrap;
6
+
5
7
  use std::sync::atomic::{AtomicUsize, Ordering};
6
- use std::sync::Arc;
8
+ use std::sync::{Arc, Mutex, Weak};
9
+ use std::time::{SystemTime, UNIX_EPOCH};
7
10
 
8
- use kobako_runtime::filesystem::Access;
11
+ use kobako_runtime::filesystem::Bind;
12
+ use kobako_runtime::filesystem::Filesystem;
9
13
  use kobako_runtime::filesystem::{
10
- DirEntry, Directory, File, Filesystem, FilesystemError, Hold, Memory, Metadata, OpenOptions,
11
- Overlay, Rename, Temporary,
14
+ FileOperations, FileSystemType, FileType, InodeOperations, Kiocb, Kstat, Lookup, OpenHow,
15
+ Overlay, RenameFlag, Tmpfs,
12
16
  };
13
17
  use kobako_runtime::grant::Grant;
14
- use kobako_runtime::mount::{Mount, Policy};
18
+ use kobako_runtime::mount::{Access, Mount, MountRequest};
19
+ use kobako_runtime::policy::Policy;
15
20
  use kobako_runtime::profile::Profile;
21
+ use kobako_runtime::security::{prepare_creds, SecurityOperations, SecurityPath};
22
+ use kobako_runtime::vfs::{self, Dentry, Inode, Path, PATH_MAX};
23
+ use kobako_runtime::Errno;
16
24
  use wasmtime::{Instance, Module, Store};
17
25
 
18
- use crate::cache::shared_engine;
26
+ use crate::cache::load_engine;
19
27
  use crate::config::Config;
20
28
  use crate::imports;
21
29
  use crate::invocation::Invocation;
22
30
  use crate::trap::NO_TIMEOUT_EPOCH_DELTA;
23
31
  use crate::wasi::Wasi;
24
-
25
- /// The answer of a test Filesystem holding no links.
26
- macro_rules! holds_no_links {
27
- () => {
28
- fn symlink_metadata(&self, path: &str) -> Result<Metadata, FilesystemError> {
29
- self.metadata(path)
30
- }
31
-
32
- fn canonicalize_beneath(&self, _base: &str, path: &str) -> Result<String, FilesystemError> {
33
- Ok(path.to_string())
34
- }
35
-
36
- fn for_policy(&self) -> Option<Arc<dyn Filesystem>> {
37
- None
38
- }
39
- };
40
- }
41
-
42
- /// The answer of a test Filesystem matching names byte for byte.
43
- macro_rules! matches_names_exactly {
44
- () => {
45
- fn stored_path(&self, path: &str) -> Result<String, FilesystemError> {
46
- Ok(path.to_string())
47
- }
48
- };
49
- }
50
-
51
- /// The answer of a test Filesystem whose identities never repeat.
52
- macro_rules! never_repeats_identities {
53
- () => {
54
- fn hold_directory(&self, _path: &str) -> Result<Option<Hold>, FilesystemError> {
55
- Ok(None)
56
- }
57
- };
32
+ use wrap::{Hook, Wrap};
33
+
34
+ /// The root of `filesystem` as the host reaches it through the VFS, a
35
+ /// writer of its own beside the guest.
36
+ fn host<F: FileSystemType>(filesystem: &Arc<F>) -> Path {
37
+ let mount = Mount::new(
38
+ "/data",
39
+ Filesystem::new(filesystem.clone()).expect("the instance must stand"),
40
+ Access::ReadWrite,
41
+ )
42
+ .expect("/data is a guest path");
43
+ Path::root(mount.mnt())
58
44
  }
59
45
 
60
- /// The answer of a test Filesystem every Invocation shares.
61
- macro_rules! is_shared {
62
- () => {
63
- fn for_invocation(&self) -> Option<Arc<dyn Filesystem>> {
64
- None
65
- }
66
- };
46
+ /// The names `filesystem`'s root holds, as the host lists them.
47
+ fn host_entries<F: FileSystemType>(filesystem: &Arc<F>) -> Result<Vec<String>, Errno> {
48
+ let mount = Mount::new(
49
+ "/data",
50
+ Filesystem::new(filesystem.clone()).expect("the instance must stand"),
51
+ Access::ReadWrite,
52
+ )
53
+ .expect("/data is a guest path");
54
+ let mut root = vfs::File::root(mount.mnt(), &prepare_creds(&[], None))?;
55
+ let mut names = Vec::new();
56
+ root.llseek(2, vfs::Whence::Set)?;
57
+ root.iterate_dir(&mut vfs::DirContext::new(0, &mut |emit| {
58
+ names.push(emit.name.to_string());
59
+ true
60
+ }))?;
61
+ Ok(names)
67
62
  }
68
63
 
69
64
  const ERRNO_ACCES: i32 = 2;
70
65
  const ERRNO_BADF: i32 = 8;
71
66
  const ERRNO_BUSY: i32 = 10;
72
- const ERRNO_FBIG: i32 = 22;
67
+ const ERRNO_MFILE: i32 = 33;
73
68
  const ERRNO_INVAL: i32 = 28;
74
69
  const ERRNO_IO: i32 = 29;
75
70
  const ERRNO_ISDIR: i32 = 31;
71
+ #[cfg(unix)]
76
72
  const ERRNO_LOOP: i32 = 32;
77
73
  const ERRNO_NOENT: i32 = 44;
74
+ const ERRNO_NOMEM: i32 = 48;
75
+ const ERRNO_OVERFLOW: i32 = 61;
78
76
  const ERRNO_NOTDIR: i32 = 54;
77
+ const ERRNO_NOTEMPTY: i32 = 55;
78
+ const ERRNO_NOSPC: i32 = 51;
79
79
  const ERRNO_NOTSUP: i32 = 58;
80
80
  const ERRNO_ROFS: i32 = 69;
81
81
  const ERRNO_XDEV: i32 = 75;
82
82
  const ERRNO_NOTCAPABLE: i32 = 76;
83
83
 
84
- /// Memory holds an `iovec` at 64 over 512..576, a `ciovec` at 80 over
84
+ /// Tmpfs holds an `iovec` at 64 over 512..576, a `ciovec` at 80 over
85
85
  /// "hello" at 600, the paths `file.txt` at 700 and `../file.txt` at 720,
86
86
  /// and from 740 the paths the resolution rules turn on. An opened
87
87
  /// descriptor lands at 128, a count at 132, a listing's count at 136, a
@@ -92,7 +92,9 @@ const PROBE_WAT: &str = r#"
92
92
  (import "wasi_snapshot_preview1" "fd_prestat_dir_name" (func $prestat_name (param i32 i32 i32) (result i32)))
93
93
  (import "wasi_snapshot_preview1" "path_open" (func $open (param i32 i32 i32 i32 i32 i64 i64 i32 i32) (result i32)))
94
94
  (import "wasi_snapshot_preview1" "path_filestat_get" (func $stat (param i32 i32 i32 i32 i32) (result i32)))
95
+ (import "wasi_snapshot_preview1" "fd_filestat_get" (func $fstat (param i32 i32) (result i32)))
95
96
  (import "wasi_snapshot_preview1" "fd_read" (func $read (param i32 i32 i32 i32) (result i32)))
97
+ (import "wasi_snapshot_preview1" "fd_close" (func $close (param i32) (result i32)))
96
98
  (import "wasi_snapshot_preview1" "fd_write" (func $write (param i32 i32 i32 i32) (result i32)))
97
99
  (import "wasi_snapshot_preview1" "path_remove_directory" (func $rmdir (param i32 i32 i32) (result i32)))
98
100
  (import "wasi_snapshot_preview1" "path_rename" (func $rename (param i32 i32 i32 i32 i32 i32) (result i32)))
@@ -108,6 +110,9 @@ const PROBE_WAT: &str = r#"
108
110
  (import "wasi_snapshot_preview1" "fd_fdstat_get" (func $fdstat (param i32 i32) (result i32)))
109
111
  (import "wasi_snapshot_preview1" "fd_fdstat_set_flags" (func $set_flags (param i32 i32) (result i32)))
110
112
  (import "wasi_snapshot_preview1" "poll_oneoff" (func $poll (param i32 i32 i32 i32) (result i32)))
113
+ (import "wasi_snapshot_preview1" "fd_sync" (func $sync (param i32) (result i32)))
114
+ (import "wasi_snapshot_preview1" "fd_filestat_set_times" (func $set_times (param i32 i64 i64 i32) (result i32)))
115
+ (import "wasi_snapshot_preview1" "sock_shutdown" (func $shutdown (param i32 i32) (result i32)))
111
116
  (memory (export "memory") 1)
112
117
  (data (i32.const 740) ".")
113
118
  (data (i32.const 760) "missing/../file.txt")
@@ -137,6 +142,12 @@ const PROBE_WAT: &str = r#"
137
142
  (data (i32.const 1120) "dir/up")
138
143
  (data (i32.const 1130) "nowhere")
139
144
  (data (i32.const 1150) "pub/x")
145
+ (data (i32.const 1160) "in/inner/../../sub/y")
146
+ (data (i32.const 1184) "loop")
147
+ (data (i32.const 1190) "dir/sub")
148
+ (data (i32.const 1400) "dir/in/y")
149
+ (data (i32.const 1420) "dir/sub/y")
150
+ (data (i32.const 1440) "\ff")
140
151
  ;; An iovec naming 16 bytes past the one page of memory.
141
152
  (data (i32.const 1140) "\00\00\02\00\10\00\00\00")
142
153
  (data (i32.const 64) "\00\02\00\00\40\00\00\00")
@@ -159,6 +170,22 @@ const PROBE_WAT: &str = r#"
159
170
  (if (local.get $errno) (then (return (local.get $errno))))
160
171
  (call $read (i32.load (i32.const 128)) (i32.const 64) (i32.const 1) (i32.const 132)))
161
172
 
173
+ ;; Open the path read-only and close it again.
174
+ (func (export "open_close") (param $path i32) (param $len i32) (result i32)
175
+ (local $errno i32)
176
+ (local.set $errno (call $open (i32.const 3) (i32.const 0) (local.get $path) (local.get $len)
177
+ (i32.const 0) (i64.const 2) (i64.const 0) (i32.const 0) (i32.const 128)))
178
+ (if (local.get $errno) (then (return (local.get $errno))))
179
+ (call $close (i32.load (i32.const 128))))
180
+
181
+ ;; Open the path asking no right, with the given oflags, and read from it.
182
+ (func (export "read_unasked") (param $path i32) (param $len i32) (param $oflags i32) (result i32)
183
+ (local $errno i32)
184
+ (local.set $errno (call $open (i32.const 3) (i32.const 0) (local.get $path) (local.get $len)
185
+ (local.get $oflags) (i64.const 0) (i64.const 0) (i32.const 0) (i32.const 128)))
186
+ (if (local.get $errno) (then (return (local.get $errno))))
187
+ (call $read (i32.load (i32.const 128)) (i32.const 64) (i32.const 1) (i32.const 132)))
188
+
162
189
  ;; Open the path with read rights only, asking to truncate it.
163
190
  (func (export "truncate_file") (param $path i32) (param $len i32) (result i32)
164
191
  (call $open (i32.const 3) (i32.const 0) (local.get $path) (local.get $len)
@@ -181,6 +208,14 @@ const PROBE_WAT: &str = r#"
181
208
  (func (export "stat_flagged") (param $path i32) (param $len i32) (param $flags i32) (result i32)
182
209
  (call $stat (i32.const 3) (local.get $flags) (local.get $path) (local.get $len) (i32.const 384)))
183
210
 
211
+ ;; Open the path read-only and stat what is open into 384.
212
+ (func (export "stat_opened") (param $path i32) (param $len i32) (result i32)
213
+ (local $errno i32)
214
+ (local.set $errno (call $open (i32.const 3) (i32.const 0) (local.get $path) (local.get $len)
215
+ (i32.const 0) (i64.const 2097154) (i64.const 0) (i32.const 0) (i32.const 128)))
216
+ (if (local.get $errno) (then (return (local.get $errno))))
217
+ (call $fstat (i32.load (i32.const 128)) (i32.const 384)))
218
+
184
219
  ;; Change the root `.` at 740.
185
220
  (func (export "remove_root") (result i32)
186
221
  (call $rmdir (i32.const 3) (i32.const 740) (i32.const 1)))
@@ -204,9 +239,6 @@ const PROBE_WAT: &str = r#"
204
239
  (if (local.get $errno) (then (return (local.get $errno))))
205
240
  (call $allocate (i32.load (i32.const 128)) (i64.const 0) (i64.const 100)))
206
241
 
207
- ;; Rename `file.txt` to `new.txt`.
208
- (func (export "rename_to_new") (result i32)
209
- (call $rename (i32.const 3) (i32.const 700) (i32.const 8) (i32.const 3) (i32.const 840) (i32.const 7)))
210
242
  ;; Rename `file.txt` onto `file.txt/`, its own path as a directory.
211
243
  (func (export "rename_onto_itself_as_directory") (result i32)
212
244
  (call $rename (i32.const 3) (i32.const 700) (i32.const 8) (i32.const 3) (i32.const 800) (i32.const 9)))
@@ -293,9 +325,39 @@ const PROBE_WAT: &str = r#"
293
325
  (func (export "dir_fdstat") (result i32)
294
326
  (local $errno i32)
295
327
  (local.set $errno (call $open (i32.const 3) (i32.const 0) (i32.const 930) (i32.const 3)
296
- (i32.const 2) (i64.const 0) (i64.const 2) (i32.const 0) (i32.const 128)))
328
+ (i32.const 2) (i64.const 0x4002) (i64.const 2) (i32.const 0) (i32.const 128)))
297
329
  (if (local.get $errno) (then (return (local.get $errno))))
298
330
  (call $fdstat (i32.load (i32.const 128)) (i32.const 384)))
331
+ ;; Open `dir` as a directory with `rights`, then make call `$call` of it:
332
+ ;; list, sync, advise, set its flags, size, or times, wait on it with its
333
+ ;; event at 1264, stat it, stat `inner` from it, or read its fdstat into
334
+ ;; 384.
335
+ (func (export "dir_with") (param $rights i64) (param $call i32) (result i32)
336
+ (local $errno i32)
337
+ (local $fd i32)
338
+ (local.set $errno (call $open (i32.const 3) (i32.const 0) (i32.const 930) (i32.const 3)
339
+ (i32.const 2) (local.get $rights) (i64.const 0) (i32.const 0) (i32.const 128)))
340
+ (if (local.get $errno) (then (return (local.get $errno))))
341
+ (local.set $fd (i32.load (i32.const 128)))
342
+ (if (i32.eq (local.get $call) (i32.const 0)) (then (return
343
+ (call $readdir (local.get $fd) (i32.const 2048) (i32.const 64) (i64.const 0) (i32.const 136)))))
344
+ (if (i32.eq (local.get $call) (i32.const 1)) (then (return (call $sync (local.get $fd)))))
345
+ (if (i32.eq (local.get $call) (i32.const 2)) (then (return
346
+ (call $advise (local.get $fd) (i64.const 0) (i64.const 0) (i32.const 0)))))
347
+ (if (i32.eq (local.get $call) (i32.const 3)) (then (return (call $set_flags (local.get $fd) (i32.const 0)))))
348
+ (if (i32.eq (local.get $call) (i32.const 4)) (then (return (call $set_size (local.get $fd) (i64.const 0)))))
349
+ (if (i32.eq (local.get $call) (i32.const 5)) (then (return
350
+ (call $set_times (local.get $fd) (i64.const 0) (i64.const 0) (i32.const 2)))))
351
+ (if (i32.eq (local.get $call) (i32.const 7)) (then (return (call $fstat (local.get $fd) (i32.const 384)))))
352
+ (if (i32.eq (local.get $call) (i32.const 8)) (then (return
353
+ (call $stat (local.get $fd) (i32.const 0) (i32.const 960) (i32.const 5) (i32.const 384)))))
354
+ (if (i32.eq (local.get $call) (i32.const 9)) (then (return (call $fdstat (local.get $fd) (i32.const 384)))))
355
+ (if (i32.eq (local.get $call) (i32.const 10)) (then (return (call $shutdown (local.get $fd) (i32.const 3)))))
356
+ (i32.store8 (i32.const 1208) (i32.const 1))
357
+ (i32.store (i32.const 1216) (local.get $fd))
358
+ (local.set $errno (call $poll (i32.const 1200) (i32.const 1264) (i32.const 1) (i32.const 1296)))
359
+ (if (local.get $errno) (then (return (local.get $errno))))
360
+ (i32.load16_u (i32.const 1272)))
299
361
  ;; Size `file.txt` to `offset` bytes.
300
362
  (func (export "size_at") (param $offset i64) (result i32)
301
363
  (local $errno i32)
@@ -345,7 +407,7 @@ const PROBE_WAT: &str = r#"
345
407
  (func (export "open_beneath_dir") (param $path i32) (param $len i32) (result i32)
346
408
  (local $errno i32)
347
409
  (local.set $errno (call $open (i32.const 3) (i32.const 0) (i32.const 930) (i32.const 3)
348
- (i32.const 2) (i64.const 0) (i64.const 2) (i32.const 0) (i32.const 128)))
410
+ (i32.const 2) (i64.const 0x4002) (i64.const 2) (i32.const 0) (i32.const 128)))
349
411
  (if (local.get $errno) (then (return (local.get $errno))))
350
412
  (call $open (i32.load (i32.const 128)) (i32.const 0) (local.get $path) (local.get $len)
351
413
  (i32.const 0) (i64.const 2) (i64.const 0) (i32.const 0) (i32.const 132)))
@@ -372,10 +434,20 @@ const PROBE_WAT: &str = r#"
372
434
  ;; Open `dir` as a directory into 128.
373
435
  (func $open_dir (export "open_dir") (result i32)
374
436
  (call $open (i32.const 3) (i32.const 0) (i32.const 930) (i32.const 3)
375
- (i32.const 2) (i64.const 0) (i64.const 2) (i32.const 0) (i32.const 128)))
437
+ (i32.const 2) (i64.const 0x4002) (i64.const 2) (i32.const 0) (i32.const 128)))
438
+ ;; Stat the directory opened into 128 itself.
439
+ (func (export "fstat_dir") (result i32)
440
+ (call $fstat (i32.load (i32.const 128)) (i32.const 384)))
441
+ ;; List the directory opened into 128 from its start.
442
+ (func (export "list_dir") (result i32)
443
+ (call $readdir (i32.load (i32.const 128)) (i32.const 2048) (i32.const 256) (i64.const 0) (i32.const 136)))
376
444
  ;; Stat `inner` beneath the directory opened into 128.
377
445
  (func (export "stat_inner") (result i32)
378
- (call $stat (i32.load (i32.const 128)) (i32.const 0) (i32.const 960) (i32.const 5) (i32.const 384))))
446
+ (call $stat (i32.load (i32.const 128)) (i32.const 0) (i32.const 960) (i32.const 5) (i32.const 384)))
447
+ ;; Open `inner` for reading beneath the directory opened into 128.
448
+ (func (export "open_inner") (result i32)
449
+ (call $open (i32.load (i32.const 128)) (i32.const 0) (i32.const 960) (i32.const 5)
450
+ (i32.const 0) (i64.const 2) (i64.const 0) (i32.const 0) (i32.const 132))))
379
451
  "#;
380
452
 
381
453
  const FILE: (i32, i32) = (700, 8);
@@ -385,6 +457,7 @@ const THROUGH_MISSING: (i32, i32) = (760, 19);
385
457
  const OUT_OF_FILE: (i32, i32) = (780, 11);
386
458
  const FILE_AS_DIRECTORY: (i32, i32) = (800, 9);
387
459
  const NEW_AS_DIRECTORY: (i32, i32) = (820, 8);
460
+ #[cfg(unix)]
388
461
  const THROUGH_FILE: (i32, i32) = (860, 12);
389
462
  const DIR_DOT: (i32, i32) = (880, 5);
390
463
  const DIR_DOT_DOT: (i32, i32) = (890, 6);
@@ -392,29 +465,38 @@ const BENEATH_FILE: (i32, i32) = (900, 10);
392
465
  const MOVED: (i32, i32) = (920, 5);
393
466
  const DIR: (i32, i32) = (930, 3);
394
467
  const MISSING_DOT: (i32, i32) = (940, 9);
468
+ #[cfg(unix)]
395
469
  const LINK_DOT: (i32, i32) = (970, 10);
470
+ #[cfg(unix)]
396
471
  const OUT_OF_LINK: (i32, i32) = (990, 20);
397
472
  const HOLDING_NUL: (i32, i32) = (1010, 9);
473
+ const NOT_UTF8: (i32, i32) = (1440, 1);
398
474
  const DIR_FILE: (i32, i32) = (1030, 12);
475
+ #[cfg(unix)]
399
476
  const DIR_AS_DIRECTORY: (i32, i32) = (1050, 4);
477
+ #[cfg(unix)]
400
478
  const GONE_AS_DIRECTORY: (i32, i32) = (1060, 5);
401
- const ERRNO_OVERFLOW: i32 = 61;
402
479
  const ERRNO_EXIST: i32 = 20;
403
480
  const OFLAGS_EXCL: i32 = 1 << 2;
404
481
 
405
- /// The default `OpenOptions` with `set` applied.
406
- fn build_options(set: impl FnOnce(&mut OpenOptions)) -> OpenOptions {
407
- let mut options = OpenOptions::default();
408
- set(&mut options);
409
- options
482
+ /// The default `OpenHow` with `set` applied.
483
+ fn build_how(set: impl FnOnce(&mut OpenHow)) -> OpenHow {
484
+ let mut how = OpenHow::default();
485
+ set(&mut how);
486
+ how
410
487
  }
411
488
 
412
489
  fn grant(
413
- filesystem: Arc<dyn Filesystem>,
490
+ filesystem: Arc<dyn FileSystemType>,
414
491
  access: Access,
415
- policy: Option<Arc<dyn Policy>>,
492
+ policy: Option<Arc<dyn for<'a> Policy<MountRequest<'a>>>>,
416
493
  ) -> Grant {
417
- let mount = Mount::new("/data", filesystem, access).expect("/data is a guest path");
494
+ let mount = Mount::new(
495
+ "/data",
496
+ Filesystem::new(filesystem).expect("the instance must stand"),
497
+ access,
498
+ )
499
+ .expect("/data is a guest path");
418
500
  Grant::Mount(match policy {
419
501
  Some(policy) => mount.with_policy(policy),
420
502
  None => mount,
@@ -429,18 +511,49 @@ struct Guest {
429
511
 
430
512
  impl Guest {
431
513
  fn new(grants: &[Grant]) -> Self {
432
- let engine = shared_engine().expect("shared engine must be constructible");
433
- let config = Config {
434
- timeout: None,
435
- setup_timeout: None,
436
- memory_limit: None,
437
- stdout_limit: None,
438
- stderr_limit: None,
439
- open_file_limit: None,
440
- profile: Profile::Hermetic,
441
- };
442
- let wasi = Wasi::for_invocation(&config, &[], grants).expect("WASI context must build");
443
- let mut store = Store::new(engine, Invocation::new(None, wasi));
514
+ Self::with_open_file_limit(None, grants)
515
+ }
516
+
517
+ /// A guest holding at most `open_file_limit` descriptors at once.
518
+ fn with_open_file_limit(open_file_limit: Option<usize>, grants: &[Grant]) -> Self {
519
+ Self::build(open_file_limit, None, Profile::Hermetic, Vec::new(), grants)
520
+ }
521
+
522
+ /// A guest allotted `memory_limit` bytes.
523
+ fn with_memory_limit(memory_limit: usize, grants: &[Grant]) -> Self {
524
+ Self::build(
525
+ None,
526
+ Some(memory_limit),
527
+ Profile::Hermetic,
528
+ Vec::new(),
529
+ grants,
530
+ )
531
+ }
532
+
533
+ /// A guest on `profile`.
534
+ fn for_profile(profile: Profile, grants: &[Grant]) -> Self {
535
+ Self::build(None, None, profile, Vec::new(), grants)
536
+ }
537
+
538
+ /// A guest whose Driver was built with `security`.
539
+ fn with_security(security: Vec<Arc<dyn SecurityOperations>>, grants: &[Grant]) -> Self {
540
+ Self::build(None, None, Profile::Hermetic, security, grants)
541
+ }
542
+
543
+ fn build(
544
+ open_file_limit: Option<usize>,
545
+ memory_limit: Option<usize>,
546
+ profile: Profile,
547
+ security: Vec<Arc<dyn SecurityOperations>>,
548
+ grants: &[Grant],
549
+ ) -> Self {
550
+ let engine = load_engine().expect("shared engine must be constructible");
551
+ let mut config = Config::for_profile(profile);
552
+ config.limits.memory_limit = memory_limit;
553
+ config.limits.open_file_limit = open_file_limit;
554
+ config.security = security;
555
+ let wasi = Wasi::for_invocation(&config, grants).expect("WASI context must build");
556
+ let mut store = Store::new(engine, Invocation::new(wasi));
444
557
  store.set_epoch_deadline(NO_TIMEOUT_EPOCH_DELTA);
445
558
  let module = Module::new(engine, PROBE_WAT).expect("probe module must compile");
446
559
  let instance = imports::linker()
@@ -494,6 +607,15 @@ impl Guest {
494
607
  .expect("probe call must not trap")
495
608
  }
496
609
 
610
+ /// Open `dir` with `rights` and make call `call` of it.
611
+ fn call_dir_with(&mut self, rights: i64, call: i32) -> i32 {
612
+ self.instance
613
+ .get_typed_func::<(i64, i32), i32>(&mut self.store, "dir_with")
614
+ .expect("probe export must resolve")
615
+ .call(&mut self.store, (rights, call))
616
+ .expect("probe call must not trap")
617
+ }
618
+
497
619
  /// Call an export that takes no path.
498
620
  fn call_bare(&mut self, name: &str) -> i32 {
499
621
  self.instance
@@ -503,14 +625,26 @@ impl Guest {
503
625
  .expect("probe call must not trap")
504
626
  }
505
627
 
628
+ /// Stat `file.txt`, without following a link, into 384.
629
+ fn call_flagged_stat(&mut self) -> i32 {
630
+ self.instance
631
+ .get_typed_func::<(i32, i32, i32), i32>(&mut self.store, "stat_flagged")
632
+ .expect("probe export must resolve")
633
+ .call(&mut self.store, (FILE.0, FILE.1, 0))
634
+ .expect("probe call must not trap")
635
+ }
636
+
506
637
  /// The names a listing from `cookie` into `len` bytes holds whole.
507
- fn list(&mut self, cookie: u64, len: i32) -> Vec<String> {
508
- let errno = self
509
- .instance
638
+ fn call_list(&mut self, cookie: u64, len: i32) -> i32 {
639
+ self.instance
510
640
  .get_typed_func::<(i64, i32), i32>(&mut self.store, "list")
511
641
  .expect("probe export must resolve")
512
642
  .call(&mut self.store, (cookie as i64, len))
513
- .expect("probe call must not trap");
643
+ .expect("probe call must not trap")
644
+ }
645
+
646
+ fn list(&mut self, cookie: u64, len: i32) -> Vec<String> {
647
+ let errno = self.call_list(cookie, len);
514
648
  assert_eq!(errno, 0, "the listing must succeed");
515
649
  let memory = self
516
650
  .instance
@@ -532,6 +666,36 @@ impl Guest {
532
666
  names
533
667
  }
534
668
 
669
+ /// What `path_filestat_get` answers for `path` with `flags`.
670
+ fn stat_flagged(&mut self, path: (i32, i32), flags: i32) -> i32 {
671
+ self.instance
672
+ .get_typed_func::<(i32, i32, i32), i32>(&mut self.store, "stat_flagged")
673
+ .expect("probe export must resolve")
674
+ .call(&mut self.store, (path.0, path.1, flags))
675
+ .expect("probe call must not trap")
676
+ }
677
+
678
+ /// The `u64` the last stat placed at `field` of its `filestat`.
679
+ fn stat_field(&mut self, field: usize) -> u64 {
680
+ let memory = self
681
+ .instance
682
+ .get_memory(&mut self.store, "memory")
683
+ .expect("probe exports its memory");
684
+ let at = 384 + field;
685
+ u64::from_le_bytes(memory.data(&self.store)[at..at + 8].try_into().unwrap())
686
+ }
687
+
688
+ /// The `atim`, `mtim`, and `ctim` the last stat placed at 384.
689
+ fn stat_times(&mut self) -> [u64; 3] {
690
+ [40, 48, 56].map(|field| self.stat_field(field))
691
+ }
692
+
693
+ /// The times `stat_flagged` answers for `path`.
694
+ fn times_of_path(&mut self, path: (i32, i32)) -> [u64; 3] {
695
+ assert_eq!(self.stat_flagged(path, 0), 0, "the stat must succeed");
696
+ self.stat_times()
697
+ }
698
+
535
699
  /// The bytes the last read placed at 512.
536
700
  fn read_back(&mut self) -> Vec<u8> {
537
701
  let memory = self
@@ -544,81 +708,101 @@ impl Guest {
544
708
  }
545
709
  }
546
710
 
547
- fn contents(filesystem: &dyn Filesystem, path: &str) -> Option<Vec<u8>> {
548
- let mut file = filesystem
549
- .open(path, &build_options(|options| options.read = true))
550
- .ok()?;
711
+ /// What `do_file_open` takes for an open `how` asks.
712
+ fn flags_of(how: &OpenHow) -> vfs::OpenFlags {
713
+ vfs::build_open_flags(how).expect("the flags must mean an open")
714
+ }
715
+
716
+ fn contents(root: &Path, path: &str) -> Option<Vec<u8>> {
717
+ let mut how = OpenHow::default();
718
+ how.read = true;
719
+ let Ok(mut file) = vfs::do_file_open(&prepare_creds(&[], None), root, path, &flags_of(&how))
720
+ else {
721
+ return None;
722
+ };
551
723
  let mut buf = vec![0; 64];
552
- let read = file.read_at(&mut buf, 0).ok()?;
724
+ let read = file.pread(&mut buf, 0).ok()?;
553
725
  buf.truncate(read);
554
726
  Some(buf)
555
727
  }
556
728
 
557
729
  /// Make an empty file at `path`.
558
- fn overwrite(filesystem: &dyn Filesystem, path: &str) {
559
- filesystem
560
- .open(
561
- path,
562
- &build_options(|options| (options.write, options.create) = (true, true)),
563
- )
564
- .expect("the file must be made");
730
+ fn overwrite(root: &Path, path: &str) {
731
+ let mut how = OpenHow::default();
732
+ (how.write, how.create) = (true, true);
733
+ assert!(
734
+ vfs::do_file_open(&prepare_creds(&[], None), root, path, &flags_of(&how)).is_ok(),
735
+ "the file must be made"
736
+ );
565
737
  }
566
738
 
567
739
  struct Refuses(&'static str);
568
740
 
569
- impl Policy for Refuses {
570
- fn allows(&self, path: &str, _access: Access) -> bool {
571
- path != self.0
741
+ impl Policy<MountRequest<'_>> for Refuses {
742
+ fn allows(&self, request: &MountRequest<'_>) -> bool {
743
+ request.path != self.0
572
744
  }
573
745
  }
574
746
 
575
747
  struct AllowsAll;
576
748
 
577
- impl Policy for AllowsAll {
578
- fn allows(&self, _path: &str, _access: Access) -> bool {
749
+ impl Policy<MountRequest<'_>> for AllowsAll {
750
+ fn allows(&self, _request: &MountRequest<'_>) -> bool {
579
751
  true
580
752
  }
581
753
  }
582
754
 
583
- /// A Memory storing every name in upper case while it reaches each by
584
- /// any case, as a host that folds case does.
585
- struct StoresUpperCase(Memory);
586
-
587
- impl Filesystem for StoresUpperCase {
588
- holds_no_links!();
589
- never_repeats_identities!();
590
- is_shared!();
591
-
592
- fn open(&self, path: &str, options: &OpenOptions) -> Result<Box<dyn File>, FilesystemError> {
593
- self.0.open(path, options)
594
- }
595
-
596
- fn metadata(&self, path: &str) -> Result<Metadata, FilesystemError> {
597
- self.0.metadata(path)
598
- }
599
-
600
- fn stored_path(&self, path: &str) -> Result<String, FilesystemError> {
601
- Ok(path.to_uppercase())
602
- }
603
-
604
- fn read_dir(&self, path: &str) -> Result<Vec<DirEntry>, FilesystemError> {
605
- self.0.read_dir(path)
606
- }
607
-
608
- fn create_dir(&self, path: &str) -> Result<(), FilesystemError> {
609
- self.0.create_dir(path)
610
- }
611
-
612
- fn remove_dir(&self, path: &str) -> Result<(), FilesystemError> {
613
- self.0.remove_dir(path)
755
+ /// A Filesystem holding the files `files`, each path stored in upper case and
756
+ /// reached by any case, as a host storing every name in upper case and
757
+ /// folding case does; a lookup hands back the entry it found under its stored
758
+ /// spelling.
759
+ #[derive(Clone)]
760
+ struct StoresUpperCase(&'static [&'static str]);
761
+
762
+ impl StoresUpperCase {
763
+ /// What stands at `path` once folded: a file it holds, a directory above
764
+ /// one, or nothing, each with an identity of its stored path, so a Policy
765
+ /// can tell it from another.
766
+ fn stat(&self, path: &str) -> Option<Kstat> {
767
+ let path = path.to_uppercase();
768
+ let beneath = format!("{path}/");
769
+ let kind = self.0.iter().find_map(|file| match *file {
770
+ file if file == path => Some(FileType::RegFile),
771
+ file if path.is_empty() || file.starts_with(&beneath) => Some(FileType::Dir),
772
+ _ => None,
773
+ })?;
774
+ let ino = path.bytes().fold(1, |ino: u64, byte| {
775
+ ino.wrapping_mul(31).wrapping_add(u64::from(byte))
776
+ });
777
+ Some(Kstat::new(kind, 0).with_identity(1, ino))
778
+ }
779
+ }
780
+
781
+ impl FileSystemType for StoresUpperCase {
782
+ fn fill_super(self: Arc<Self>, sb: &mut Filesystem) -> Result<(), Errno> {
783
+ sb.d_make_root(vfs::Inode::new(
784
+ &vfs::Kstat::new(vfs::FileType::Dir, 0),
785
+ self,
786
+ ));
787
+ Ok(())
614
788
  }
789
+ }
615
790
 
616
- fn remove_file(&self, path: &str) -> Result<(), FilesystemError> {
617
- self.0.remove_file(path)
791
+ impl InodeOperations for StoresUpperCase {
792
+ fn getattr(&self, dentry: &Dentry) -> Result<Kstat, Errno> {
793
+ self.stat(&dentry.path_raw()[1..]).ok_or(Errno::NotFound)
618
794
  }
619
795
 
620
- fn rename(&self, from: &str, to: &str, rename: Rename) -> Result<(), FilesystemError> {
621
- self.0.rename(from, to, rename)
796
+ fn lookup(&self, dentry: &Dentry) -> Result<Lookup, Errno> {
797
+ let Some(found) = self.stat(&dentry.path_raw()[1..]) else {
798
+ return Ok(Lookup::Absent);
799
+ };
800
+ let inode = Inode::new(&found, Arc::new(self.clone()));
801
+ let name = dentry.name().to_uppercase();
802
+ Ok(match name == dentry.name() {
803
+ true => Lookup::Found(inode),
804
+ false => Lookup::Spelled { name, inode },
805
+ })
622
806
  }
623
807
  }
624
808
 
@@ -627,10 +811,9 @@ impl Filesystem for StoresUpperCase {
627
811
  // @behavior RT-120
628
812
  #[test]
629
813
  fn a_policy_judges_a_path_as_its_filesystem_stores_it() {
630
- let memory: Memory = [("file.txt", "granted")].into_iter().collect();
631
- let policy: Arc<dyn Policy> = Arc::new(Refuses("/data/FILE.TXT"));
814
+ let policy: Arc<dyn for<'a> Policy<MountRequest<'a>>> = Arc::new(Refuses("/data/FILE.TXT"));
632
815
  let mut guest = Guest::new(&[grant(
633
- Arc::new(StoresUpperCase(memory)),
816
+ Arc::new(StoresUpperCase(&["FILE.TXT"])),
634
817
  Access::Read,
635
818
  Some(policy),
636
819
  )]);
@@ -642,10 +825,31 @@ fn a_policy_judges_a_path_as_its_filesystem_stores_it() {
642
825
  );
643
826
  }
644
827
 
828
+ // A Policy handed the descriptor's path as the guest spelled it would see
829
+ // `/data/dir/inner` and let the read through.
830
+ // @behavior RT-120
831
+ #[test]
832
+ fn a_policy_judges_a_path_beneath_an_opened_directory_as_its_filesystem_stores_it() {
833
+ const INNER: (i32, i32) = (960, 5);
834
+ let policy: Arc<dyn for<'a> Policy<MountRequest<'a>>> = Arc::new(Refuses("/data/DIR/INNER"));
835
+ let mut guest = Guest::new(&[grant(
836
+ Arc::new(StoresUpperCase(&["DIR/INNER"])),
837
+ Access::Read,
838
+ Some(policy),
839
+ )]);
840
+ assert_eq!(
841
+ guest.call("open_beneath_dir", INNER),
842
+ ERRNO_ACCES,
843
+ "path_open of `inner` through `dir` opened beneath a Mount whose Policy refuses \
844
+ `/data/DIR/INNER`, over a Filesystem storing both names in upper case, through \
845
+ preview1 must answer EACCES"
846
+ );
847
+ }
848
+
645
849
  // @behavior RT-075
646
850
  #[test]
647
851
  fn a_mount_appears_as_a_directory_at_its_path() {
648
- let mut guest = Guest::new(&[grant(Arc::new(Memory::new()), Access::Read, None)]);
852
+ let mut guest = Guest::new(&[grant(Arc::new(Tmpfs::new()), Access::Read, None)]);
649
853
  assert_eq!(
650
854
  guest.call_bare("preopen_name"),
651
855
  0,
@@ -662,66 +866,262 @@ fn a_mount_appears_as_a_directory_at_its_path() {
662
866
  );
663
867
  }
664
868
 
869
+ /// The inode number the guest reads for `file.txt` from a stat and from a
870
+ /// listing, and for the Mount's root from `.`.
871
+ fn inodes_seen(profile: Profile) -> (u64, u64, u64) {
872
+ let mut guest = Guest::for_profile(
873
+ profile,
874
+ &[grant(file_and_directory(), Access::ReadWrite, None)],
875
+ );
876
+ assert_eq!(guest.call_flagged_stat(), 0, "the stat must succeed");
877
+ assert!(
878
+ guest.list(0, 1024).contains(&"file.txt".to_string()),
879
+ "the listing must hold file.txt"
880
+ );
881
+ let memory = guest
882
+ .instance
883
+ .get_memory(&mut guest.store, "memory")
884
+ .expect("probe exports its memory");
885
+ let data = memory.data(&guest.store);
886
+ let u64_at = |at: usize| u64::from_le_bytes(data[at..at + 8].try_into().unwrap());
887
+ let used = u32::from_le_bytes(data[136..140].try_into().unwrap()) as usize;
888
+ let mut at = 2048;
889
+ let (mut dot, mut listed) = (None, None);
890
+ while at + 24 <= 2048 + used {
891
+ let len = u32::from_le_bytes(data[at + 16..at + 20].try_into().unwrap()) as usize;
892
+ match &data[at + 24..at + 24 + len] {
893
+ b"." => dot = Some(u64_at(at + 8)),
894
+ b"file.txt" => listed = Some(u64_at(at + 8)),
895
+ _ => {}
896
+ }
897
+ at += 24 + len;
898
+ }
899
+ (
900
+ u64_at(384 + 8),
901
+ listed.expect("the listing names file.txt"),
902
+ dot.expect("the listing names `.`"),
903
+ )
904
+ }
905
+
906
+ // The hash is a host detail, so only what a guest can rely on is asserted: a
907
+ // listing and a stat agree, an entry is told from another, and it is no raw
908
+ // inode number, which a fresh Tmpfs numbers from 1.
909
+ // @behavior RT-183
910
+ #[test]
911
+ fn a_permissive_guest_tells_entries_apart_by_their_inode_numbers() {
912
+ let (stat, listed, dot) = inodes_seen(Profile::Permissive);
913
+ assert_eq!(
914
+ stat, listed,
915
+ "fd_readdir and path_filestat_get of a file beneath a Mount through a permissive \
916
+ guest's preview1 must answer the same inode number"
917
+ );
918
+ assert!(
919
+ stat > u64::from(u16::MAX) && dot > u64::from(u16::MAX) && dot != stat,
920
+ "a permissive guest's inode numbers for a file and its directory must differ and be \
921
+ hashes rather than a Filesystem's own small numbers, not {stat} and {dot}"
922
+ );
923
+ }
924
+
925
+ // A Tmpfs's device number depends on how many came before it, so any number
926
+ // drawn from it would differ between otherwise identical runs.
927
+ // @behavior RT-183
928
+ #[test]
929
+ fn a_hermetic_guest_sees_no_inode_numbers() {
930
+ assert_eq!(
931
+ inodes_seen(Profile::Hermetic),
932
+ (0, 0, 0),
933
+ "a stat and a listing of a file and its directory beneath a Mount through a hermetic \
934
+ guest's preview1 must answer inode number 0"
935
+ );
936
+ }
937
+
938
+ /// A host directory holding only `a.txt`, which a Bind reads whole to list.
939
+ fn host_dir_with_a_file(name: &str) -> std::path::PathBuf {
940
+ let dir = std::env::temp_dir().join(format!("kobako-listing-{name}-{}", std::process::id()));
941
+ let _ = std::fs::remove_dir_all(&dir);
942
+ std::fs::create_dir_all(&dir).expect("the host directory must be created");
943
+ std::fs::write(dir.join("a.txt"), "").expect("the host file must be written");
944
+ dir
945
+ }
946
+
947
+ // The VFS hands a Bind every name no walk looked up, so a Bind making what
948
+ // any open asks for would leave a file on the host for a guest that only
949
+ // tried to write one standing.
950
+ // @behavior RT-311
951
+ #[test]
952
+ fn a_bind_opens_a_name_no_walk_looked_up_and_makes_nothing() {
953
+ let dir = host_dir_with_a_file("opens-unlooked");
954
+ std::fs::write(dir.join("file.txt"), "granted").expect("the host file must be written");
955
+ let bind = Arc::new(Bind::new(&dir).expect("the host directory must open"));
956
+ let mut guest = Guest::new(&[grant(bind, Access::ReadWrite, None)]);
957
+ let read = guest.call("read_file", FILE);
958
+ let content = guest.read_back();
959
+ let appended = guest.call("append_file", NEW);
960
+ assert_eq!(
961
+ (read, content, appended, dir.join("new.txt").exists()),
962
+ (0, b"granted".to_vec(), ERRNO_NOENT, false),
963
+ "path_open of a file no walk looked up beneath a Bind through preview1 must read it, \
964
+ and of a missing path without O_CREAT must answer ENOENT and make nothing on the host"
965
+ );
966
+ }
967
+
665
968
  // The first listing fills its buffer with `.` and `..` exactly, so it has
666
969
  // not reached its end when the file is made.
667
970
  // @behavior RT-107
668
971
  #[test]
669
972
  fn a_listing_goes_on_over_the_entries_it_began_with() {
670
- let memory: Arc<Memory> = Arc::new([("a.txt", "")].into_iter().collect());
671
- let mut guest = Guest::new(&[grant(memory.clone(), Access::ReadWrite, None)]);
973
+ let dir = host_dir_with_a_file("goes-on");
974
+ let bind = Arc::new(Bind::new(&dir).expect("the host directory must open"));
975
+ let mut guest = Guest::new(&[grant(bind.clone(), Access::ReadWrite, None)]);
672
976
  assert_eq!(
673
977
  guest.list(0, 51),
674
978
  [".", ".."],
675
979
  "the first listing must hold the dots"
676
980
  );
677
- memory
678
- .open(
679
- "b.txt",
680
- &build_options(|options| (options.write, options.create) = (true, true)),
681
- )
682
- .expect("the file must be made");
981
+ overwrite(&host(&bind), "b.txt");
683
982
  assert_eq!(
684
983
  guest.list(2, 4096),
685
984
  ["a.txt"],
686
985
  "a listing going on through fd_readdir must read the entries it began with"
687
986
  );
987
+ let mut from_the_start = guest.list(0, 4096);
988
+ from_the_start.sort();
688
989
  assert_eq!(
689
- guest.list(0, 4096),
990
+ from_the_start,
690
991
  [".", "..", "a.txt", "b.txt"],
691
992
  "a listing from the start through fd_readdir must read the directory as it stands"
692
993
  );
693
994
  }
694
995
 
996
+ // A buffer of 51 takes only the dots, one of 4096 the whole listing; the limit
997
+ // the listing is held against is the memory the guest was allotted, counted
998
+ // from the moment the listing is read.
999
+ // @behavior RT-237
1000
+ #[test]
1001
+ fn a_listing_it_cannot_hold_within_a_guests_memory_answers_enomem() {
1002
+ let dir = host_dir_with_a_file("holds");
1003
+ let answer = |memory_limit, len| {
1004
+ let bind = Arc::new(Bind::new(&dir).expect("the host directory must open"));
1005
+ let mut guest =
1006
+ Guest::with_memory_limit(memory_limit, &[grant(bind, Access::ReadWrite, None)]);
1007
+ let errno = guest.call_list(0, len);
1008
+ let memory = guest
1009
+ .instance
1010
+ .get_memory(&mut guest.store, "memory")
1011
+ .expect("probe exports its memory");
1012
+ let used = u32::from_le_bytes(memory.data(&guest.store)[136..140].try_into().unwrap());
1013
+ (errno, used)
1014
+ };
1015
+ assert_eq!(
1016
+ [answer(1, 51), answer(1, 4096), answer(1 << 20, 51)],
1017
+ [(ERRNO_NOMEM, 0), (ERRNO_NOMEM, 0), (0, 51)],
1018
+ "fd_readdir through preview1, with more to hold than the guest's memory_limit, must \
1019
+ answer ENOMEM before it hands any entry, read part way or whole, and within it succeed"
1020
+ );
1021
+ }
1022
+
1023
+ // @behavior RT-400
1024
+ #[test]
1025
+ fn an_open_the_memory_limit_cannot_hold_answers_enomem_whatever_the_path_names() {
1026
+ let mut starved =
1027
+ Guest::with_memory_limit(1, &[grant(file_and_directory(), Access::Read, None)]);
1028
+ let refused = [FILE, THROUGH_MISSING].map(|path| starved.call("open_close", path));
1029
+ let mut held =
1030
+ Guest::with_memory_limit(1 << 20, &[grant(file_and_directory(), Access::Read, None)]);
1031
+ let reopened = (0..10_000).all(|_| held.call("open_close", FILE) == 0);
1032
+ assert_eq!(
1033
+ (refused, reopened),
1034
+ ([ERRNO_NOMEM; 2], true),
1035
+ "path_open through preview1 under a memory_limit that holds no more files must answer \
1036
+ ENOMEM for a file and a missing path alike, as Linux's path_openat allocates the file \
1037
+ before the walk, and a closed file must give its room back for the next open"
1038
+ );
1039
+ }
1040
+
1041
+ /// A root whose listing hands `.` and `..`, then fails as a host read would.
1042
+ struct FailsPastTheDots;
1043
+
1044
+ struct FailsPastTheDotsDir;
1045
+
1046
+ impl FileOperations for FailsPastTheDotsDir {
1047
+ fn iterate_shared(
1048
+ &mut self,
1049
+ dentry: &Dentry,
1050
+ ctx: &mut vfs::DirContext<'_>,
1051
+ ) -> Result<(), Errno> {
1052
+ if !vfs::dir_emit_dots(dentry, ctx) {
1053
+ return Ok(());
1054
+ }
1055
+ Err(Errno::Other("the host read failed".into()))
1056
+ }
1057
+ }
1058
+
1059
+ impl InodeOperations for FailsPastTheDots {
1060
+ fn getattr(&self, _dentry: &Dentry) -> Result<Kstat, Errno> {
1061
+ Ok(Kstat::new(FileType::Dir, 0))
1062
+ }
1063
+
1064
+ fn open(&self, _dentry: &Dentry, _how: &OpenHow) -> Result<Box<dyn FileOperations>, Errno> {
1065
+ Ok(Box::new(FailsPastTheDotsDir))
1066
+ }
1067
+ }
1068
+
1069
+ impl FileSystemType for FailsPastTheDots {
1070
+ fn fill_super(self: Arc<Self>, sb: &mut Filesystem) -> Result<(), Errno> {
1071
+ sb.d_make_root(vfs::Inode::new(
1072
+ &vfs::Kstat::new(vfs::FileType::Dir, 0),
1073
+ self,
1074
+ ));
1075
+ Ok(())
1076
+ }
1077
+ }
1078
+
1079
+ // The dots are written before the Filesystem fails, so only the call going on
1080
+ // from them meets the failure with nothing written.
1081
+ // @behavior RT-301
1082
+ #[test]
1083
+ fn a_listing_failing_once_it_has_handed_entries_answers_those_entries() {
1084
+ let mut guest = Guest::new(&[grant(Arc::new(FailsPastTheDots), Access::Read, None)]);
1085
+ let first = guest.list(0, 4096);
1086
+ assert_eq!(
1087
+ (first, guest.call_list(2, 4096)),
1088
+ (vec![".".to_string(), "..".to_string()], ERRNO_IO),
1089
+ "fd_readdir through preview1 of a Filesystem failing after it hands the dots must \
1090
+ answer the dots, and the next call from them the error, as getdents64 answers the \
1091
+ bytes it wrote over iterate_dir's error"
1092
+ );
1093
+ }
1094
+
695
1095
  // @behavior RT-076
696
1096
  #[test]
697
1097
  fn a_guest_reads_a_file_beneath_a_mount() {
698
- let memory: Memory = [("file.txt", "granted")].into_iter().collect();
699
- let mut guest = Guest::new(&[grant(Arc::new(memory), Access::Read, None)]);
1098
+ let tmpfs: Tmpfs = [("file.txt", "granted")].into_iter().collect();
1099
+ let mut guest = Guest::new(&[grant(Arc::new(tmpfs), Access::Read, None)]);
700
1100
  assert_eq!(guest.call("read_file", FILE), 0, "the read must succeed");
701
1101
  assert_eq!(
702
1102
  guest.read_back(),
703
1103
  b"granted",
704
- "a file read beneath a Mount through preview1 must read the Memory's content"
1104
+ "a file read beneath a Mount through preview1 must read the Tmpfs's content"
705
1105
  );
706
1106
  }
707
1107
 
708
1108
  // @behavior RT-077
709
1109
  #[test]
710
1110
  fn a_guest_writes_a_file_beneath_a_read_write_mount() {
711
- let memory = Arc::new(Memory::new());
712
- let mut guest = Guest::new(&[grant(memory.clone(), Access::ReadWrite, None)]);
1111
+ let tmpfs = Arc::new(Tmpfs::new());
1112
+ let mut guest = Guest::new(&[grant(tmpfs.clone(), Access::ReadWrite, None)]);
713
1113
  assert_eq!(guest.call("write_file", FILE), 0, "the write must succeed");
714
1114
  assert_eq!(
715
- contents(memory.as_ref(), "file.txt").as_deref(),
1115
+ contents(&host(&tmpfs), "file.txt").as_deref(),
716
1116
  Some(&b"hello"[..]),
717
- "a file written beneath a read-write Mount through preview1 must land in the Memory"
1117
+ "a file written beneath a read-write Mount through preview1 must land in the Tmpfs"
718
1118
  );
719
1119
  }
720
1120
 
721
1121
  // @behavior RT-078
722
1122
  #[test]
723
1123
  fn a_change_beneath_a_read_only_mount_is_a_read_only_filesystem() {
724
- let mut guest = Guest::new(&[grant(Arc::new(Memory::new()), Access::Read, None)]);
1124
+ let mut guest = Guest::new(&[grant(Arc::new(Tmpfs::new()), Access::Read, None)]);
725
1125
  assert_eq!(
726
1126
  guest.call("write_file", FILE),
727
1127
  ERRNO_ROFS,
@@ -735,12 +1135,12 @@ fn a_change_beneath_a_read_only_mount_is_a_read_only_filesystem() {
735
1135
  // @behavior RT-078
736
1136
  #[test]
737
1137
  fn a_truncating_open_beneath_a_read_only_mount_is_refused() {
738
- let memory: Arc<Memory> = Arc::new([("file.txt", "granted")].into_iter().collect());
739
- let mut guest = Guest::new(&[grant(memory.clone(), Access::Read, None)]);
1138
+ let tmpfs = tmpfs_with("file.txt", "granted");
1139
+ let mut guest = Guest::new(&[grant(tmpfs.clone(), Access::Read, None)]);
740
1140
  assert_eq!(
741
1141
  (
742
1142
  guest.call("truncate_file", FILE),
743
- contents(memory.as_ref(), "file.txt")
1143
+ contents(&host(&tmpfs), "file.txt")
744
1144
  ),
745
1145
  (ERRNO_ROFS, Some(b"granted".to_vec())),
746
1146
  "a read-rights open with O_TRUNC beneath a read-only Mount through preview1 must answer \
@@ -751,8 +1151,8 @@ fn a_truncating_open_beneath_a_read_only_mount_is_refused() {
751
1151
  // @behavior RT-079
752
1152
  #[test]
753
1153
  fn a_path_above_a_mounts_root_is_refused() {
754
- let memory: Memory = [("file.txt", "granted")].into_iter().collect();
755
- let mut guest = Guest::new(&[grant(Arc::new(memory), Access::Read, None)]);
1154
+ let tmpfs: Tmpfs = [("file.txt", "granted")].into_iter().collect();
1155
+ let mut guest = Guest::new(&[grant(Arc::new(tmpfs), Access::Read, None)]);
756
1156
  assert_eq!(
757
1157
  guest.call("read_file", ABOVE_ROOT),
758
1158
  ERRNO_NOTCAPABLE,
@@ -765,10 +1165,10 @@ fn a_path_above_a_mounts_root_is_refused() {
765
1165
  // @behavior RT-115
766
1166
  #[test]
767
1167
  fn a_path_above_the_directory_it_is_opened_beneath_is_refused() {
768
- let memory: Memory = [("file.txt", "granted"), ("dir/inner.txt", "beneath")]
1168
+ let tmpfs: Tmpfs = [("file.txt", "granted"), ("dir/inner.txt", "beneath")]
769
1169
  .into_iter()
770
1170
  .collect();
771
- let mut guest = Guest::new(&[grant(Arc::new(memory), Access::Read, None)]);
1171
+ let mut guest = Guest::new(&[grant(Arc::new(tmpfs), Access::Read, None)]);
772
1172
  assert_eq!(
773
1173
  guest.call("open_beneath_dir", ABOVE_ROOT),
774
1174
  ERRNO_NOTCAPABLE,
@@ -777,136 +1177,262 @@ fn a_path_above_the_directory_it_is_opened_beneath_is_refused() {
777
1177
  );
778
1178
  }
779
1179
 
780
- /// What `stat_inner` answers through `dir` opened before `change` runs on
781
- /// the Memory holding it.
782
- fn stat_after(change: impl FnOnce(&Memory)) -> i32 {
783
- let memory = file_and_directory();
784
- let mut guest = Guest::new(&[grant(memory.clone(), Access::ReadWrite, None)]);
1180
+ /// What `stat_inner` answers through `dir` opened, beneath a Mount with
1181
+ /// `policy`, before `change` runs on the host's root of the Tmpfs
1182
+ /// holding it.
1183
+ fn stat_after(
1184
+ policy: Option<Arc<dyn for<'a> Policy<MountRequest<'a>>>>,
1185
+ change: impl FnOnce(&Path),
1186
+ ) -> i32 {
1187
+ let tmpfs = file_and_directory();
1188
+ let mut guest = Guest::new(&[grant(tmpfs.clone(), Access::ReadWrite, policy)]);
785
1189
  assert_eq!(
786
1190
  guest.call_bare("open_dir"),
787
1191
  0,
788
1192
  "dir must open as a directory"
789
1193
  );
790
- change(&memory);
1194
+ change(&host(&tmpfs));
791
1195
  guest.call_bare("stat_inner")
792
1196
  }
793
1197
 
1198
+ /// Move `dir` away, its `inner` with it, and make another `dir` holding
1199
+ /// an `inner` of its own, so only where the descriptor reaches decides
1200
+ /// whether the lookup finds one.
1201
+ fn move_and_replace(root: &Path) {
1202
+ vfs::filename_renameat2(&prepare_creds(&[], None), root, "dir", root, "moved").unwrap();
1203
+ vfs::filename_mkdirat(&prepare_creds(&[], None), root, "dir").unwrap();
1204
+ overwrite(root, "dir/inner");
1205
+ }
1206
+
794
1207
  // A directory made at the path holds an `inner` of its own, so only the
795
- // identity check keeps the descriptor from reaching it.
1208
+ // descriptor still standing for the removed one keeps it from reaching it.
796
1209
  // @behavior RT-117
797
1210
  #[test]
798
- fn a_directory_made_in_an_opened_directorys_place_is_not_reached_through_it() {
799
- let answers = (
800
- stat_after(|memory| {
801
- memory.rename("dir", "moved", Rename::Any).unwrap();
802
- memory.create_dir("dir").unwrap();
803
- overwrite(memory, "dir/inner");
804
- }),
805
- stat_after(|memory| {
806
- memory.remove_file("dir/inner").unwrap();
807
- memory.remove_dir("dir").unwrap();
808
- memory.create_dir("dir").unwrap();
809
- overwrite(memory, "dir/inner");
810
- }),
811
- );
1211
+ fn a_directory_made_in_a_removed_directorys_place_is_not_reached_through_it() {
1212
+ let answer = stat_after(None, |root| {
1213
+ vfs::filename_unlinkat(&prepare_creds(&[], None), root, "dir/inner").unwrap();
1214
+ vfs::filename_rmdir(&prepare_creds(&[], None), root, "dir").unwrap();
1215
+ vfs::filename_mkdirat(&prepare_creds(&[], None), root, "dir").unwrap();
1216
+ overwrite(root, "dir/inner");
1217
+ });
812
1218
  assert_eq!(
813
- answers,
814
- (ERRNO_NOENT, ERRNO_NOENT),
1219
+ answer, ERRNO_NOENT,
815
1220
  "path_filestat_get through a directory descriptor beneath a Mount through preview1 must \
816
- answer ENOENT once another directory stands at its path, moved in or made anew"
1221
+ answer ENOENT once the directory was removed and another made at its path"
817
1222
  );
818
1223
  }
819
1224
 
820
- /// A Memory naming `dir` by one inode number for as long as nothing holds
821
- /// it, as a host hands a removed directory's number to the next one made,
822
- /// and by a fresh number once a held `dir` was removed.
823
- struct ReusesInodes {
824
- memory: Arc<Memory>,
825
- holds: Arc<AtomicUsize>,
826
- removed_while_held: AtomicUsize,
1225
+ // @behavior RT-149
1226
+ #[test]
1227
+ fn a_directory_moved_while_opened_is_reached_through_its_descriptor() {
1228
+ assert_eq!(
1229
+ stat_after(None, move_and_replace),
1230
+ 0,
1231
+ "path_filestat_get through a directory descriptor beneath a Mount without a Policy \
1232
+ through preview1 must reach the directory where it moved"
1233
+ );
827
1234
  }
828
1235
 
829
- /// Counts as holding a directory until it drops.
830
- struct Holding(Arc<AtomicUsize>);
1236
+ // A Bind opens a directory a walk only steps through when a call needs
1237
+ // it, so only an open that holds the host directory at once keeps the
1238
+ // descriptor on it once another stands at its path.
1239
+ // @behavior RT-149
1240
+ #[cfg(unix)]
1241
+ #[test]
1242
+ fn a_host_directory_moved_while_opened_is_reached_through_its_descriptor() {
1243
+ let host = LinkedHost::new("moved-open");
1244
+ std::fs::create_dir_all(host.0.join("real2/inner")).expect("the host tree must be made");
1245
+ std::fs::remove_file(host.0.join("dir")).expect("the link must go");
1246
+ std::fs::rename(host.0.join("real2"), host.0.join("dir")).expect("the directory must move");
1247
+ let mut guest = host.guest();
1248
+ assert_eq!(guest.call_bare("open_dir"), 0, "dir must open");
1249
+ std::fs::rename(host.0.join("dir"), host.0.join("moved")).expect("the directory must move");
1250
+ std::fs::create_dir(host.0.join("dir")).expect("another directory must be made");
1251
+ assert_eq!(
1252
+ guest.call_bare("stat_inner"),
1253
+ 0,
1254
+ "path_filestat_get of inner through a descriptor of a host directory beneath a Bind \
1255
+ Mount, moved away after it opened and another made at its path, through preview1 must \
1256
+ reach the directory where it moved"
1257
+ );
1258
+ }
831
1259
 
832
- impl Drop for Holding {
833
- fn drop(&mut self) {
834
- self.0.fetch_sub(1, Ordering::SeqCst);
835
- }
1260
+ // The move goes through another Filesystem instance, which the guest's
1261
+ // dentries never see, so only the Tmpfs answering the descriptor's dentry
1262
+ // stale, once another directory stands at its path, refuses the call.
1263
+ // @behavior RT-150
1264
+ #[test]
1265
+ fn a_directory_moved_while_opened_beneath_a_policy_is_not_reached() {
1266
+ assert_eq!(
1267
+ stat_after(Some(Arc::new(AllowsAll)), move_and_replace),
1268
+ ERRNO_NOENT,
1269
+ "path_filestat_get through a directory descriptor beneath a Mount with a Policy through \
1270
+ preview1 must answer ENOENT once the directory moved away"
1271
+ );
836
1272
  }
837
1273
 
838
- impl Filesystem for ReusesInodes {
839
- holds_no_links!();
840
- matches_names_exactly!();
841
- is_shared!();
1274
+ /// What `call` answers through the directory a guest holds beneath a Policy,
1275
+ /// once the directory moved away outside the runtime.
1276
+ fn answer_once_moved_away(call: &str) -> i32 {
1277
+ let tmpfs = file_and_directory();
1278
+ let mut guest = Guest::new(&[grant(
1279
+ tmpfs.clone(),
1280
+ Access::ReadWrite,
1281
+ Some(Arc::new(AllowsAll)),
1282
+ )]);
1283
+ assert_eq!(guest.call_bare("open_dir"), 0, "dir must open");
1284
+ move_and_replace(&host(&tmpfs));
1285
+ guest.call_bare(call)
1286
+ }
842
1287
 
843
- fn open(&self, path: &str, options: &OpenOptions) -> Result<Box<dyn File>, FilesystemError> {
844
- self.memory.open(path, options)
845
- }
1288
+ // A Policy judges no stat or listing, so nothing asks whether the descriptor's
1289
+ // dentry still stands; the descriptor answers as its Filesystem holds it.
1290
+ // @behavior RT-226
1291
+ #[test]
1292
+ fn a_descriptor_moved_beneath_a_policy_still_reports_itself() {
1293
+ assert_eq!(
1294
+ answer_once_moved_away("fstat_dir"),
1295
+ 0,
1296
+ "fd_filestat_get of a directory descriptor beneath a Mount with a Policy through preview1 \
1297
+ must succeed once the directory moved away"
1298
+ );
1299
+ }
846
1300
 
847
- fn metadata(&self, path: &str) -> Result<Metadata, FilesystemError> {
848
- let found = self.memory.metadata(path)?;
849
- if path != "dir" {
850
- return Ok(found);
851
- }
852
- let ino = 100 + self.removed_while_held.load(Ordering::SeqCst) as u64;
853
- Ok(found.with_identity(1, ino))
854
- }
1301
+ // @behavior RT-227
1302
+ #[test]
1303
+ fn a_descriptor_moved_beneath_a_policy_still_lists_itself() {
1304
+ assert_eq!(
1305
+ answer_once_moved_away("list_dir"),
1306
+ 0,
1307
+ "fd_readdir of a directory descriptor beneath a Mount with a Policy through preview1 must \
1308
+ succeed once the directory moved away"
1309
+ );
1310
+ }
1311
+
1312
+ // The second Mount shares the instance's dentries, so the move carries
1313
+ // the descriptor's along, and the Policy judges the path it moved to:
1314
+ // allowed there it reaches `inner`, refused there it answers EACCES.
1315
+ // @behavior RT-170
1316
+ #[test]
1317
+ fn a_directory_moved_beneath_another_mount_of_its_instance_is_reached_beneath_a_policy() {
1318
+ let open_after_move = |policy: Arc<dyn for<'a> Policy<MountRequest<'a>>>| {
1319
+ let instance = Filesystem::new(file_and_directory()).expect("the instance must stand");
1320
+ let mount = Mount::new("/data", instance.clone(), Access::ReadWrite)
1321
+ .expect("/data is a guest path");
1322
+ let mut guest = Guest::new(&[Grant::Mount(mount.clone().with_policy(policy))]);
1323
+ assert_eq!(guest.call_bare("open_dir"), 0, "dir must open");
1324
+ let other = Path::root(mount.mnt());
1325
+ vfs::filename_renameat2(&prepare_creds(&[], None), &other, "dir", &other, "moved")
1326
+ .expect("the directory must move");
1327
+ vfs::filename_mkdirat(&prepare_creds(&[], None), &other, "dir")
1328
+ .expect("another directory must be made");
1329
+ guest.call_bare("open_inner")
1330
+ };
1331
+ assert_eq!(
1332
+ (
1333
+ open_after_move(Arc::new(AllowsAll)),
1334
+ open_after_move(Arc::new(Refuses("/data/moved/inner")))
1335
+ ),
1336
+ (0, ERRNO_ACCES),
1337
+ "path_open of inner through a directory descriptor beneath a Mount with a Policy, \
1338
+ once the directory moved beneath another Mount of the same Filesystem instance, through \
1339
+ preview1 must reach it where it moved, as the Policy judges that path"
1340
+ );
1341
+ }
855
1342
 
856
- fn hold_directory(&self, path: &str) -> Result<Option<Hold>, FilesystemError> {
857
- if path != "dir" {
858
- return Ok(None);
859
- }
860
- self.holds.fetch_add(1, Ordering::SeqCst);
861
- Ok(Some(Hold::new(Holding(self.holds.clone()))))
862
- }
1343
+ /// A Tmpfs naming `dir` by one inode number for as long as no directory
1344
+ /// it opened there is open, as a host hands a removed directory's number
1345
+ /// to the next one made, and by a fresh number once an open `dir` was
1346
+ /// removed.
1347
+ #[derive(Default)]
1348
+ struct ReusesInodes {
1349
+ found: Mutex<Vec<Weak<dyn InodeOperations>>>,
1350
+ removed_while_open: AtomicUsize,
1351
+ }
863
1352
 
864
- fn read_dir(&self, path: &str) -> Result<Vec<DirEntry>, FilesystemError> {
865
- self.memory.read_dir(path)
1353
+ impl ReusesInodes {
1354
+ fn dir_kstat(&self, found: Kstat) -> Kstat {
1355
+ let ino = 100 + self.removed_while_open.load(Ordering::SeqCst) as u64;
1356
+ found.with_identity(1, ino)
866
1357
  }
1358
+ }
867
1359
 
868
- fn create_dir(&self, path: &str) -> Result<(), FilesystemError> {
869
- self.memory.create_dir(path)
1360
+ impl Hook for ReusesInodes {
1361
+ fn getattr(&self, inner: &dyn InodeOperations, dentry: &Dentry) -> Result<Kstat, Errno> {
1362
+ let found = inner.getattr(dentry)?;
1363
+ Ok(match dentry.name().as_str() {
1364
+ "dir" => self.dir_kstat(found),
1365
+ _ => found,
1366
+ })
870
1367
  }
871
1368
 
872
- fn remove_dir(&self, path: &str) -> Result<(), FilesystemError> {
873
- self.memory.remove_dir(path)?;
874
- if self.holds.load(Ordering::SeqCst) > 0 {
875
- self.removed_while_held.fetch_add(1, Ordering::SeqCst);
876
- }
877
- Ok(())
1369
+ fn lookup(&self, inner: &dyn InodeOperations, dentry: &Dentry) -> Result<Lookup, Errno> {
1370
+ Ok(match inner.lookup(dentry)? {
1371
+ Lookup::Found(inode) if dentry.name() == "dir" => {
1372
+ self.found.lock().unwrap().push(Arc::downgrade(inode.ops()));
1373
+ let found = self.dir_kstat(inode.ops().getattr(dentry)?);
1374
+ Lookup::Found(Inode::new(&found, inode.ops().clone()))
1375
+ }
1376
+ other => other,
1377
+ })
878
1378
  }
879
1379
 
880
- fn remove_file(&self, path: &str) -> Result<(), FilesystemError> {
881
- self.memory.remove_file(path)
1380
+ /// Its root answers as the Filesystem's and sets up nothing of it.
1381
+ fn fill_super(&self, fs: Arc<dyn FileSystemType>, sb: &mut Filesystem) -> Result<(), Errno> {
1382
+ let beneath = Filesystem::new(fs)?;
1383
+ let root = beneath
1384
+ .root()
1385
+ .and_then(|root| root.inode())
1386
+ .ok_or(Errno::NotFound)?;
1387
+ sb.d_make_root(vfs::Inode::new(
1388
+ &vfs::Kstat::new(vfs::FileType::Dir, 0),
1389
+ root.ops().clone(),
1390
+ ));
1391
+ Ok(())
882
1392
  }
883
1393
 
884
- fn rename(&self, from: &str, to: &str, rename: Rename) -> Result<(), FilesystemError> {
885
- self.memory.rename(from, to, rename)
1394
+ /// The call removing it holds what it looked up, so `dir` is open
1395
+ /// beyond that only where a descriptor holds it too.
1396
+ fn rmdir(&self, inner: &dyn InodeOperations, dentry: &Dentry) -> Result<(), Errno> {
1397
+ let removed = inner.rmdir(dentry);
1398
+ let held = self
1399
+ .found
1400
+ .lock()
1401
+ .unwrap()
1402
+ .iter()
1403
+ .filter(|dir| dir.strong_count() > 0)
1404
+ .count();
1405
+ if removed.is_ok() && dentry.name() == "dir" && held > 1 {
1406
+ self.removed_while_open.fetch_add(1, Ordering::SeqCst);
1407
+ }
1408
+ removed
886
1409
  }
887
1410
  }
888
1411
 
889
- // The Filesystem gives the new `dir` the old one's number unless a Hold
890
- // on it lives, so only the descriptor keeping its Hold refuses the call.
1412
+ // The Filesystem gives the new `dir` the old one's number unless the
1413
+ // directory opened there is still open, and beneath a Policy the
1414
+ // descriptor finds its directory again by that number, so only the
1415
+ // descriptor keeping the directory open refuses the call.
891
1416
  // @behavior RT-121
892
1417
  #[test]
893
1418
  fn a_directory_descriptor_holds_its_directory_while_open() {
894
- let memory = file_and_directory();
895
- let reuses = Arc::new(ReusesInodes {
896
- memory: memory.clone(),
897
- holds: Arc::new(AtomicUsize::new(0)),
898
- removed_while_held: AtomicUsize::new(0),
899
- });
900
- let mut guest = Guest::new(&[grant(reuses.clone(), Access::ReadWrite, None)]);
1419
+ let tmpfs = file_and_directory();
1420
+ let reuses = Wrap::new(tmpfs.clone(), Arc::new(ReusesInodes::default()));
1421
+ let mut guest = Guest::new(&[grant(
1422
+ reuses.clone(),
1423
+ Access::ReadWrite,
1424
+ Some(Arc::new(AllowsAll)),
1425
+ )]);
901
1426
  assert_eq!(
902
1427
  guest.call_bare("open_dir"),
903
1428
  0,
904
1429
  "dir must open as a directory"
905
1430
  );
906
- reuses.remove_file("dir/inner").unwrap();
907
- reuses.remove_dir("dir").unwrap();
908
- reuses.create_dir("dir").unwrap();
909
- overwrite(memory.as_ref(), "dir/inner");
1431
+ let outside = host(&reuses);
1432
+ vfs::filename_unlinkat(&prepare_creds(&[], None), &outside, "dir/inner").unwrap();
1433
+ vfs::filename_rmdir(&prepare_creds(&[], None), &outside, "dir").unwrap();
1434
+ vfs::filename_mkdirat(&prepare_creds(&[], None), &outside, "dir").unwrap();
1435
+ overwrite(&host(&tmpfs), "dir/inner");
910
1436
  assert_eq!(
911
1437
  guest.call_bare("stat_inner"),
912
1438
  ERRNO_NOENT,
@@ -916,16 +1442,117 @@ fn a_directory_descriptor_holds_its_directory_while_open() {
916
1442
  );
917
1443
  }
918
1444
 
1445
+ /// A Tmpfs reporting no identity for anything it holds, as a host whose
1446
+ /// stat names no inode.
1447
+ struct NamesNoIdentity;
1448
+
1449
+ impl Hook for NamesNoIdentity {
1450
+ fn lookup(&self, inner: &dyn InodeOperations, dentry: &Dentry) -> Result<Lookup, Errno> {
1451
+ Ok(match inner.lookup(dentry)? {
1452
+ Lookup::Found(inode) => {
1453
+ let found = inode.ops().getattr(dentry)?;
1454
+ let bare = Kstat::new(found.file_type, found.size);
1455
+ Lookup::Found(Inode::new(&bare, inode.ops().clone()))
1456
+ }
1457
+ other => other,
1458
+ })
1459
+ }
1460
+ }
1461
+
1462
+ // Without an identity the descriptor cannot tell its directory from one
1463
+ // made in its place, so beneath a Policy it answers less rather than
1464
+ // reach another.
1465
+ // @behavior RT-151
1466
+ #[test]
1467
+ fn a_directory_without_an_identity_is_not_reached_again_beneath_a_policy() {
1468
+ let mut guest = Guest::new(&[grant(
1469
+ Wrap::new(file_and_directory(), Arc::new(NamesNoIdentity)),
1470
+ Access::ReadWrite,
1471
+ Some(Arc::new(AllowsAll)),
1472
+ )]);
1473
+ assert_eq!(
1474
+ (guest.call_bare("open_dir"), guest.call_bare("stat_inner")),
1475
+ (0, ERRNO_NOENT),
1476
+ "path_filestat_get through a directory descriptor beneath a Mount with a Policy, over a \
1477
+ Filesystem reporting no identity, through preview1 must answer ENOENT"
1478
+ );
1479
+ }
1480
+
1481
+ // @behavior RT-233
1482
+ #[test]
1483
+ fn a_directory_without_an_identity_still_reports_itself_beneath_a_policy() {
1484
+ let mut guest = Guest::new(&[grant(
1485
+ Wrap::new(file_and_directory(), Arc::new(NamesNoIdentity)),
1486
+ Access::ReadWrite,
1487
+ Some(Arc::new(AllowsAll)),
1488
+ )]);
1489
+ assert_eq!(
1490
+ (guest.call_bare("open_dir"), guest.call_bare("fstat_dir")),
1491
+ (0, 0),
1492
+ "fd_filestat_get of a directory descriptor beneath a Mount with a Policy, over a \
1493
+ Filesystem reporting no identity, through preview1 must succeed"
1494
+ );
1495
+ }
1496
+
1497
+ // The table holds the three standard descriptors and the preopen alone, so a
1498
+ // missing path, or one no call can take, could only answer EMFILE by asking
1499
+ // the table first. A path of `PATH_MAX` bytes is too long, an empty one or one
1500
+ // holding a NUL names nothing, and one that is not UTF-8 is never decoded.
1501
+ // @behavior RT-190
1502
+ #[test]
1503
+ fn a_full_table_answers_emfile_whatever_the_path_names() {
1504
+ let mut guest = Guest::with_open_file_limit(
1505
+ Some(4),
1506
+ &[grant(file_and_directory(), Access::ReadWrite, None)],
1507
+ );
1508
+ let too_long = (0, i32::try_from(PATH_MAX).expect("PATH_MAX fits an i32"));
1509
+ let answers = [THROUGH_MISSING, EMPTY, HOLDING_NUL, too_long, NOT_UTF8]
1510
+ .map(|path| guest.call("read_file", path));
1511
+ assert_eq!(
1512
+ answers, [ERRNO_MFILE; 5],
1513
+ "path_open of a missing, empty, NUL-holding, too long, or non-UTF-8 path through \
1514
+ preview1 with no descriptor left must answer EMFILE, as Linux's FD_ADD takes one \
1515
+ before do_file_open answers for the name"
1516
+ );
1517
+ }
1518
+
1519
+ // The three standard descriptors and the preopen leave room for one more,
1520
+ // so a directory spanning both Layers taking more than one leaves none
1521
+ // for the file.
1522
+ // @behavior RT-152
1523
+ #[test]
1524
+ fn an_overlay_directory_takes_one_descriptor_however_many_layers_it_spans() {
1525
+ let overlay = Overlay::new(
1526
+ vec![Filesystem::new(file_and_directory()).expect("the instance must stand")],
1527
+ Some(Filesystem::new(tmpfs_with("dir/upper", "u")).expect("the instance must stand")),
1528
+ )
1529
+ .expect("an upper over a lower Layer must make a view");
1530
+ let mut guest = Guest::with_open_file_limit(
1531
+ Some(6),
1532
+ &[grant(Arc::new(overlay), Access::ReadWrite, None)],
1533
+ );
1534
+ assert_eq!(
1535
+ (
1536
+ guest.call_bare("open_dir"),
1537
+ guest.call("read_file", FILE),
1538
+ guest.call("read_file", FILE)
1539
+ ),
1540
+ (0, 0, ERRNO_MFILE),
1541
+ "path_open of a directory two Layers of an Overlay hold, then of files, beneath a Mount \
1542
+ through preview1 with room for two descriptors must take one descriptor for each"
1543
+ );
1544
+ }
1545
+
919
1546
  // The open looks the directory up without following a link at its end, so
920
1547
  // the identity it remembers comes from the Overlay's lstat, and every later
921
1548
  // call compares it with the Overlay's stat.
922
1549
  #[test]
923
1550
  fn a_directory_two_layers_hold_is_reached_through_its_descriptor() {
924
- let upper: Arc<dyn Filesystem> = Arc::new([("dir/upper", "u")].into_iter().collect::<Memory>());
925
- let lower: Arc<dyn Filesystem> = file_and_directory();
926
- let overlay = Overlay::new()
927
- .layer(upper, Access::ReadWrite)
928
- .layer(lower, Access::Read);
1551
+ let overlay = Overlay::new(
1552
+ vec![Filesystem::new(file_and_directory()).expect("the instance must stand")],
1553
+ Some(Filesystem::new(tmpfs_with("dir/upper", "u")).expect("the instance must stand")),
1554
+ )
1555
+ .expect("an upper over a lower Layer must make a view");
929
1556
  let mut guest = Guest::new(&[grant(Arc::new(overlay), Access::ReadWrite, None)]);
930
1557
  assert_eq!(
931
1558
  (guest.call_bare("open_dir"), guest.call_bare("stat_inner")),
@@ -938,9 +1565,9 @@ fn a_directory_two_layers_hold_is_reached_through_its_descriptor() {
938
1565
  // @behavior RT-118
939
1566
  #[test]
940
1567
  fn a_directory_moved_back_to_its_path_is_reached_through_its_descriptor_again() {
941
- let answer = stat_after(|memory| {
942
- memory.rename("dir", "moved", Rename::Any).unwrap();
943
- memory.rename("moved", "dir", Rename::Any).unwrap();
1568
+ let answer = stat_after(None, |root| {
1569
+ vfs::filename_renameat2(&prepare_creds(&[], None), root, "dir", root, "moved").unwrap();
1570
+ vfs::filename_renameat2(&prepare_creds(&[], None), root, "moved", root, "dir").unwrap();
944
1571
  });
945
1572
  assert_eq!(
946
1573
  answer, 0,
@@ -952,9 +1579,9 @@ fn a_directory_moved_back_to_its_path_is_reached_through_its_descriptor_again()
952
1579
  // @behavior RT-080
953
1580
  #[test]
954
1581
  fn a_policy_refusing_an_open_answers_access_denied() {
955
- let memory: Memory = [("file.txt", "granted")].into_iter().collect();
956
- let policy: Arc<dyn Policy> = Arc::new(Refuses("/data/file.txt"));
957
- let mut guest = Guest::new(&[grant(Arc::new(memory), Access::Read, Some(policy))]);
1582
+ let tmpfs: Tmpfs = [("file.txt", "granted")].into_iter().collect();
1583
+ let policy: Arc<dyn for<'a> Policy<MountRequest<'a>>> = Arc::new(Refuses("/data/file.txt"));
1584
+ let mut guest = Guest::new(&[grant(Arc::new(tmpfs), Access::Read, Some(policy))]);
958
1585
  assert_eq!(
959
1586
  guest.call("read_file", FILE),
960
1587
  ERRNO_ACCES,
@@ -964,22 +1591,26 @@ fn a_policy_refusing_an_open_answers_access_denied() {
964
1591
 
965
1592
  // @behavior RT-081
966
1593
  #[test]
967
- fn a_policy_decides_in_the_place_of_a_mounts_access() {
968
- let memory = Arc::new(Memory::new());
969
- let policy: Arc<dyn Policy> = Arc::new(AllowsAll);
970
- let mut guest = Guest::new(&[grant(memory.clone(), Access::Read, Some(policy))]);
971
- assert_eq!(guest.call("write_file", FILE), 0, "the write must succeed");
1594
+ fn a_policy_cannot_widen_a_mounts_access() {
1595
+ let tmpfs = Arc::new(Tmpfs::new());
1596
+ let policy: Arc<dyn for<'a> Policy<MountRequest<'a>>> = Arc::new(AllowsAll);
1597
+ let mut guest = Guest::new(&[grant(tmpfs.clone(), Access::Read, Some(policy))]);
972
1598
  assert_eq!(
973
- contents(memory.as_ref(), "file.txt").as_deref(),
974
- Some(&b"hello"[..]),
975
- "a write a Policy allows beneath a read-only Mount through preview1 must land"
1599
+ (
1600
+ guest.call("write_file", FILE),
1601
+ contents(&host(&tmpfs), "file.txt")
1602
+ ),
1603
+ (ERRNO_ROFS, None),
1604
+ "a write a Policy allows beneath a read-only Mount through preview1 must answer EROFS \
1605
+ and leave nothing behind"
976
1606
  );
977
1607
  }
978
1608
 
979
1609
  // @behavior RT-082
980
1610
  #[test]
981
- fn each_invocation_is_handed_the_filesystem_it_starts_from() {
982
- let grants = [grant(Arc::new(Temporary::new()), Access::ReadWrite, None)];
1611
+ fn every_invocation_reaches_the_filesystem_its_mount_holds() {
1612
+ let tmpfs = Arc::new(Tmpfs::new());
1613
+ let grants = [grant(tmpfs.clone(), Access::ReadWrite, None)];
983
1614
  assert_eq!(
984
1615
  Guest::new(&grants).call("write_file", FILE),
985
1616
  0,
@@ -987,24 +1618,30 @@ fn each_invocation_is_handed_the_filesystem_it_starts_from() {
987
1618
  );
988
1619
  assert_eq!(
989
1620
  Guest::new(&grants).call("read_file", FILE),
990
- ERRNO_NOENT,
991
- "a file an earlier invocation wrote to a Temporary must not be found by the next one"
1621
+ 0,
1622
+ "a file an earlier invocation wrote beneath a Mount over a Tmpfs must be found by the \
1623
+ next invocation through preview1"
1624
+ );
1625
+ assert_eq!(
1626
+ contents(&host(&tmpfs), "file.txt").as_deref(),
1627
+ Some(&b"hello"[..]),
1628
+ "the file the next invocation finds must hold what the earlier invocation wrote"
992
1629
  );
993
1630
  }
994
1631
 
995
- /// A Memory holding `file.txt` that counts every change it is asked for,
1632
+ /// A Tmpfs holding `file.txt` that counts every change it is asked for,
996
1633
  /// so a test can tell the runtime refused before asking it.
1634
+ #[derive(Default)]
997
1635
  struct ChangeCounter {
998
- memory: Memory,
999
1636
  changes: AtomicUsize,
1000
1637
  }
1001
1638
 
1002
1639
  impl ChangeCounter {
1003
- fn new() -> Arc<Self> {
1004
- Arc::new(Self {
1005
- memory: [("file.txt", "granted")].into_iter().collect(),
1006
- changes: AtomicUsize::new(0),
1007
- })
1640
+ /// A counter, and a Tmpfs holding `file.txt` it counts the changes of.
1641
+ fn over_file() -> (Arc<Self>, Arc<Wrap<Self>>) {
1642
+ let counter = Arc::new(Self::default());
1643
+ let tmpfs: Tmpfs = [("file.txt", "granted")].into_iter().collect();
1644
+ (counter.clone(), Wrap::new(Arc::new(tmpfs), counter))
1008
1645
  }
1009
1646
 
1010
1647
  fn change(&self) {
@@ -1012,201 +1649,108 @@ impl ChangeCounter {
1012
1649
  }
1013
1650
  }
1014
1651
 
1015
- impl Filesystem for ChangeCounter {
1016
- holds_no_links!();
1017
- matches_names_exactly!();
1018
- never_repeats_identities!();
1019
- is_shared!();
1020
-
1021
- fn open(&self, path: &str, options: &OpenOptions) -> Result<Box<dyn File>, FilesystemError> {
1022
- self.memory.open(path, options)
1023
- }
1024
-
1025
- fn metadata(&self, path: &str) -> Result<Metadata, FilesystemError> {
1026
- self.memory.metadata(path)
1027
- }
1028
-
1029
- fn read_dir(&self, path: &str) -> Result<Vec<DirEntry>, FilesystemError> {
1030
- self.memory.read_dir(path)
1031
- }
1032
-
1033
- fn create_dir(&self, path: &str) -> Result<(), FilesystemError> {
1652
+ impl Hook for ChangeCounter {
1653
+ fn mkdir(&self, inner: &dyn InodeOperations, dentry: &Dentry) -> Result<(), Errno> {
1034
1654
  self.change();
1035
- self.memory.create_dir(path)
1655
+ inner.mkdir(dentry)
1036
1656
  }
1037
1657
 
1038
- fn remove_dir(&self, path: &str) -> Result<(), FilesystemError> {
1658
+ fn rmdir(&self, inner: &dyn InodeOperations, dentry: &Dentry) -> Result<(), Errno> {
1039
1659
  self.change();
1040
- self.memory.remove_dir(path)
1660
+ inner.rmdir(dentry)
1041
1661
  }
1042
1662
 
1043
- fn remove_file(&self, path: &str) -> Result<(), FilesystemError> {
1663
+ fn unlink(&self, inner: &dyn InodeOperations, dentry: &Dentry) -> Result<(), Errno> {
1044
1664
  self.change();
1045
- self.memory.remove_file(path)
1665
+ inner.unlink(dentry)
1046
1666
  }
1047
1667
 
1048
- fn rename(&self, from: &str, to: &str, rename: Rename) -> Result<(), FilesystemError> {
1668
+ fn rename(
1669
+ &self,
1670
+ inner: &dyn InodeOperations,
1671
+ old: &Dentry,
1672
+ new_dir: &dyn InodeOperations,
1673
+ new: &Dentry,
1674
+ flags: Option<RenameFlag>,
1675
+ ) -> Result<(), Errno> {
1049
1676
  self.change();
1050
- self.memory.rename(from, to, rename)
1051
- }
1052
- }
1053
-
1054
- /// A Memory holding `file.txt` that, as a rename reaches it, replaces the
1055
- /// file with a directory holding `secret`, as another invocation sharing
1056
- /// the Memory could between the runtime's checks and the move.
1057
- struct SwappedForADirectory(Memory);
1058
-
1059
- impl SwappedForADirectory {
1060
- fn new() -> Arc<Self> {
1061
- Arc::new(Self([("file.txt", "granted")].into_iter().collect()))
1062
- }
1063
- }
1064
-
1065
- impl Filesystem for SwappedForADirectory {
1066
- holds_no_links!();
1067
- matches_names_exactly!();
1068
- never_repeats_identities!();
1069
- is_shared!();
1070
-
1071
- fn open(&self, path: &str, options: &OpenOptions) -> Result<Box<dyn File>, FilesystemError> {
1072
- self.0.open(path, options)
1073
- }
1074
-
1075
- fn metadata(&self, path: &str) -> Result<Metadata, FilesystemError> {
1076
- self.0.metadata(path)
1077
- }
1078
-
1079
- fn read_dir(&self, path: &str) -> Result<Vec<DirEntry>, FilesystemError> {
1080
- self.0.read_dir(path)
1081
- }
1082
-
1083
- fn create_dir(&self, path: &str) -> Result<(), FilesystemError> {
1084
- self.0.create_dir(path)
1085
- }
1086
-
1087
- fn remove_dir(&self, path: &str) -> Result<(), FilesystemError> {
1088
- self.0.remove_dir(path)
1089
- }
1090
-
1091
- fn remove_file(&self, path: &str) -> Result<(), FilesystemError> {
1092
- self.0.remove_file(path)
1093
- }
1094
-
1095
- fn rename(&self, from: &str, to: &str, rename: Rename) -> Result<(), FilesystemError> {
1096
- self.0.remove_file(from)?;
1097
- self.0.create_dir(from)?;
1098
- drop(self.0.open(
1099
- &format!("{from}/secret"),
1100
- &build_options(|options| (options.write, options.create) = (true, true)),
1101
- )?);
1102
- self.0.rename(from, to, rename)
1677
+ inner.rename(old, new_dir, new, flags)
1103
1678
  }
1104
1679
  }
1105
1680
 
1106
1681
  // The Policy allows everything, so only the rename's own refusal of a
1107
- // directory, checked as the Filesystem moves it, keeps `secret` from
1108
- // taking a path the Policy never judged.
1682
+ // directory keeps `secret` from taking a path the Policy never judged.
1109
1683
  // @behavior RT-094
1110
1684
  #[test]
1111
1685
  fn a_directory_beneath_a_mount_with_a_policy_does_not_move() {
1112
- let swapped = SwappedForADirectory::new();
1113
- let policy: Arc<dyn Policy> = Arc::new(AllowsAll);
1114
- let mut guest = Guest::new(&[grant(swapped.clone(), Access::ReadWrite, Some(policy))]);
1686
+ let tmpfs = Arc::new([("dir/secret", "x")].into_iter().collect::<Tmpfs>());
1687
+ let policy: Arc<dyn for<'a> Policy<MountRequest<'a>>> = Arc::new(AllowsAll);
1688
+ let mut guest = Guest::new(&[grant(tmpfs.clone(), Access::ReadWrite, Some(policy))]);
1115
1689
  assert_eq!(
1116
1690
  (
1117
- guest.call_bare("rename_to_new"),
1118
- swapped.metadata("new.txt/secret")
1691
+ guest.call_pair("rename_paths", DIR, MOVED),
1692
+ vfs::vfs_fstatat(
1693
+ &prepare_creds(&[], None),
1694
+ &host(&tmpfs),
1695
+ "dir/secret",
1696
+ false
1697
+ )
1698
+ .map(|m| m.file_type)
1119
1699
  ),
1120
- (ERRNO_XDEV, Err(FilesystemError::NotFound)),
1121
- "path_rename of what is a directory by the time it moves, beneath a Mount with a \
1122
- Policy, through preview1 must answer EXDEV and move nothing"
1700
+ (ERRNO_XDEV, Ok(FileType::RegFile)),
1701
+ "path_rename of a directory beneath a Mount with a Policy through preview1 must \
1702
+ answer EXDEV and move nothing"
1123
1703
  );
1124
1704
  }
1125
1705
 
1126
- /// A Memory whose files take another writer's `bbb` at their end as one
1706
+ /// A Tmpfs whose files take another writer's `bbb` at their end as one
1127
1707
  /// is written, once the length the write would land at is known and
1128
1708
  /// before it lands, as another invocation sharing the file could.
1129
- struct AppendedMeanwhile(Memory);
1709
+ struct AppendedMeanwhile;
1130
1710
 
1131
1711
  struct AppendedMeanwhileFile {
1132
- file: Box<dyn File>,
1133
- other: std::sync::Mutex<Box<dyn File>>,
1712
+ file: Box<dyn FileOperations>,
1713
+ other: std::sync::Mutex<Box<dyn FileOperations>>,
1134
1714
  }
1135
1715
 
1136
1716
  impl AppendedMeanwhileFile {
1137
- fn other_appends(&self) -> Result<(), FilesystemError> {
1717
+ fn other_appends(&self) -> Result<(), Errno> {
1138
1718
  self.other
1139
1719
  .lock()
1140
1720
  .expect("the other writer's lock must not be poisoned")
1141
- .append(b"bbb")
1721
+ .write_iter(&mut Kiocb::new(0).with_append(), b"bbb")
1142
1722
  .map(drop)
1143
1723
  }
1144
1724
  }
1145
1725
 
1146
- impl File for AppendedMeanwhileFile {
1147
- fn read_at(&mut self, buf: &mut [u8], offset: u64) -> Result<usize, FilesystemError> {
1148
- self.file.read_at(buf, offset)
1726
+ impl FileOperations for AppendedMeanwhileFile {
1727
+ fn read_iter(&mut self, iocb: &mut Kiocb, buf: &mut [u8]) -> Result<usize, Errno> {
1728
+ self.file.read_iter(iocb, buf)
1149
1729
  }
1150
1730
 
1151
- fn write_at(&mut self, buf: &[u8], offset: u64) -> Result<usize, FilesystemError> {
1152
- self.file.write_at(buf, offset)
1153
- }
1154
-
1155
- /// The length is read before the other writer appends, so a write
1156
- /// placed by it lands over what the other wrote.
1157
- fn metadata(&self) -> Result<Metadata, FilesystemError> {
1158
- let metadata = self.file.metadata()?;
1159
- self.other_appends()?;
1160
- Ok(metadata)
1161
- }
1162
-
1163
- fn set_len(&mut self, len: u64) -> Result<(), FilesystemError> {
1164
- self.file.set_len(len)
1165
- }
1166
-
1167
- fn append(&mut self, buf: &[u8]) -> Result<(u64, usize), FilesystemError> {
1168
- self.other_appends()?;
1169
- self.file.append(buf)
1731
+ fn write_iter(&mut self, iocb: &mut Kiocb, buf: &[u8]) -> Result<usize, Errno> {
1732
+ if iocb.append {
1733
+ self.other_appends()?;
1734
+ }
1735
+ self.file.write_iter(iocb, buf)
1170
1736
  }
1171
1737
  }
1172
1738
 
1173
- impl Filesystem for AppendedMeanwhile {
1174
- holds_no_links!();
1175
- matches_names_exactly!();
1176
- never_repeats_identities!();
1177
- is_shared!();
1178
-
1179
- fn open(&self, path: &str, options: &OpenOptions) -> Result<Box<dyn File>, FilesystemError> {
1180
- let writes = build_options(|options| options.write = true);
1739
+ impl Hook for AppendedMeanwhile {
1740
+ fn open(
1741
+ &self,
1742
+ inner: &dyn InodeOperations,
1743
+ dentry: &Dentry,
1744
+ how: &OpenHow,
1745
+ ) -> Result<Box<dyn FileOperations>, Errno> {
1746
+ let writes = build_how(|how| how.write = true);
1747
+ let file = inner.open(dentry, how)?;
1748
+ let other = inner.open(dentry, &writes)?;
1181
1749
  Ok(Box::new(AppendedMeanwhileFile {
1182
- file: self.0.open(path, options)?,
1183
- other: std::sync::Mutex::new(self.0.open(path, &writes)?),
1750
+ file,
1751
+ other: std::sync::Mutex::new(other),
1184
1752
  }))
1185
1753
  }
1186
-
1187
- fn metadata(&self, path: &str) -> Result<Metadata, FilesystemError> {
1188
- self.0.metadata(path)
1189
- }
1190
-
1191
- fn read_dir(&self, path: &str) -> Result<Vec<DirEntry>, FilesystemError> {
1192
- self.0.read_dir(path)
1193
- }
1194
-
1195
- fn create_dir(&self, path: &str) -> Result<(), FilesystemError> {
1196
- self.0.create_dir(path)
1197
- }
1198
-
1199
- fn remove_dir(&self, path: &str) -> Result<(), FilesystemError> {
1200
- self.0.remove_dir(path)
1201
- }
1202
-
1203
- fn remove_file(&self, path: &str) -> Result<(), FilesystemError> {
1204
- self.0.remove_file(path)
1205
- }
1206
-
1207
- fn rename(&self, from: &str, to: &str, rename: Rename) -> Result<(), FilesystemError> {
1208
- self.0.rename(from, to, rename)
1209
- }
1210
1754
  }
1211
1755
 
1212
1756
  // The other writer's `bbb` lands as the guest's append is made, so only
@@ -1214,13 +1758,13 @@ impl Filesystem for AppendedMeanwhile {
1214
1758
  // @behavior RT-095
1215
1759
  #[test]
1216
1760
  fn an_append_lands_after_another_writers_append() {
1217
- let memory: Memory = [("file.txt", "granted")].into_iter().collect();
1218
- let shared = Arc::new(AppendedMeanwhile(memory));
1219
- let mut guest = Guest::new(&[grant(shared.clone(), Access::ReadWrite, None)]);
1761
+ let tmpfs = tmpfs_with("file.txt", "granted");
1762
+ let shared = Wrap::new(tmpfs.clone(), Arc::new(AppendedMeanwhile));
1763
+ let mut guest = Guest::new(&[grant(shared, Access::ReadWrite, None)]);
1220
1764
  assert_eq!(
1221
1765
  (
1222
1766
  guest.call("append_file", FILE),
1223
- contents(&shared.0, "file.txt")
1767
+ contents(&host(&tmpfs), "file.txt")
1224
1768
  ),
1225
1769
  (0, Some(b"grantedbbbhello".to_vec())),
1226
1770
  "fd_write to a file opened to append beneath a Mount through preview1 must land after \
@@ -1228,39 +1772,43 @@ fn an_append_lands_after_another_writers_append() {
1228
1772
  );
1229
1773
  }
1230
1774
 
1775
+ #[cfg(unix)]
1231
1776
  const FILETYPE_UNKNOWN: u8 = 0;
1777
+ #[cfg(unix)]
1232
1778
  const FILETYPE_DIRECTORY: u8 = 3;
1779
+ #[cfg(unix)]
1233
1780
  const FILETYPE_REGULAR_FILE: u8 = 4;
1781
+ #[cfg(unix)]
1234
1782
  const FILETYPE_SYMBOLIC_LINK: u8 = 7;
1235
1783
 
1236
1784
  /// A host directory of its own holding `file.txt` as a link to `target`,
1237
- /// made by `make_target`, and a guest handed it as a read-only Directory
1785
+ /// made by `make_target`, and a guest handed it as a read-only Bind
1238
1786
  /// Mount.
1239
1787
  #[cfg(unix)]
1240
- fn linked(name: &str, make_target: fn(&std::path::Path)) -> (std::path::PathBuf, Guest) {
1241
- linked_under(name, make_target, Access::Read, None)
1788
+ fn mount_link(name: &str, make_target: fn(&std::path::Path)) -> (std::path::PathBuf, Guest) {
1789
+ mount_link_under(name, make_target, Access::Read, None)
1242
1790
  }
1243
1791
 
1244
1792
  /// As `linked`, the Mount taking `access` and `policy`.
1245
1793
  #[cfg(unix)]
1246
- fn linked_under(
1794
+ fn mount_link_under(
1247
1795
  name: &str,
1248
1796
  make_target: fn(&std::path::Path),
1249
1797
  access: Access,
1250
- policy: Option<Arc<dyn Policy>>,
1798
+ policy: Option<Arc<dyn for<'a> Policy<MountRequest<'a>>>>,
1251
1799
  ) -> (std::path::PathBuf, Guest) {
1252
1800
  let host = std::env::temp_dir().join(format!("kobako-granted-{name}-{}", std::process::id()));
1253
1801
  let _ = std::fs::remove_dir_all(&host);
1254
1802
  std::fs::create_dir_all(&host).expect("the host directory must be created");
1255
1803
  make_target(&host.join("target"));
1256
1804
  std::os::unix::fs::symlink("target", host.join("file.txt")).expect("the link must be made");
1257
- let directory = Directory::new(&host).expect("the host directory must open");
1805
+ let directory = Bind::new(&host).expect("the host directory must open");
1258
1806
  let guest = Guest::new(&[grant(Arc::new(directory), access, policy)]);
1259
1807
  (host, guest)
1260
1808
  }
1261
1809
 
1262
1810
  /// What each stat of `path` with the given lookupflags answers, and the
1263
- /// filetype it wrote, beneath a Directory Mount whose host directory
1811
+ /// filetype it wrote, beneath a Bind Mount whose host directory
1264
1812
  /// holds `file.txt` as a link to `target`, made by `make_target`.
1265
1813
  #[cfg(unix)]
1266
1814
  fn stat_link(
@@ -1268,16 +1816,11 @@ fn stat_link(
1268
1816
  make_target: fn(&std::path::Path),
1269
1817
  stats: &[((i32, i32), i32)],
1270
1818
  ) -> Vec<(i32, u8)> {
1271
- let (host, mut guest) = linked(name, make_target);
1819
+ let (host, mut guest) = mount_link(name, make_target);
1272
1820
  let answers = stats
1273
1821
  .iter()
1274
1822
  .map(|&(path, flags)| {
1275
- let errno = guest
1276
- .instance
1277
- .get_typed_func::<(i32, i32, i32), i32>(&mut guest.store, "stat_flagged")
1278
- .expect("probe export must resolve")
1279
- .call(&mut guest.store, (path.0, path.1, flags))
1280
- .expect("probe call must not trap");
1823
+ let errno = guest.stat_flagged(path, flags);
1281
1824
  let memory = guest
1282
1825
  .instance
1283
1826
  .get_memory(&mut guest.store, "memory")
@@ -1303,14 +1846,9 @@ fn a_guest_sees_a_fifo_as_of_an_unknown_type_and_cannot_open_it() {
1303
1846
  .status()
1304
1847
  .expect("mkfifo must run");
1305
1848
  assert!(made.success(), "the FIFO must be made");
1306
- let directory = Directory::new(&host).expect("the host directory must open");
1849
+ let directory = Bind::new(&host).expect("the host directory must open");
1307
1850
  let mut guest = Guest::new(&[grant(Arc::new(directory), Access::Read, None)]);
1308
- let stat = guest
1309
- .instance
1310
- .get_typed_func::<(i32, i32, i32), i32>(&mut guest.store, "stat_flagged")
1311
- .expect("probe export must resolve")
1312
- .call(&mut guest.store, (FILE.0, FILE.1, 0))
1313
- .expect("probe call must not trap");
1851
+ let stat = guest.stat_flagged(FILE, 0);
1314
1852
  let filestat = guest
1315
1853
  .instance
1316
1854
  .get_memory(&mut guest.store, "memory")
@@ -1323,11 +1861,40 @@ fn a_guest_sees_a_fifo_as_of_an_unknown_type_and_cannot_open_it() {
1323
1861
  assert_eq!(
1324
1862
  (stat, filestat[16], nlink, opened),
1325
1863
  (0, FILETYPE_UNKNOWN, 1, ERRNO_ACCES),
1326
- "path_filestat_get of a FIFO beneath a Directory Mount through preview1 must report an \
1864
+ "path_filestat_get of a FIFO beneath a Bind Mount through preview1 must report an \
1327
1865
  unknown filetype named once, and path_open of it must answer EACCES"
1328
1866
  );
1329
1867
  }
1330
1868
 
1869
+ // Bound and never accepted, so an open reaching it would answer ENXIO rather
1870
+ // than the refusal asserted here.
1871
+ // @behavior RT-196
1872
+ #[cfg(unix)]
1873
+ #[test]
1874
+ fn a_guest_sees_a_socket_as_one_and_cannot_open_it() {
1875
+ let host = std::env::temp_dir().join(format!("kobako-granted-sock-{}", std::process::id()));
1876
+ let _ = std::fs::remove_dir_all(&host);
1877
+ std::fs::create_dir_all(&host).expect("the host directory must be created");
1878
+ let _socket = std::os::unix::net::UnixListener::bind(host.join("file.txt"))
1879
+ .expect("the socket must be bound");
1880
+ let directory = Bind::new(&host).expect("the host directory must open");
1881
+ let mut guest = Guest::new(&[grant(Arc::new(directory), Access::Read, None)]);
1882
+ let stat = guest.stat_flagged(FILE, 0);
1883
+ let filetype = guest
1884
+ .instance
1885
+ .get_memory(&mut guest.store, "memory")
1886
+ .expect("probe exports its memory")
1887
+ .data(&guest.store)[384 + 16];
1888
+ let opened = guest.call("read_file", FILE);
1889
+ let _ = std::fs::remove_dir_all(&host);
1890
+ assert_eq!(
1891
+ (stat, filetype, opened),
1892
+ (0, 6, ERRNO_ACCES),
1893
+ "path_filestat_get of a socket beneath a Bind Mount through preview1 must report a \
1894
+ stream socket, and path_open of it must answer EACCES"
1895
+ );
1896
+ }
1897
+
1331
1898
  // The link points at a regular file, so only a stat that follows none
1332
1899
  // can answer a link.
1333
1900
  // @behavior RT-097
@@ -1342,11 +1909,140 @@ fn a_stat_following_no_link_reports_the_link_itself() {
1342
1909
  assert_eq!(
1343
1910
  answers,
1344
1911
  [(0, FILETYPE_REGULAR_FILE), (0, FILETYPE_SYMBOLIC_LINK)],
1345
- "path_filestat_get of a host link beneath a Directory Mount through preview1 must report \
1912
+ "path_filestat_get of a host link beneath a Bind Mount through preview1 must report \
1346
1913
  the file it points to when following links, and a symbolic link when following none"
1347
1914
  );
1348
1915
  }
1349
1916
 
1917
+ // A host link reports the length of where it points, so only what the runtime
1918
+ // shows a guest keeps that length from it.
1919
+ // @behavior RT-173
1920
+ #[cfg(unix)]
1921
+ #[test]
1922
+ fn a_link_reports_no_size_however_its_filesystem_sizes_it() {
1923
+ let (host, mut guest) = mount_link("link-size", |target| {
1924
+ std::fs::write(target, "granted").expect("the host file must be written")
1925
+ });
1926
+ let answered = guest.stat_flagged(FILE, 0);
1927
+ let size = guest.stat_field(32);
1928
+ let _ = std::fs::remove_dir_all(&host);
1929
+ assert_eq!(
1930
+ (answered, size),
1931
+ (0, 0),
1932
+ "path_filestat_get following no link of a host link beneath a Bind Mount through \
1933
+ preview1 must report a size of zero"
1934
+ );
1935
+ }
1936
+
1937
+ /// One Tmpfs read-write, as an invocation on each profile is handed it.
1938
+ fn tmpfs_grant(tmpfs: &Arc<Tmpfs>) -> [Grant; 1] {
1939
+ [grant(tmpfs.clone(), Access::ReadWrite, None)]
1940
+ }
1941
+
1942
+ // @behavior RT-156
1943
+ #[test]
1944
+ fn the_permissive_profile_sees_the_times_a_filesystem_keeps() {
1945
+ let mut guest = Guest::for_profile(Profile::Permissive, &tmpfs_grant(&Arc::new(Tmpfs::new())));
1946
+ let before = SystemTime::now()
1947
+ .duration_since(UNIX_EPOCH)
1948
+ .expect("the host clock stands past the epoch")
1949
+ .as_nanos() as u64;
1950
+ assert_eq!(guest.call("write_file", FILE), 0, "the write must succeed");
1951
+ assert!(
1952
+ guest.times_of_path(FILE)[1] >= before,
1953
+ "path_filestat_get of a file written beneath a Mount through preview1 on the \
1954
+ permissive profile must report a modification time no earlier than the write"
1955
+ );
1956
+ }
1957
+
1958
+ // A Tmpfs records the host's real time, so only the profile's view turns it
1959
+ // into the epoch.
1960
+ // @behavior RT-157
1961
+ #[test]
1962
+ fn the_hermetic_profile_sees_every_time_at_the_unix_epoch() {
1963
+ let mut guest = Guest::for_profile(Profile::Hermetic, &tmpfs_grant(&Arc::new(Tmpfs::new())));
1964
+ assert_eq!(guest.call("write_file", FILE), 0, "the write must succeed");
1965
+ let path = guest.times_of_path(FILE);
1966
+ assert_eq!(guest.call("stat_opened", FILE), 0, "the stat must succeed");
1967
+ assert_eq!(
1968
+ (path, guest.stat_times()),
1969
+ ([0; 3], [0; 3]),
1970
+ "path_filestat_get and fd_filestat_get of a written file through preview1 on the \
1971
+ hermetic profile must report each time as the Unix epoch"
1972
+ );
1973
+ }
1974
+
1975
+ // @behavior RT-158
1976
+ #[test]
1977
+ fn a_time_another_profile_wrote_reaches_the_hermetic_profile_as_the_epoch() {
1978
+ let tmpfs = Arc::new(Tmpfs::new());
1979
+ let mut writer = Guest::for_profile(Profile::Permissive, &tmpfs_grant(&tmpfs));
1980
+ assert_eq!(writer.call("write_file", FILE), 0, "the write must succeed");
1981
+ let mut reader = Guest::for_profile(Profile::Hermetic, &tmpfs_grant(&tmpfs));
1982
+ assert_eq!(
1983
+ reader.times_of_path(FILE),
1984
+ [0; 3],
1985
+ "path_filestat_get through preview1 on the hermetic profile, of a file the permissive \
1986
+ profile wrote into the same Tmpfs, must report each time as the Unix epoch"
1987
+ );
1988
+ }
1989
+
1990
+ /// A Filesystem holding `file.txt`, modified in the year 2600, more
1991
+ /// nanoseconds after the epoch than a `u64` counts. A guest sets a time in
1992
+ /// those nanoseconds, so only a Filesystem of its own can report one.
1993
+ struct ModifiedIn2600;
1994
+
1995
+ impl ModifiedIn2600 {
1996
+ fn stat(path: &str) -> Option<Kstat> {
1997
+ let year_2600 = std::time::UNIX_EPOCH + std::time::Duration::from_secs(19_880_879_760);
1998
+ match path {
1999
+ "" => Some(Kstat::new(FileType::Dir, 0)),
2000
+ "file.txt" => {
2001
+ Some(Kstat::new(FileType::RegFile, 0).with_times(None, Some(year_2600), None))
2002
+ }
2003
+ _ => None,
2004
+ }
2005
+ }
2006
+ }
2007
+
2008
+ impl FileSystemType for ModifiedIn2600 {
2009
+ fn fill_super(self: Arc<Self>, sb: &mut Filesystem) -> Result<(), Errno> {
2010
+ sb.d_make_root(vfs::Inode::new(
2011
+ &vfs::Kstat::new(vfs::FileType::Dir, 0),
2012
+ self,
2013
+ ));
2014
+ Ok(())
2015
+ }
2016
+ }
2017
+
2018
+ impl InodeOperations for ModifiedIn2600 {
2019
+ fn getattr(&self, dentry: &Dentry) -> Result<Kstat, Errno> {
2020
+ Self::stat(&dentry.path_raw()[1..]).ok_or(Errno::NotFound)
2021
+ }
2022
+
2023
+ fn lookup(&self, dentry: &Dentry) -> Result<Lookup, Errno> {
2024
+ Ok(match Self::stat(&dentry.path_raw()[1..]) {
2025
+ Some(found) => Lookup::Found(Inode::new(&found, Arc::new(Self))),
2026
+ None => Lookup::Absent,
2027
+ })
2028
+ }
2029
+ }
2030
+
2031
+ // @behavior RT-404
2032
+ #[test]
2033
+ fn a_file_time_past_what_a_timestamp_holds_answers_overflow() {
2034
+ let mut guest = Guest::for_profile(
2035
+ Profile::Permissive,
2036
+ &[grant(Arc::new(ModifiedIn2600), Access::Read, None)],
2037
+ );
2038
+ assert_eq!(
2039
+ guest.stat_flagged(FILE, 0),
2040
+ ERRNO_OVERFLOW,
2041
+ "path_filestat_get through preview1 of a file its Filesystem reports modified in the \
2042
+ year 2600 must answer OVERFLOW, as wasmtime-wasi does"
2043
+ );
2044
+ }
2045
+
1350
2046
  // The stat follows no link, so only the trailing `/` can make it reach
1351
2047
  // the directory the link points at, as Linux's `lstat` does.
1352
2048
  // @behavior RT-098
@@ -1362,18 +2058,21 @@ fn a_stat_of_a_link_named_with_a_trailing_slash_reports_its_directory() {
1362
2058
  answers,
1363
2059
  [(0, FILETYPE_DIRECTORY), (0, FILETYPE_SYMBOLIC_LINK)],
1364
2060
  "path_filestat_get following no link of a host link to a directory, named with a \
1365
- trailing slash, beneath a Directory Mount through preview1 must report the directory, \
2061
+ trailing slash, beneath a Bind Mount through preview1 must report the directory, \
1366
2062
  and without the slash a symbolic link"
1367
2063
  );
1368
2064
  }
1369
2065
 
1370
2066
  /// What `path_unlink_file` and `path_rename` answer for the link
1371
- /// `file.txt/` to a directory beneath a read-write Directory Mount taking
2067
+ /// `file.txt/` to a directory beneath a read-write Bind Mount taking
1372
2068
  /// `policy`, and whether the link stays; `name` keeps its host directory
1373
2069
  /// its own.
1374
2070
  #[cfg(unix)]
1375
- fn change_link_named_as_directory(name: &str, policy: Option<Arc<dyn Policy>>) -> ([i32; 2], bool) {
1376
- let (host, mut guest) = linked_under(name, directory_with_key, Access::ReadWrite, policy);
2071
+ fn change_link_named_as_directory(
2072
+ name: &str,
2073
+ policy: Option<Arc<dyn for<'a> Policy<MountRequest<'a>>>>,
2074
+ ) -> ([i32; 2], bool) {
2075
+ let (host, mut guest) = mount_link_under(name, directory_with_key, Access::ReadWrite, policy);
1377
2076
  let answers = [
1378
2077
  guest.call("unlink_path", FILE_AS_DIRECTORY),
1379
2078
  guest.call_pair("rename_paths", FILE_AS_DIRECTORY, MOVED),
@@ -1397,7 +2096,7 @@ fn a_link_named_with_a_trailing_slash_is_neither_removed_nor_moved() {
1397
2096
  ],
1398
2097
  [([ERRNO_NOTDIR, ERRNO_NOTDIR], true); 2],
1399
2098
  "path_unlink_file and path_rename of a host link to a directory named with a trailing \
1400
- slash, beneath a read-write Directory Mount with or without a Policy through preview1, \
2099
+ slash, beneath a read-write Bind Mount with or without a Policy through preview1, \
1401
2100
  must answer ENOTDIR as Linux does and leave the link"
1402
2101
  );
1403
2102
  }
@@ -1416,7 +2115,7 @@ fn an_unlink_with_a_trailing_slash_answers_for_the_name_itself() {
1416
2115
  std::fs::create_dir_all(host.join("dir")).expect("the host directory must be created");
1417
2116
  std::fs::write(host.join("file.txt"), "granted").expect("the host file must be written");
1418
2117
  std::os::unix::fs::symlink("nowhere", host.join("gone")).expect("the link must be made");
1419
- let directory = Directory::new(&host).expect("the host directory must open");
2118
+ let directory = Bind::new(&host).expect("the host directory must open");
1420
2119
  let mut guest = Guest::new(&[grant(Arc::new(directory), Access::ReadWrite, None)]);
1421
2120
  let answers = [
1422
2121
  DIR_AS_DIRECTORY,
@@ -1434,22 +2133,117 @@ fn an_unlink_with_a_trailing_slash_answers_for_the_name_itself() {
1434
2133
  [true; 3]
1435
2134
  ),
1436
2135
  "path_unlink_file of a directory, a file, a link to nothing, and a missing name, each \
1437
- named with a trailing slash beneath a read-write Directory Mount through preview1, must \
2136
+ named with a trailing slash beneath a read-write Bind Mount through preview1, must \
1438
2137
  answer EISDIR, ENOTDIR, ENOTDIR, and ENOENT as Linux does and remove nothing"
1439
2138
  );
1440
2139
  }
1441
2140
 
2141
+ // @behavior RT-188
2142
+ #[test]
2143
+ fn a_name_no_filesystem_makes_is_answered_by_what_stands() {
2144
+ let tmpfs = tmpfs_with("file.txt", "granted");
2145
+ let mount = Mount::new(
2146
+ "/data",
2147
+ Filesystem::new(tmpfs.clone()).expect("the instance must stand"),
2148
+ Access::ReadWrite,
2149
+ )
2150
+ .expect("/data is a guest path");
2151
+ let root = vfs::Path::root(mount.mnt());
2152
+ let cred = prepare_creds(&[], None);
2153
+ let link = |old, new| vfs::filename_linkat(&cred, &root, old, &root, new, false);
2154
+ let symlink = |new| vfs::filename_symlinkat(&cred, "target", &root, new);
2155
+ let refused = Err;
2156
+ assert_eq!(
2157
+ (
2158
+ link("missing", "new"),
2159
+ link("file.txt", "file.txt"),
2160
+ link("file.txt", "new"),
2161
+ symlink("file.txt"),
2162
+ symlink("new"),
2163
+ ),
2164
+ (
2165
+ refused(Errno::NotFound),
2166
+ refused(Errno::AlreadyExists),
2167
+ refused(Errno::NotPermitted),
2168
+ refused(Errno::AlreadyExists),
2169
+ refused(Errno::NotPermitted),
2170
+ ),
2171
+ "vfs::filename_linkat and filename_symlinkat over a Filesystem making no links must \
2172
+ answer ENOENT for a missing source, EEXIST for a name that stands, and otherwise EPERM"
2173
+ );
2174
+ assert_eq!(
2175
+ host_entries(&tmpfs).expect("the root must list"),
2176
+ vec!["file.txt".to_string()],
2177
+ "a refused link must make nothing"
2178
+ );
2179
+ }
2180
+
2181
+ // Only Linux grows a file in one step, so a Bind elsewhere refuses and leaves it.
1442
2182
  // @behavior RT-099
2183
+ // @behavior RT-239
2184
+ #[test]
2185
+ fn an_allocation_grows_a_file_to_where_its_room_ends_and_shortens_none() {
2186
+ // What a file holds from where the room might start, and how long it is.
2187
+ let read = |bytes: Vec<u8>| (bytes.len(), bytes.get(7).copied());
2188
+ let long = "x".repeat(200);
2189
+ let through_tmpfs = |seed: &str| {
2190
+ let tmpfs = tmpfs_with("file.txt", seed);
2191
+ let answer = Guest::new(&[grant(tmpfs.clone(), Access::ReadWrite, None)])
2192
+ .call("allocate_file", FILE);
2193
+ let len = vfs::vfs_fstatat(&prepare_creds(&[], None), &host(&tmpfs), "file.txt", false)
2194
+ .map(|stat| stat.size);
2195
+ let held = contents(&host(&tmpfs), "file.txt").map(|head| head[7]);
2196
+ (answer, len.ok().map(|len| len as usize), held)
2197
+ };
2198
+ let through_bind = |seed: &str| {
2199
+ let dir = std::env::temp_dir().join(format!("kobako-allocate-{}", std::process::id()));
2200
+ let _ = std::fs::remove_dir_all(&dir);
2201
+ std::fs::create_dir_all(&dir).expect("the host directory must be created");
2202
+ std::fs::write(dir.join("file.txt"), seed).expect("the host file must be written");
2203
+ let bind = Bind::new(&dir).expect("the host directory must open");
2204
+ let answer = Guest::new(&[grant(Arc::new(bind), Access::ReadWrite, None)])
2205
+ .call("allocate_file", FILE);
2206
+ let (len, held) = read(std::fs::read(dir.join("file.txt")).expect("the file stands"));
2207
+ let _ = std::fs::remove_dir_all(&dir);
2208
+ (answer, Some(len), held)
2209
+ };
2210
+ let bind_answers = match cfg!(target_os = "linux") {
2211
+ true => [(0, Some(100), Some(0)), (0, Some(200), Some(b'x'))],
2212
+ false => [
2213
+ (ERRNO_NOTSUP, Some(7), None),
2214
+ (ERRNO_NOTSUP, Some(200), Some(b'x')),
2215
+ ],
2216
+ };
2217
+ assert_eq!(
2218
+ (
2219
+ [through_tmpfs("granted"), through_tmpfs(&long)],
2220
+ [through_bind("granted"), through_bind(&long)],
2221
+ ),
2222
+ (
2223
+ [(0, Some(100), Some(0)), (0, Some(200), Some(b'x'))],
2224
+ bind_answers,
2225
+ ),
2226
+ "fd_allocate of 100 bytes from the start through preview1, over a Tmpfs and a Bind on \
2227
+ Linux, must grow a shorter file with zeros and leave a longer one as it was, and over a \
2228
+ Bind elsewhere answer ENOTSUP and leave both"
2229
+ );
2230
+ }
2231
+
2232
+ // Linux counts room reserved in `i_blocks` against the tmpfs's size, and a
2233
+ // Tmpfs holds every byte up to a file's end, so its budget refuses the growth.
2234
+ // @behavior RT-238
1443
2235
  #[test]
1444
- fn an_allocation_for_a_file_beneath_a_mount_is_unsupported() {
1445
- let memory: Arc<Memory> = Arc::new([("file.txt", "granted")].into_iter().collect());
1446
- let answer =
1447
- Guest::new(&[grant(memory.clone(), Access::ReadWrite, None)]).call("allocate_file", FILE);
2236
+ fn an_allocation_past_a_tmpfs_size_answers_enospc() {
2237
+ let tmpfs: Tmpfs = [("file.txt", "x")].into_iter().collect();
2238
+ let answer = Guest::new(&[grant(
2239
+ Arc::new(tmpfs.with_size(Some(50))),
2240
+ Access::ReadWrite,
2241
+ None,
2242
+ )])
2243
+ .call("allocate_file", FILE);
1448
2244
  assert_eq!(
1449
- (answer, contents(memory.as_ref(), "file.txt")),
1450
- (ERRNO_NOTSUP, Some(b"granted".to_vec())),
1451
- "fd_allocate of a file beneath a read-write Mount through preview1 must answer ENOTSUP \
1452
- as wasmtime-wasi does, leaving the file as it was"
2245
+ answer, ERRNO_NOSPC,
2246
+ "fd_allocate of 100 bytes in a Tmpfs of 50 through preview1 must answer ENOSPC"
1453
2247
  );
1454
2248
  }
1455
2249
 
@@ -1459,7 +2253,7 @@ fn an_allocation_for_a_file_beneath_a_mount_is_unsupported() {
1459
2253
  #[cfg(unix)]
1460
2254
  #[test]
1461
2255
  fn an_open_following_no_link_refuses_a_link_to_a_directory() {
1462
- let (host, mut guest) = linked("open-nofollow", |target| {
2256
+ let (host, mut guest) = mount_link("open-nofollow", |target| {
1463
2257
  std::fs::create_dir(target).expect("the host directory must be created")
1464
2258
  });
1465
2259
  let answers = [
@@ -1470,7 +2264,7 @@ fn an_open_following_no_link_refuses_a_link_to_a_directory() {
1470
2264
  assert_eq!(
1471
2265
  answers,
1472
2266
  [ERRNO_LOOP, 0],
1473
- "path_open following no link of a host link to a directory beneath a Directory Mount \
2267
+ "path_open following no link of a host link to a directory beneath a Bind Mount \
1474
2268
  through preview1 must answer ELOOP, and with a trailing slash open the directory"
1475
2269
  );
1476
2270
  }
@@ -1482,27 +2276,33 @@ fn directory_with_key(target: &std::path::Path) {
1482
2276
  std::fs::write(target.join("key"), "secret").expect("the host file must be written");
1483
2277
  }
1484
2278
 
1485
- // The Policy allows everything, so only the link on the way can refuse
1486
- // these; the same calls beneath a Mount without a Policy go through.
2279
+ // The link itself is allowed; only judging where it leads refuses the key, so
2280
+ // a walk that took the link's own path for the answer would hand it over.
1487
2281
  // @behavior RT-101
1488
2282
  #[cfg(unix)]
1489
2283
  #[test]
1490
- fn a_path_through_a_link_beneath_a_mount_with_a_policy_answers_eloop() {
1491
- let policy: Arc<dyn Policy> = Arc::new(AllowsAll);
1492
- let (host, mut guest) = linked_under(
1493
- "policy-link",
2284
+ fn a_path_through_a_link_beneath_a_mount_with_a_policy_is_judged_where_it_leads() {
2285
+ let refuses_key: Arc<dyn for<'a> Policy<MountRequest<'a>>> =
2286
+ Arc::new(Refuses("/data/target/key"));
2287
+ let (host, mut guest) = mount_link_under(
2288
+ "policy-link-refused",
1494
2289
  directory_with_key,
1495
2290
  Access::ReadWrite,
1496
- Some(policy),
2291
+ Some(refuses_key),
1497
2292
  );
1498
2293
  let refused = [
1499
2294
  guest.call("read_file", THROUGH_FILE),
1500
2295
  guest.call("unlink_path", THROUGH_FILE),
1501
- guest.call("open_following", FILE),
1502
2296
  ];
1503
2297
  let kept = host.join("target/key").exists();
1504
2298
  let _ = std::fs::remove_dir_all(&host);
1505
- let (host, mut guest) = linked_under("plain-link", directory_with_key, Access::Read, None);
2299
+ let allows: Arc<dyn for<'a> Policy<MountRequest<'a>>> = Arc::new(AllowsAll);
2300
+ let (host, mut guest) = mount_link_under(
2301
+ "policy-link-allowed",
2302
+ directory_with_key,
2303
+ Access::ReadWrite,
2304
+ Some(allows),
2305
+ );
1506
2306
  let followed = [
1507
2307
  guest.call("read_file", THROUGH_FILE),
1508
2308
  guest.call("open_following", FILE),
@@ -1510,21 +2310,20 @@ fn a_path_through_a_link_beneath_a_mount_with_a_policy_answers_eloop() {
1510
2310
  let _ = std::fs::remove_dir_all(&host);
1511
2311
  assert_eq!(
1512
2312
  (refused, kept, followed),
1513
- ([ERRNO_LOOP; 3], true, [0, 0]),
1514
- "path_open and path_unlink_file through a host link, or path_open following one at the \
1515
- end, beneath a Mount with a Policy through preview1 must answer ELOOP and change \
1516
- nothing, while a Mount without a Policy follows the link"
2313
+ ([ERRNO_ACCES; 2], true, [0, 0]),
2314
+ "path_open and path_unlink_file through a host link beneath a Mount with a Policy \
2315
+ through preview1 must answer what the Policy says of where the link leads, EACCES \
2316
+ for a refused path, changing nothing, and follow it to an allowed one"
1517
2317
  );
1518
2318
  }
1519
2319
 
1520
- // cap-std refuses to follow a link out of the host directory, and the
1521
- // host refuses a loop, so each open is refused whichever answers first;
1522
- // only ELOOP says the link is why. An unlink acts on the link itself,
1523
- // which no Policy-free walk past it is needed for.
2320
+ // A Policy changes nothing of where a link may lead: one out of the Bind escapes
2321
+ // it and one into itself loops, as beneath a Mount without a Policy, and an unlink
2322
+ // acts on the link itself.
1524
2323
  // @behavior RT-125
1525
2324
  #[cfg(unix)]
1526
2325
  #[test]
1527
- fn a_link_out_of_a_directory_or_into_a_loop_answers_eloop_beneath_a_policy() {
2326
+ fn a_link_out_of_a_directory_or_into_a_loop_answers_as_without_a_policy() {
1528
2327
  let outside = std::env::temp_dir().join(format!("kobako-outside-{}", std::process::id()));
1529
2328
  directory_with_key(&outside);
1530
2329
  let targets = [
@@ -1544,8 +2343,8 @@ fn a_link_out_of_a_directory_or_into_a_loop_answers_eloop_beneath_a_policy() {
1544
2343
  std::fs::create_dir_all(&host).expect("the host directory must be created");
1545
2344
  std::os::unix::fs::symlink(target, host.join("file.txt"))
1546
2345
  .expect("the link must be made");
1547
- let directory = Directory::new(&host).expect("the host directory must open");
1548
- let policy: Arc<dyn Policy> = Arc::new(AllowsAll);
2346
+ let directory = Bind::new(&host).expect("the host directory must open");
2347
+ let policy: Arc<dyn for<'a> Policy<MountRequest<'a>>> = Arc::new(AllowsAll);
1549
2348
  let mut guest =
1550
2349
  Guest::new(&[grant(Arc::new(directory), Access::ReadWrite, Some(policy))]);
1551
2350
  let answers = [
@@ -1561,90 +2360,56 @@ fn a_link_out_of_a_directory_or_into_a_loop_answers_eloop_beneath_a_policy() {
1561
2360
  let _ = std::fs::remove_dir_all(&outside);
1562
2361
  assert_eq!(
1563
2362
  (answers, kept),
1564
- (vec![([ERRNO_LOOP, 0], true); 3], true),
1565
- "path_open through a host link out of a Directory, by an absolute or a relative target, \
1566
- or into a loop, beneath a Mount with a Policy through preview1 must answer ELOOP, and \
1567
- path_unlink_file of each link must remove it"
1568
- );
1569
- }
1570
-
1571
- // The Filesystem fails only the lookup of `dir`, which the open needs
1572
- // no answer from but the walk for links on its way does.
1573
- // @behavior RT-126
1574
- #[test]
1575
- fn a_link_check_that_fails_fails_the_call_beneath_a_policy() {
1576
- let failing = Arc::new(FailsLookingUpDir(
1577
- [("dir/file.txt", "granted")].into_iter().collect(),
1578
- ));
1579
- let policy: Arc<dyn Policy> = Arc::new(AllowsAll);
1580
- let mut guest = Guest::new(&[grant(failing, Access::Read, Some(policy))]);
1581
- assert_eq!(
1582
- guest.call("read_file", DIR_FILE),
1583
- ERRNO_IO,
1584
- "path_open of a file beneath a directory the Filesystem fails to look up, beneath a \
1585
- Mount with a Policy through preview1, must answer that failure"
1586
- );
1587
- }
1588
-
1589
- /// A Memory failing every lookup of `dir` itself, as a host directory
1590
- /// that cannot be read could.
1591
- struct FailsLookingUpDir(Memory);
1592
-
1593
- impl Filesystem for FailsLookingUpDir {
1594
- matches_names_exactly!();
1595
- never_repeats_identities!();
1596
- is_shared!();
1597
-
1598
- fn open(&self, path: &str, options: &OpenOptions) -> Result<Box<dyn File>, FilesystemError> {
1599
- self.0.open(path, options)
1600
- }
1601
-
1602
- fn metadata(&self, path: &str) -> Result<Metadata, FilesystemError> {
1603
- self.0.metadata(path)
1604
- }
1605
-
1606
- fn symlink_metadata(&self, path: &str) -> Result<Metadata, FilesystemError> {
1607
- match path {
1608
- "dir" => Err(FilesystemError::Other("unreadable".into())),
1609
- path => self.0.symlink_metadata(path),
1610
- }
1611
- }
1612
-
1613
- fn canonicalize_beneath(&self, base: &str, path: &str) -> Result<String, FilesystemError> {
1614
- self.0.canonicalize_beneath(base, path)
1615
- }
1616
-
1617
- fn for_policy(&self) -> Option<Arc<dyn Filesystem>> {
1618
- None
1619
- }
1620
-
1621
- fn read_dir(&self, path: &str) -> Result<Vec<DirEntry>, FilesystemError> {
1622
- self.0.read_dir(path)
1623
- }
1624
-
1625
- fn create_dir(&self, path: &str) -> Result<(), FilesystemError> {
1626
- self.0.create_dir(path)
1627
- }
2363
+ (
2364
+ vec![
2365
+ ([ERRNO_NOTCAPABLE, 0], true),
2366
+ ([ERRNO_NOTCAPABLE, 0], true),
2367
+ ([ERRNO_LOOP, 0], true),
2368
+ ],
2369
+ true
2370
+ ),
2371
+ "path_open through a host link out of a Bind, by an absolute or a relative target, \
2372
+ beneath a Mount with a Policy through preview1 must answer NOTCAPABLE, into a loop \
2373
+ ELOOP, and path_unlink_file of each link must remove it"
2374
+ );
2375
+ }
1628
2376
 
1629
- fn remove_dir(&self, path: &str) -> Result<(), FilesystemError> {
1630
- self.0.remove_dir(path)
1631
- }
2377
+ // The Filesystem fails only the lookup of `dir`, which the open needs no answer
2378
+ // from but the walk on its way does.
2379
+ // @behavior RT-126
2380
+ #[test]
2381
+ fn a_lookup_that_fails_fails_the_call_beneath_a_policy() {
2382
+ let tmpfs: Tmpfs = [("dir/file.txt", "granted")].into_iter().collect();
2383
+ let failing = Wrap::new(Arc::new(tmpfs), Arc::new(FailsLookingUpDir));
2384
+ let policy: Arc<dyn for<'a> Policy<MountRequest<'a>>> = Arc::new(AllowsAll);
2385
+ let mut guest = Guest::new(&[grant(failing, Access::Read, Some(policy))]);
2386
+ assert_eq!(
2387
+ guest.call("read_file", DIR_FILE),
2388
+ ERRNO_IO,
2389
+ "path_open of a file beneath a directory the Filesystem fails to look up, beneath a \
2390
+ Mount with a Policy through preview1, must answer that failure"
2391
+ );
2392
+ }
1632
2393
 
1633
- fn remove_file(&self, path: &str) -> Result<(), FilesystemError> {
1634
- self.0.remove_file(path)
1635
- }
2394
+ /// A Tmpfs failing every lookup of `dir` itself, as a host directory
2395
+ /// that cannot be read could.
2396
+ struct FailsLookingUpDir;
1636
2397
 
1637
- fn rename(&self, from: &str, to: &str, rename: Rename) -> Result<(), FilesystemError> {
1638
- self.0.rename(from, to, rename)
2398
+ impl Hook for FailsLookingUpDir {
2399
+ fn lookup(&self, inner: &dyn InodeOperations, dentry: &Dentry) -> Result<Lookup, Errno> {
2400
+ match dentry.name().as_str() {
2401
+ "dir" => Err(Errno::Other("unreadable".into())),
2402
+ _ => inner.lookup(dentry),
2403
+ }
1639
2404
  }
1640
2405
  }
1641
2406
 
1642
- // The Mount has no Policy and follows links, so only the step out of
1643
- // the link can refuse these.
2407
+ // Each path lands on what the link's target or its parent holds, so only a
2408
+ // walk taking `.` and `..` from where the link led answers.
1644
2409
  // @behavior RT-119
1645
2410
  #[cfg(unix)]
1646
2411
  #[test]
1647
- fn a_step_out_of_a_link_answers_eloop() {
2412
+ fn a_step_out_of_a_link_lands_where_it_leads() {
1648
2413
  assert_eq!(
1649
2414
  stat_link(
1650
2415
  "dot-link",
@@ -1654,13 +2419,18 @@ fn a_step_out_of_a_link_answers_eloop() {
1654
2419
  .into_iter()
1655
2420
  .map(|(errno, _)| errno)
1656
2421
  .collect::<Vec<_>>(),
1657
- [ERRNO_LOOP; 2],
2422
+ [0; 2],
1658
2423
  "path_filestat_get of `file.txt/.` and `file.txt/../file.txt`, where `file.txt` is a \
1659
- host link to a directory, beneath a Directory Mount through preview1 must answer ELOOP"
2424
+ host link to a directory, beneath a Bind Mount through preview1 must answer what they \
2425
+ lead to, as Linux's walk does"
1660
2426
  );
1661
2427
  }
1662
2428
 
1663
- fn file_and_directory() -> Arc<Memory> {
2429
+ fn tmpfs_with(path: &str, contents: &str) -> Arc<Tmpfs> {
2430
+ Arc::new([(path, contents)].into_iter().collect())
2431
+ }
2432
+
2433
+ fn file_and_directory() -> Arc<Tmpfs> {
1664
2434
  Arc::new(
1665
2435
  [("file.txt", "granted"), ("dir/inner", "x")]
1666
2436
  .into_iter()
@@ -1668,19 +2438,53 @@ fn file_and_directory() -> Arc<Memory> {
1668
2438
  )
1669
2439
  }
1670
2440
 
2441
+ /// A security module refusing every directory made.
2442
+ struct RefusesMkdir;
2443
+
2444
+ impl SecurityOperations for RefusesMkdir {
2445
+ fn path_mkdir(&self, _path: SecurityPath<'_>) -> Result<(), Errno> {
2446
+ Err(Errno::PermissionDenied)
2447
+ }
2448
+ }
2449
+
2450
+ // The Mount allows every change and has no Policy, so only the module the
2451
+ // Driver was built with refuses the make.
2452
+ // @behavior RT-329
2453
+ #[test]
2454
+ fn a_security_module_the_driver_was_built_with_judges_the_guest() {
2455
+ let tmpfs = file_and_directory();
2456
+ let mut guest = Guest::with_security(
2457
+ vec![Arc::new(RefusesMkdir)],
2458
+ &[grant(tmpfs.clone(), Access::ReadWrite, None)],
2459
+ );
2460
+ assert_eq!(
2461
+ (
2462
+ guest.call("make_dir", NEW_AS_DIRECTORY),
2463
+ vfs::vfs_fstatat(&prepare_creds(&[], None), &host(&tmpfs), "new.txt", false).is_err()
2464
+ ),
2465
+ (ERRNO_ACCES, true),
2466
+ "path_create_directory beneath a Mount through preview1, the Driver built with a \
2467
+ security module refusing it, must answer EACCES and make nothing, as an LSM stacked \
2468
+ at boot refuses security_path_mkdir"
2469
+ );
2470
+ }
2471
+
1671
2472
  // A `.` after a name resolves through it, so Linux and macOS both refuse
1672
2473
  // `missing/.` at the missing name rather than make it.
1673
2474
  // @behavior RT-109
1674
2475
  #[test]
1675
2476
  fn a_path_ending_in_a_dot_makes_nothing_where_no_directory_stands() {
1676
- let memory = file_and_directory();
1677
- let mut guest = Guest::new(&[grant(memory.clone(), Access::ReadWrite, None)]);
2477
+ let tmpfs = file_and_directory();
2478
+ let mut guest = Guest::new(&[grant(tmpfs.clone(), Access::ReadWrite, None)]);
1678
2479
  let answers = [
1679
2480
  guest.call("make_dir", MISSING_DOT),
1680
2481
  guest.call_flagged(MISSING_DOT, OFLAGS_CREAT, 0),
1681
2482
  ];
1682
2483
  assert_eq!(
1683
- (answers, memory.metadata("missing").is_err()),
2484
+ (
2485
+ answers,
2486
+ vfs::vfs_fstatat(&prepare_creds(&[], None), &host(&tmpfs), "missing", false).is_err()
2487
+ ),
1684
2488
  ([ERRNO_NOENT, ERRNO_NOENT], true),
1685
2489
  "path_create_directory and path_open with O_CREAT of missing/. beneath a Mount through \
1686
2490
  preview1 must answer ENOENT, as Linux does, and make nothing named missing"
@@ -1692,8 +2496,8 @@ fn a_path_ending_in_a_dot_makes_nothing_where_no_directory_stands() {
1692
2496
  // @behavior RT-102
1693
2497
  #[test]
1694
2498
  fn a_path_ending_in_a_dot_is_neither_removed_nor_moved() {
1695
- let memory = file_and_directory();
1696
- let mut guest = Guest::new(&[grant(memory.clone(), Access::ReadWrite, None)]);
2499
+ let tmpfs = file_and_directory();
2500
+ let mut guest = Guest::new(&[grant(tmpfs.clone(), Access::ReadWrite, None)]);
1697
2501
  let answers = [
1698
2502
  guest.call("remove_path", DIR_DOT),
1699
2503
  guest.call("remove_path", DIR_DOT_DOT),
@@ -1703,11 +2507,14 @@ fn a_path_ending_in_a_dot_is_neither_removed_nor_moved() {
1703
2507
  guest.call_pair("rename_paths", OUT_OF_FILE, MOVED),
1704
2508
  ];
1705
2509
  assert_eq!(
1706
- (answers, memory.metadata("dir/inner").is_ok()),
2510
+ (
2511
+ answers,
2512
+ vfs::vfs_fstatat(&prepare_creds(&[], None), &host(&tmpfs), "dir/inner", false).is_ok()
2513
+ ),
1707
2514
  (
1708
2515
  [
1709
2516
  ERRNO_INVAL,
1710
- ERRNO_INVAL,
2517
+ ERRNO_NOTEMPTY,
1711
2518
  ERRNO_BUSY,
1712
2519
  ERRNO_BUSY,
1713
2520
  ERRNO_NOTDIR,
@@ -1716,8 +2523,9 @@ fn a_path_ending_in_a_dot_is_neither_removed_nor_moved() {
1716
2523
  true
1717
2524
  ),
1718
2525
  "path_remove_directory of a path ending in . or .., and path_rename of one, beneath a \
1719
- Mount through preview1 must answer EINVAL and EBUSY as wasmtime-wasi does, or ENOTDIR \
1720
- where a file stands before the dot, and leave the directory in place"
2526
+ Mount through preview1 must answer EINVAL for . and ENOTEMPTY for .. and EBUSY, as \
2527
+ Linux does, or ENOTDIR where a file stands before the dot, and leave the directory in \
2528
+ place"
1721
2529
  );
1722
2530
  }
1723
2531
 
@@ -1755,7 +2563,7 @@ fn a_create_of_a_host_file_that_only_reads_opens_it() {
1755
2563
  std::fs::Permissions::from_mode(0o444),
1756
2564
  )
1757
2565
  .expect("the host file must become read-only");
1758
- let directory = Directory::new(&host).expect("the host directory must open");
2566
+ let directory = Bind::new(&host).expect("the host directory must open");
1759
2567
  let answer = Guest::new(&[grant(Arc::new(directory), Access::ReadWrite, None)]).call_flagged(
1760
2568
  FILE,
1761
2569
  OFLAGS_CREAT,
@@ -1764,26 +2572,173 @@ fn a_create_of_a_host_file_that_only_reads_opens_it() {
1764
2572
  let _ = std::fs::remove_dir_all(&host);
1765
2573
  assert_eq!(
1766
2574
  answer, 0,
1767
- "path_open with O_CREAT and no write of a read-only host file beneath a Directory Mount \
2575
+ "path_open with O_CREAT and no write of a read-only host file beneath a Bind Mount \
1768
2576
  through preview1 must open it"
1769
2577
  );
1770
2578
  }
1771
2579
 
2580
+ /// A host directory of the test's own beneath a read-write Bind Mount,
2581
+ /// `dir` a link to the directory `real` and `gone` a link to nothing,
2582
+ /// removed when it drops.
2583
+ #[cfg(unix)]
2584
+ struct LinkedHost(std::path::PathBuf);
2585
+
2586
+ #[cfg(unix)]
2587
+ impl LinkedHost {
2588
+ fn new(name: &str) -> Self {
2589
+ let host = std::env::temp_dir().join(format!("kobako-{name}-{}", std::process::id()));
2590
+ let _ = std::fs::remove_dir_all(&host);
2591
+ std::fs::create_dir_all(host.join("real/inner")).expect("the host tree must be made");
2592
+ std::os::unix::fs::symlink("real", host.join("dir")).expect("the link must be made");
2593
+ std::os::unix::fs::symlink("nowhere", host.join("gone")).expect("the link must be made");
2594
+ Self(host)
2595
+ }
2596
+
2597
+ fn guest(&self) -> Guest {
2598
+ let directory = Bind::new(&self.0).expect("the host directory must open");
2599
+ Guest::new(&[grant(Arc::new(directory), Access::ReadWrite, None)])
2600
+ }
2601
+ }
2602
+
2603
+ #[cfg(unix)]
2604
+ impl Drop for LinkedHost {
2605
+ fn drop(&mut self) {
2606
+ let _ = std::fs::remove_dir_all(&self.0);
2607
+ }
2608
+ }
2609
+
2610
+ // The link stands before the dot, so it is followed as Linux follows a
2611
+ // link that is not the last name, and the dot answers as one through a
2612
+ // directory does.
2613
+ // @behavior RT-161
2614
+ #[cfg(unix)]
2615
+ #[test]
2616
+ fn a_path_ending_in_a_dot_through_a_link_is_neither_removed_nor_moved() {
2617
+ let host = LinkedHost::new("dot-link");
2618
+ let mut guest = host.guest();
2619
+ let answers = [
2620
+ guest.call("remove_path", DIR_DOT),
2621
+ guest.call("remove_path", DIR_DOT_DOT),
2622
+ guest.call_pair("rename_paths", DIR_DOT, MOVED),
2623
+ guest.call_pair("rename_paths", DIR_DOT_DOT, MOVED),
2624
+ ];
2625
+ assert_eq!(
2626
+ (answers, host.0.join("real/inner").is_dir()),
2627
+ ([ERRNO_INVAL, ERRNO_NOTEMPTY, ERRNO_BUSY, ERRNO_BUSY], true),
2628
+ "path_remove_directory and path_rename of dir/. and dir/.., dir a host link to a \
2629
+ directory beneath a Bind Mount, through preview1 must answer EINVAL, ENOTEMPTY, and \
2630
+ EBUSY, as Linux does, and leave the directory"
2631
+ );
2632
+ }
2633
+
2634
+ // The dot is the last name, which these act on rather than land on, so
2635
+ // nothing of where the link points shows, and the answers are Linux's.
2636
+ // @behavior RT-219
2637
+ #[cfg(unix)]
2638
+ #[test]
2639
+ fn a_change_naming_a_dot_through_a_link_answers_as_linux() {
2640
+ let host = LinkedHost::new("dot-change");
2641
+ let mut guest = host.guest();
2642
+ assert_eq!(
2643
+ (
2644
+ guest.call("make_dir", DIR_DOT),
2645
+ guest.call("unlink_path", DIR_DOT),
2646
+ host.0.join("real/inner").is_dir()
2647
+ ),
2648
+ (ERRNO_EXIST, ERRNO_ISDIR, true),
2649
+ "path_create_directory and path_unlink_file of dir/., dir a host link to a directory \
2650
+ beneath a Bind Mount, through preview1 must answer EEXIST and EISDIR, as Linux does, \
2651
+ and leave the directory"
2652
+ );
2653
+ }
2654
+
2655
+ /// The root of `host` beneath a Bind Mount, as the VFS walks it.
2656
+ #[cfg(unix)]
2657
+ fn bind_root(host: &std::path::Path) -> Path {
2658
+ let directory = Bind::new(host).expect("the host directory must open");
2659
+ let mount = Mount::new(
2660
+ "/data",
2661
+ Filesystem::new(directory).expect("the instance must stand"),
2662
+ Access::ReadWrite,
2663
+ )
2664
+ .expect("/data is a guest path");
2665
+ Path::root(mount.mnt())
2666
+ }
2667
+
2668
+ // No security module is registered, so were the link followed the file would
2669
+ // be made where it points, and only `O_EXCL` keeps that from happening.
2670
+ // @behavior RT-220
2671
+ #[cfg(unix)]
2672
+ #[test]
2673
+ fn an_exclusive_create_follows_no_link_at_the_end() {
2674
+ let host = LinkedHost::new("excl-link");
2675
+ let mut how = OpenHow::default();
2676
+ how.write = true;
2677
+ how.create = true;
2678
+ how.exclusive = true;
2679
+ how.follow = true;
2680
+ let answer = vfs::do_file_open(
2681
+ &prepare_creds(&[], None),
2682
+ &bind_root(&host.0),
2683
+ "gone",
2684
+ &flags_of(&how),
2685
+ );
2686
+ assert_eq!(
2687
+ (answer.err(), host.0.join("nowhere").exists()),
2688
+ (Some(Errno::AlreadyExists), false),
2689
+ "vfs::do_file_open with create and exclusive of a link to nothing, asking to follow it, \
2690
+ must answer EEXIST, as Linux's O_EXCL does, and make nothing"
2691
+ );
2692
+ }
2693
+
2694
+ // The trailing `/` follows the link, so what is read stands at the directory,
2695
+ // where the walk that reports a link as itself would answer ENOTDIR.
2696
+ // @behavior RT-221
2697
+ #[cfg(unix)]
2698
+ #[test]
2699
+ fn a_trailing_slash_on_a_link_to_a_directory_reads_no_link() {
2700
+ let host = LinkedHost::new("readlink-slash");
2701
+ assert_eq!(
2702
+ vfs::do_readlinkat(&prepare_creds(&[], None), &bind_root(&host.0), "dir/").err(),
2703
+ Some(Errno::InvalidInput),
2704
+ "vfs::do_readlinkat of dir/, dir a host link to a directory beneath a Bind Mount, must \
2705
+ answer EINVAL, as Linux's does"
2706
+ );
2707
+ }
2708
+
2709
+ // Linux answers the trailing slash of a create before it would follow the
2710
+ // link, which points at nothing a create could make.
2711
+ // @behavior RT-162
2712
+ #[cfg(unix)]
2713
+ #[test]
2714
+ fn a_create_through_a_trailing_slash_answers_eisdir_before_following_a_link() {
2715
+ let host = LinkedHost::new("slash-link");
2716
+ let answer = host
2717
+ .guest()
2718
+ .call_flagged(GONE_AS_DIRECTORY, OFLAGS_CREAT, 0);
2719
+ assert_eq!(
2720
+ (answer, host.0.join("nowhere").exists()),
2721
+ (ERRNO_ISDIR, false),
2722
+ "path_open with O_CREAT of gone/, gone a host link to nothing beneath a Bind Mount, \
2723
+ through preview1 must answer EISDIR, as Linux does, and make nothing"
2724
+ );
2725
+ }
2726
+
1772
2727
  // The second seek would land past what a signed offset holds, so only
1773
2728
  // the cap keeps the position from reaching it.
1774
2729
  // @behavior RT-104
1775
2730
  #[test]
1776
- fn a_seek_past_the_largest_offset_overflows() {
2731
+ fn a_seek_past_the_largest_offset_is_invalid() {
1777
2732
  let answer = Guest::new(&[grant(file_and_directory(), Access::Read, None)])
1778
2733
  .call_bare("seek_past_the_largest_offset");
1779
2734
  assert_eq!(
1780
- answer, ERRNO_OVERFLOW,
2735
+ answer, ERRNO_INVAL,
1781
2736
  "fd_seek past the largest signed 64-bit offset of a file beneath a Mount through \
1782
- preview1 must answer EOVERFLOW, as Linux does"
2737
+ preview1 must answer EINVAL, as Linux does"
1783
2738
  );
1784
2739
  }
1785
2740
 
1786
- // A Memory clamps a read past its end and tries to grow for a write or a
2741
+ // A Tmpfs clamps a read past its end and tries to grow for a write or a
1787
2742
  // size, so only the check before the Filesystem answers each as Linux does.
1788
2743
  // @behavior RT-116
1789
2744
  #[test]
@@ -1797,7 +2752,7 @@ fn an_offset_past_the_largest_signed_offset_is_invalid() {
1797
2752
  ),
1798
2753
  (ERRNO_INVAL, ERRNO_INVAL, ERRNO_INVAL),
1799
2754
  "fd_pread, fd_pwrite, and fd_filestat_set_size past the largest signed 64-bit offset of a \
1800
- Memory file beneath a Mount through preview1 must answer EINVAL, as Linux does"
2755
+ Tmpfs file beneath a Mount through preview1 must answer EINVAL, as Linux does"
1801
2756
  );
1802
2757
  }
1803
2758
 
@@ -1824,17 +2779,17 @@ fn a_read_whose_end_passes_the_largest_signed_offset_is_invalid() {
1824
2779
  // two answers apart.
1825
2780
  // @behavior RT-135
1826
2781
  #[test]
1827
- fn a_wait_to_write_a_file_answers_by_what_its_mount_permits() {
2782
+ fn a_wait_to_write_a_file_is_ready_whatever_its_mount_permits() {
1828
2783
  let wait = |access| {
1829
2784
  Guest::new(&[grant(file_and_directory(), access, None)])
1830
2785
  .call_at("poll_write_with", RIGHTS_FD_READ)
1831
2786
  };
1832
2787
  assert_eq!(
1833
2788
  (wait(Access::ReadWrite), wait(Access::Read)),
1834
- (0, ERRNO_PERM),
2789
+ (0, 0),
1835
2790
  "poll_oneoff waiting to write a file opened only to read through preview1 must be ready \
1836
- beneath a read-write Mount and answer EPERM beneath a read-only one, as wasmtime-wasi \
1837
- answers by its preopen"
2791
+ beneath a read-write and a read-only Mount alike, as Linux's vfs_poll answers a file \
2792
+ with no poll of its own"
1838
2793
  );
1839
2794
  }
1840
2795
 
@@ -1852,10 +2807,10 @@ fn sizing_a_file_opened_only_to_read_answers_by_its_mount_then_as_linux_does() {
1852
2807
  size(Access::ReadWrite, RIGHTS_FD_READ),
1853
2808
  size(Access::ReadWrite, RIGHTS_FD_WRITE),
1854
2809
  ),
1855
- (ERRNO_PERM, ERRNO_INVAL, 0),
1856
- "fd_filestat_set_size on a file opened only to read through preview1 must answer EPERM \
1857
- beneath a read-only Mount, as wasmtime-wasi does, and EINVAL beneath a read-write one, \
1858
- as Linux's ftruncate does, while a file opened to write is sized"
2810
+ (ERRNO_INVAL, ERRNO_INVAL, 0),
2811
+ "fd_filestat_set_size on a file opened only to read through preview1 must answer EINVAL \
2812
+ beneath a read-only and a read-write Mount, as Linux's ftruncate does, while a file \
2813
+ opened to write is sized"
1859
2814
  );
1860
2815
  }
1861
2816
 
@@ -1863,15 +2818,18 @@ fn sizing_a_file_opened_only_to_read_answers_by_its_mount_then_as_linux_does() {
1863
2818
  #[derive(Default)]
1864
2819
  struct RecordsAsks(std::sync::Mutex<Vec<(String, Access)>>);
1865
2820
 
1866
- impl Policy for RecordsAsks {
1867
- fn allows(&self, path: &str, access: Access) -> bool {
1868
- self.0.lock().unwrap().push((path.to_owned(), access));
2821
+ impl Policy<MountRequest<'_>> for RecordsAsks {
2822
+ fn allows(&self, request: &MountRequest<'_>) -> bool {
2823
+ self.0
2824
+ .lock()
2825
+ .unwrap()
2826
+ .push((request.path.to_owned(), request.access));
1869
2827
  true
1870
2828
  }
1871
2829
  }
1872
2830
 
1873
- // The Mount is made read-only, as a Ruby mount with a block is by default,
1874
- // so only the Policy standing in its access's place lets either through.
2831
+ // The Mount is made read-only, so only a Mount allowing writes lets either
2832
+ // through.
1875
2833
  // Each Policy is asked only by the open before the call, so a wait or a size
1876
2834
  // asking it as well adds an ask the literal lists below do not hold.
1877
2835
  // @behavior RT-139
@@ -1881,8 +2839,8 @@ fn a_mount_whose_policy_decides_may_be_written() {
1881
2839
  let policy = Arc::new(RecordsAsks::default());
1882
2840
  let errno = Guest::new(&[grant(
1883
2841
  file_and_directory(),
1884
- Access::Read,
1885
- Some(policy.clone() as Arc<dyn Policy>),
2842
+ Access::ReadWrite,
2843
+ Some(policy.clone() as Arc<dyn for<'a> Policy<MountRequest<'a>>>),
1886
2844
  )])
1887
2845
  .call_at(name, rights);
1888
2846
  let asked = policy.0.lock().unwrap().clone();
@@ -1897,24 +2855,25 @@ fn a_mount_whose_policy_decides_may_be_written() {
1897
2855
  (0, vec![("/data/file.txt".to_owned(), Access::Read)]),
1898
2856
  (0, vec![("/data/file.txt".to_owned(), Access::ReadWrite)]),
1899
2857
  ),
1900
- "through preview1 beneath a read-only Mount whose Policy allows every change, \
2858
+ "through preview1 beneath a read-write Mount whose Policy allows every change, \
1901
2859
  poll_oneoff waiting to write a file opened only to read must be ready, and \
1902
2860
  fd_filestat_set_size on a file opened to write must size it, the Policy asked \
1903
2861
  only by each open"
1904
2862
  );
1905
2863
  }
1906
2864
 
1907
- // Each open asks without the right to write, so only its CREAT, where
1908
- // nothing stands yet, makes it a change.
2865
+ // Each open asks without the right to write, so only its CREAT makes it a
2866
+ // change; that is asked before the walk knows the file stands, as Linux's
2867
+ // `may_o_create` is, and the open of the file then asks as a read.
1909
2868
  // @behavior RT-146
1910
2869
  #[test]
1911
- fn a_policy_is_asked_once_for_an_open_that_may_create_as_what_it_does() {
2870
+ fn an_open_that_may_create_asks_to_make_the_file_before_it_finds_what_stands() {
1912
2871
  let open = |path| {
1913
2872
  let policy = Arc::new(RecordsAsks::default());
1914
2873
  let errno = Guest::new(&[grant(
1915
2874
  file_and_directory(),
1916
- Access::Read,
1917
- Some(policy.clone() as Arc<dyn Policy>),
2875
+ Access::ReadWrite,
2876
+ Some(policy.clone() as Arc<dyn for<'a> Policy<MountRequest<'a>>>),
1918
2877
  )])
1919
2878
  .call_flagged(path, OFLAGS_CREAT, 0);
1920
2879
  let asked = policy.0.lock().unwrap().clone();
@@ -1924,11 +2883,52 @@ fn a_policy_is_asked_once_for_an_open_that_may_create_as_what_it_does() {
1924
2883
  (open(NEW), open(FILE)),
1925
2884
  (
1926
2885
  (0, vec![("/data/new.txt".to_owned(), Access::ReadWrite)]),
1927
- (0, vec![("/data/file.txt".to_owned(), Access::Read)]),
2886
+ (
2887
+ 0,
2888
+ vec![
2889
+ ("/data/file.txt".to_owned(), Access::ReadWrite),
2890
+ ("/data/file.txt".to_owned(), Access::Read),
2891
+ ]
2892
+ ),
1928
2893
  ),
1929
2894
  "path_open with O_CREAT and no write of a missing path and of an existing file beneath \
1930
- a Mount whose Policy allows every change through preview1 must ask the Policy once for \
1931
- each, as a change where it creates and as a read where the file stands"
2895
+ a Mount whose Policy allows every change through preview1 must ask the Policy a change \
2896
+ for each, then a read for the file, as lookup_open asks may_o_create first"
2897
+ );
2898
+ }
2899
+
2900
+ /// A Policy refusing the Mount's root and allowing what lies beneath it,
2901
+ /// keeping each path it is asked.
2902
+ #[derive(Default)]
2903
+ struct RefusesTheRoot(std::sync::Mutex<Vec<String>>);
2904
+
2905
+ impl Policy<MountRequest<'_>> for RefusesTheRoot {
2906
+ fn allows(&self, request: &MountRequest<'_>) -> bool {
2907
+ self.0.lock().unwrap().push(request.path.to_owned());
2908
+ request.path != "/data"
2909
+ }
2910
+ }
2911
+
2912
+ // A Policy opening its Mount's root itself would refuse the invocation before
2913
+ // the guest runs, so only a root opened before the Policy applies lets the
2914
+ // read through.
2915
+ // @behavior RT-290
2916
+ #[test]
2917
+ fn a_mount_whose_policy_refuses_its_root_still_reads_beneath_it() {
2918
+ let policy = Arc::new(RefusesTheRoot::default());
2919
+ let mut guest = Guest::new(&[grant(
2920
+ file_and_directory(),
2921
+ Access::Read,
2922
+ Some(policy.clone() as Arc<dyn for<'a> Policy<MountRequest<'a>>>),
2923
+ )]);
2924
+ let read = guest.call("read_file", FILE);
2925
+ let asked = policy.0.lock().unwrap().clone();
2926
+ assert_eq!(
2927
+ (read, asked),
2928
+ (0, vec!["/data/file.txt".to_owned()]),
2929
+ "path_open of a file beneath a Mount whose Policy refuses its root, through preview1, \
2930
+ must read the file and ask the Policy only about it, as a Linux task opens what it \
2931
+ keeps before landlock_restrict_self"
1932
2932
  );
1933
2933
  }
1934
2934
 
@@ -1944,7 +2944,7 @@ fn an_open_of_a_missing_path_that_makes_nothing_answers_enoent() {
1944
2944
  let policed = Guest::new(&[grant(
1945
2945
  file_and_directory(),
1946
2946
  Access::Read,
1947
- Some(policy.clone() as Arc<dyn Policy>),
2947
+ Some(policy.clone() as Arc<dyn for<'a> Policy<MountRequest<'a>>>),
1948
2948
  )])
1949
2949
  .call("append_file", NEW);
1950
2950
  let asked = policy.0.lock().unwrap().clone();
@@ -1973,29 +2973,120 @@ fn what_stands_at_a_path_answers_before_a_read_only_mount_refuses() {
1973
2973
  );
1974
2974
  }
1975
2975
 
2976
+ // wasi-testsuite makes a file asking no right, so only an open that reads
2977
+ // lets the descriptor read what it made or emptied.
2978
+ // @behavior RT-303
2979
+ #[test]
2980
+ fn an_open_making_or_emptying_a_file_with_no_right_opens_it_to_read() {
2981
+ let tmpfs = file_and_directory();
2982
+ let mut guest = Guest::new(&[grant(tmpfs.clone(), Access::ReadWrite, None)]);
2983
+ let mut read_unasked = |path: (i32, i32), oflags: i32| {
2984
+ guest
2985
+ .instance
2986
+ .get_typed_func::<(i32, i32, i32), i32>(&mut guest.store, "read_unasked")
2987
+ .expect("probe export must resolve")
2988
+ .call(&mut guest.store, (path.0, path.1, oflags))
2989
+ .expect("probe call must not trap")
2990
+ };
2991
+ let answers = (
2992
+ read_unasked(NEW, OFLAGS_CREAT),
2993
+ read_unasked(FILE, OFLAGS_TRUNC),
2994
+ );
2995
+ assert_eq!(
2996
+ (
2997
+ answers,
2998
+ contents(&host(&tmpfs), "new.txt"),
2999
+ contents(&host(&tmpfs), "file.txt")
3000
+ ),
3001
+ ((0, 0), Some(Vec::new()), Some(Vec::new())),
3002
+ "path_open asking no right with O_CREAT, or with O_TRUNC, of a Tmpfs beneath a read-write \
3003
+ Mount through preview1 must make or empty the file and open it to read, as an O_RDONLY \
3004
+ open does"
3005
+ );
3006
+ }
3007
+
1976
3008
  const NEW: (i32, i32) = (840, 7);
1977
3009
  const RIGHTS_FD_READ: u64 = 1 << 1;
1978
3010
  const ERRNO_PERM: i32 = 63;
1979
3011
 
1980
- // A Memory would refuse the bytes for want of space, so only the refusal
1981
- // before the Filesystem is asked answers EFBIG.
3012
+ /// A Tmpfs with no operation to make, remove, or move a name, as a NULL in
3013
+ /// Linux's `inode_operations`.
3014
+ struct ChangesNothing(Arc<dyn InodeOperations>);
3015
+
3016
+ impl FileSystemType for ChangesNothing {
3017
+ fn fill_super(self: Arc<Self>, sb: &mut Filesystem) -> Result<(), Errno> {
3018
+ sb.d_make_root(vfs::Inode::new(
3019
+ &vfs::Kstat::new(vfs::FileType::Dir, 0),
3020
+ self,
3021
+ ));
3022
+ Ok(())
3023
+ }
3024
+ }
3025
+
3026
+ impl InodeOperations for ChangesNothing {
3027
+ fn getattr(&self, dentry: &Dentry) -> Result<Kstat, Errno> {
3028
+ self.0.getattr(dentry)
3029
+ }
3030
+
3031
+ fn lookup(&self, dentry: &Dentry) -> Result<Lookup, Errno> {
3032
+ Ok(match self.0.lookup(dentry)? {
3033
+ Lookup::Found(inode) => {
3034
+ Lookup::Found(inode.with_ops(Arc::new(Self(inode.ops().clone()))))
3035
+ }
3036
+ other => other,
3037
+ })
3038
+ }
3039
+
3040
+ fn open(&self, dentry: &Dentry, how: &OpenHow) -> Result<Box<dyn FileOperations>, Errno> {
3041
+ self.0.open(dentry, how)
3042
+ }
3043
+ }
3044
+
3045
+ // The Filesystem has nothing to answer these with, so each errno is the
3046
+ // runtime's, the one Linux's VFS answers for a NULL in `inode_operations`.
3047
+ // @behavior RT-175
3048
+ #[test]
3049
+ fn the_runtime_answers_for_an_operation_a_filesystem_lacks() {
3050
+ let filesystem = Arc::new(ChangesNothing(file_and_directory()));
3051
+ let mut guest = Guest::new(&[grant(filesystem, Access::ReadWrite, None)]);
3052
+ assert_eq!(
3053
+ (
3054
+ guest.call("make_dir", NEW),
3055
+ guest.call_flagged(NEW, OFLAGS_CREAT, 0),
3056
+ guest.call("remove_path", DIR),
3057
+ guest.call("unlink_path", FILE),
3058
+ guest.call_pair("rename_paths", FILE, MOVED),
3059
+ ),
3060
+ (ERRNO_PERM, ERRNO_ACCES, ERRNO_PERM, ERRNO_PERM, ERRNO_PERM),
3061
+ "path_create_directory, path_open with O_CREAT, path_remove_directory, \
3062
+ path_unlink_file, and path_rename through preview1, of a Filesystem lacking each \
3063
+ operation, must answer EPERM, EACCES, EPERM, EPERM, and EPERM"
3064
+ );
3065
+ }
3066
+
3067
+ // A Tmpfs would refuse the bytes for want of space, so only the refusal
3068
+ // before the Filesystem is asked answers EINVAL.
1982
3069
  // @behavior RT-133
1983
3070
  #[test]
1984
- fn a_write_at_the_largest_signed_offset_is_too_large() {
1985
- let memory = file_and_directory();
1986
- let answer = Guest::new(&[grant(memory.clone(), Access::ReadWrite, None)])
1987
- .call_bare("write_at_the_largest_offset");
3071
+ fn a_write_ending_past_the_largest_signed_offset_is_invalid() {
3072
+ let tmpfs = file_and_directory();
3073
+ let mut guest = Guest::new(&[grant(tmpfs.clone(), Access::ReadWrite, None)]);
3074
+ let answers = (
3075
+ guest.call_bare("write_at_the_largest_offset"),
3076
+ guest.call_at("write_at", i64::MAX as u64 - 1),
3077
+ );
1988
3078
  assert_eq!(
1989
- (answer, contents(memory.as_ref(), "file.txt")),
1990
- (ERRNO_FBIG, Some(b"granted".to_vec())),
1991
- "fd_write at the largest signed 64-bit offset of a Memory file beneath a Mount through \
1992
- preview1 must answer EFBIG, as Linux does, and leave the file as it was"
3079
+ (answers, contents(&host(&tmpfs), "file.txt")),
3080
+ ((ERRNO_INVAL, ERRNO_INVAL), Some(b"granted".to_vec())),
3081
+ "fd_write at the largest signed 64-bit offset, and fd_pwrite from one before it, of a \
3082
+ Tmpfs file beneath a Mount through preview1 must answer EINVAL, as Linux does, and \
3083
+ leave the file as it was"
1993
3084
  );
1994
3085
  }
1995
3086
 
1996
3087
  // @behavior RT-130
1997
3088
  #[test]
1998
- fn an_advice_past_the_largest_signed_offset_is_invalid() {
3089
+ fn an_advice_reaching_past_the_largest_signed_offset_is_invalid() {
1999
3090
  let mut guest = Guest::new(&[grant(file_and_directory(), Access::ReadWrite, None)]);
2000
3091
  assert_eq!(
2001
3092
  (
@@ -2004,16 +3095,17 @@ fn an_advice_past_the_largest_signed_offset_is_invalid() {
2004
3095
  guest.call_at("advise_for", 0)
2005
3096
  ),
2006
3097
  (ERRNO_INVAL, ERRNO_INVAL, 0),
2007
- "fd_advise from or for past the largest signed 64-bit offset of a Memory file beneath a \
2008
- Mount through preview1 must answer EINVAL, as an advice within it succeeds"
3098
+ "fd_advise of a Tmpfs file beneath a Mount through preview1 must answer EINVAL from an \
3099
+ offset or for a length past the largest signed 64-bit offset, as Linux's \
3100
+ generic_fadvise does"
2009
3101
  );
2010
3102
  }
2011
3103
 
2012
3104
  // The open asks to read only, so nothing else the open could refuse
2013
- // stands in for the refusal of not blocking.
3105
+ // stands in for a refusal of not blocking.
2014
3106
  // @behavior RT-129
2015
3107
  #[test]
2016
- fn a_descriptor_that_would_not_block_is_unsupported() {
3108
+ fn a_descriptor_may_ask_not_to_block() {
2017
3109
  let mut guest = Guest::new(&[grant(file_and_directory(), Access::ReadWrite, None)]);
2018
3110
  assert_eq!(
2019
3111
  (
@@ -2021,9 +3113,10 @@ fn a_descriptor_that_would_not_block_is_unsupported() {
2021
3113
  guest.call_bare("set_nonblocking"),
2022
3114
  guest.call_flagged(FILE, 0, 0)
2023
3115
  ),
2024
- (ERRNO_NOTSUP, ERRNO_NOTSUP, 0),
3116
+ (0, 0, 0),
2025
3117
  "path_open asking not to block and fd_fdstat_set_flags setting an open file not to \
2026
- block, beneath a Mount through preview1, must answer ENOTSUP"
3118
+ block, beneath a Mount through preview1, must succeed, as Linux takes O_NONBLOCK on a \
3119
+ file"
2027
3120
  );
2028
3121
  }
2029
3122
 
@@ -2049,17 +3142,106 @@ fn a_directory_a_guest_opens_carries_no_right_to_write() {
2049
3142
  );
2050
3143
  }
2051
3144
 
3145
+ // wasi-libc's `openat` asks only the rights its directory hands down, so a
3146
+ // write beneath a directory a guest opened needs `fd_write` among them.
3147
+ // @behavior RT-298
3148
+ #[test]
3149
+ fn a_directory_a_guest_opens_hands_down_the_right_to_write() {
3150
+ let mut guest = Guest::new(&[grant(file_and_directory(), Access::ReadWrite, None)]);
3151
+ let errno = guest.call_dir_with((RIGHTS_FD_READ | RIGHTS_FD_READDIR) as i64, 9);
3152
+ let memory = guest
3153
+ .instance
3154
+ .get_memory(&mut guest.store, "memory")
3155
+ .expect("probe exports its memory");
3156
+ let inheriting = u64::from_le_bytes(
3157
+ memory.data(&guest.store)[400..408]
3158
+ .try_into()
3159
+ .expect("the rights are eight bytes"),
3160
+ );
3161
+ assert_eq!(
3162
+ (errno, inheriting & RIGHTS_FD_WRITE),
3163
+ (0, RIGHTS_FD_WRITE),
3164
+ "fd_fdstat_get of a directory opened through path_open beneath a read-write Mount \
3165
+ through preview1 must hand down fd_write, as Linux takes an open's mode from its \
3166
+ flags alone"
3167
+ );
3168
+ }
3169
+
3170
+ // wasi-libc opens `O_SEARCH`, which glibc spells `O_PATH`, without `fd_read`,
3171
+ // `fd_readdir`, or `fd_write`; the poll answers the event's error, its call
3172
+ // succeeding. wasi-testsuite lists a directory opened with `fd_readdir` alone.
3173
+ // @behavior RT-297
3174
+ // @behavior RT-299
3175
+ // @behavior RT-300
3176
+ #[test]
3177
+ fn a_directory_opened_for_neither_reading_nor_writing_stands_only_for_its_path() {
3178
+ let mut guest = Guest::new(&[grant(file_and_directory(), Access::ReadWrite, None)]);
3179
+ assert_eq!(
3180
+ guest.call_dir_with(RIGHTS_FD_READDIR as i64, 0),
3181
+ 0,
3182
+ "fd_readdir of a directory opened with fd_readdir alone through preview1 must list it"
3183
+ );
3184
+ let answers: Vec<i32> = (0..9).map(|call| guest.call_dir_with(0, call)).collect();
3185
+ assert_eq!(
3186
+ answers,
3187
+ [
3188
+ ERRNO_BADF, ERRNO_BADF, ERRNO_BADF, ERRNO_BADF, ERRNO_BADF, ERRNO_BADF, ERRNO_BADF, 0,
3189
+ 0
3190
+ ],
3191
+ "fd_readdir, fd_sync, fd_advise, fd_fdstat_set_flags, fd_filestat_set_size, \
3192
+ fd_filestat_set_times, and poll_oneoff of a directory opened without fd_read or \
3193
+ fd_write beneath a read-write Mount through preview1 must answer EBADF, as fdget \
3194
+ refuses O_PATH, while fd_filestat_get and path_filestat_get from it succeed"
3195
+ );
3196
+ let errno = guest.call_dir_with(0, 9);
3197
+ let memory = guest
3198
+ .instance
3199
+ .get_memory(&mut guest.store, "memory")
3200
+ .expect("probe exports its memory");
3201
+ let rights = u64::from_le_bytes(
3202
+ memory.data(&guest.store)[392..400]
3203
+ .try_into()
3204
+ .expect("the rights are eight bytes"),
3205
+ );
3206
+ assert_eq!(
3207
+ (errno, rights & RIGHTS_FD_READDIR),
3208
+ (0, 0),
3209
+ "fd_fdstat_get of a directory opened without fd_read or fd_write through preview1 \
3210
+ must report no fd_readdir, as it lists nothing"
3211
+ );
3212
+ }
3213
+
3214
+ // A directory opened to list answers NOTSOCK, so only a socket call taking its
3215
+ // descriptor through fdget answers EBADF for one standing only for its path.
3216
+ // @behavior RT-306
3217
+ #[test]
3218
+ fn a_socket_call_refuses_a_descriptor_standing_only_for_its_path() {
3219
+ let mut guest = Guest::new(&[grant(file_and_directory(), Access::ReadWrite, None)]);
3220
+ assert_eq!(
3221
+ (
3222
+ guest.call_dir_with(0, 10),
3223
+ guest.call_dir_with(RIGHTS_FD_READDIR as i64, 10)
3224
+ ),
3225
+ (ERRNO_BADF, ERRNO_NOTSOCK),
3226
+ "sock_shutdown through preview1 of a directory opened without fd_read or fd_write must \
3227
+ answer EBADF, as Linux's socket calls take theirs through fdget, and of one opened to \
3228
+ list ENOTSOCK"
3229
+ );
3230
+ }
3231
+
3232
+ const ERRNO_NOTSOCK: i32 = 57;
3233
+
2052
3234
  // @behavior RT-105
2053
3235
  #[test]
2054
3236
  fn a_file_moved_beneath_itself_is_no_directory() {
2055
- let memory = file_and_directory();
2056
- let answer = Guest::new(&[grant(memory.clone(), Access::ReadWrite, None)]).call_pair(
3237
+ let tmpfs = file_and_directory();
3238
+ let answer = Guest::new(&[grant(tmpfs.clone(), Access::ReadWrite, None)]).call_pair(
2057
3239
  "rename_paths",
2058
3240
  FILE,
2059
3241
  BENEATH_FILE,
2060
3242
  );
2061
3243
  assert_eq!(
2062
- (answer, contents(memory.as_ref(), "file.txt")),
3244
+ (answer, contents(&host(&tmpfs), "file.txt")),
2063
3245
  (ERRNO_NOTDIR, Some(b"granted".to_vec())),
2064
3246
  "path_rename of a file to a path beneath it, beneath a Mount through preview1, must \
2065
3247
  answer ENOTDIR as Linux does and leave the file in place"
@@ -2072,7 +3254,7 @@ fn a_file_moved_beneath_itself_is_no_directory() {
2072
3254
  #[cfg(unix)]
2073
3255
  #[test]
2074
3256
  fn an_open_following_no_link_finds_a_dangling_link_as_itself() {
2075
- let (host, mut guest) = linked_under("dangling", |_| {}, Access::ReadWrite, None);
3257
+ let (host, mut guest) = mount_link_under("dangling", |_| {}, Access::ReadWrite, None);
2076
3258
  let answers = [
2077
3259
  guest.call_flagged(FILE, 0, 0),
2078
3260
  guest.call_flagged(FILE, OFLAGS_CREAT | OFLAGS_EXCL, 0),
@@ -2082,7 +3264,7 @@ fn an_open_following_no_link_finds_a_dangling_link_as_itself() {
2082
3264
  assert_eq!(
2083
3265
  (answers, made),
2084
3266
  ([ERRNO_LOOP, ERRNO_EXIST], false),
2085
- "path_open following no link of a dangling host link beneath a Directory Mount through \
3267
+ "path_open following no link of a dangling host link beneath a Bind Mount through \
2086
3268
  preview1 must answer ELOOP, and with O_CREAT and O_EXCL EEXIST, as Linux does, making \
2087
3269
  nothing where it points"
2088
3270
  );
@@ -2091,8 +3273,8 @@ fn an_open_following_no_link_finds_a_dangling_link_as_itself() {
2091
3273
  /// What each root-changing export answers, and how many changes the
2092
3274
  /// Filesystem was asked for along the way.
2093
3275
  fn change_root(exports: &[&str]) -> (Vec<i32>, usize) {
2094
- let counted = ChangeCounter::new();
2095
- let mut guest = Guest::new(&[grant(counted.clone(), Access::ReadWrite, None)]);
3276
+ let (counted, filesystem) = ChangeCounter::over_file();
3277
+ let mut guest = Guest::new(&[grant(filesystem, Access::ReadWrite, None)]);
2096
3278
  let answers = exports.iter().map(|name| guest.call_bare(name)).collect();
2097
3279
  (answers, counted.changes.load(Ordering::Relaxed))
2098
3280
  }
@@ -2133,8 +3315,8 @@ fn unlinking_a_mounts_root_answers_that_it_is_a_directory() {
2133
3315
  /// What reading `path` answers beneath a read-only Mount holding
2134
3316
  /// `file.txt`.
2135
3317
  fn read_beneath(path: (i32, i32)) -> i32 {
2136
- let memory: Memory = [("file.txt", "granted")].into_iter().collect();
2137
- Guest::new(&[grant(Arc::new(memory), Access::Read, None)]).call("read_file", path)
3318
+ let tmpfs: Tmpfs = [("file.txt", "granted")].into_iter().collect();
3319
+ Guest::new(&[grant(Arc::new(tmpfs), Access::Read, None)]).call("read_file", path)
2138
3320
  }
2139
3321
 
2140
3322
  // @behavior RT-086
@@ -2157,7 +3339,7 @@ fn a_dot_dot_after_a_missing_name_names_nothing() {
2157
3339
  );
2158
3340
  }
2159
3341
 
2160
- // The Memory would hold `file.txt` and any other name, so only the NUL
3342
+ // The Tmpfs would hold `file.txt` and any other name, so only the NUL
2161
3343
  // refuses the open.
2162
3344
  // @behavior RT-122
2163
3345
  #[test]
@@ -2193,12 +3375,12 @@ fn a_path_ending_in_a_slash_names_only_a_directory() {
2193
3375
  // @behavior RT-093
2194
3376
  #[test]
2195
3377
  fn a_rename_of_a_file_onto_a_path_ending_in_a_slash_is_not_a_directory() {
2196
- let memory: Arc<Memory> = Arc::new([("file.txt", "granted")].into_iter().collect());
2197
- let mut guest = Guest::new(&[grant(memory.clone(), Access::ReadWrite, None)]);
3378
+ let tmpfs = tmpfs_with("file.txt", "granted");
3379
+ let mut guest = Guest::new(&[grant(tmpfs.clone(), Access::ReadWrite, None)]);
2198
3380
  assert_eq!(
2199
3381
  (
2200
3382
  guest.call_bare("rename_onto_itself_as_directory"),
2201
- contents(memory.as_ref(), "file.txt")
3383
+ contents(&host(&tmpfs), "file.txt")
2202
3384
  ),
2203
3385
  (ERRNO_NOTDIR, Some(b"granted".to_vec())),
2204
3386
  "path_rename of `file.txt` onto `file.txt/` beneath a Mount through preview1 must \
@@ -2209,12 +3391,12 @@ fn a_rename_of_a_file_onto_a_path_ending_in_a_slash_is_not_a_directory() {
2209
3391
  // @behavior RT-090
2210
3392
  #[test]
2211
3393
  fn a_file_created_at_a_path_ending_in_a_slash_is_refused_as_a_directory() {
2212
- let memory = Arc::new(Memory::new());
2213
- let mut guest = Guest::new(&[grant(memory.clone(), Access::ReadWrite, None)]);
3394
+ let tmpfs = Arc::new(Tmpfs::new());
3395
+ let mut guest = Guest::new(&[grant(tmpfs.clone(), Access::ReadWrite, None)]);
2214
3396
  assert_eq!(
2215
3397
  (
2216
3398
  guest.call("write_file", NEW_AS_DIRECTORY),
2217
- memory.read_dir("").map(|entries| entries.len())
3399
+ host_entries(&tmpfs).map(|entries| entries.len())
2218
3400
  ),
2219
3401
  (ERRNO_ISDIR, Ok(0)),
2220
3402
  "path_open creating `new.txt/` beneath a Mount through preview1 must answer EISDIR and \
@@ -2231,57 +3413,75 @@ const RIGHTS_FD_WRITE: u64 = 1 << 6;
2231
3413
  const RIGHTS_FD_READDIR: u64 = 1 << 14;
2232
3414
 
2233
3415
  /// What opening `path` with `oflags` and `fdflags` answers beneath a
2234
- /// read-write Memory holding `file.txt`, and the paths it holds after.
3416
+ /// read-write Tmpfs holding `file.txt`, and the paths it holds after.
2235
3417
  fn open_flagged(path: (i32, i32), oflags: i32, fdflags: i32) -> (i32, Vec<String>) {
2236
- let memory: Arc<Memory> = Arc::new([("file.txt", "granted")].into_iter().collect());
2237
- let errno = Guest::new(&[grant(memory.clone(), Access::ReadWrite, None)])
3418
+ let tmpfs = tmpfs_with("file.txt", "granted");
3419
+ let errno = Guest::new(&[grant(tmpfs.clone(), Access::ReadWrite, None)])
2238
3420
  .call_flagged(path, oflags, fdflags);
2239
- let held = memory
2240
- .read_dir("")
2241
- .expect("the root must list")
2242
- .into_iter()
2243
- .map(|entry| entry.name)
2244
- .collect();
3421
+ let held = host_entries(&tmpfs).expect("the root must list");
2245
3422
  (errno, held)
2246
3423
  }
2247
3424
 
2248
3425
  // @behavior RT-091
2249
3426
  #[test]
2250
- fn an_open_asking_for_synchronized_writes_is_unsupported() {
3427
+ fn an_open_may_ask_for_synchronized_writes() {
2251
3428
  assert_eq!(
2252
3429
  open_flagged(FILE, 0, FDFLAGS_SYNC).0,
2253
- ERRNO_NOTSUP,
2254
- "path_open of `file.txt` with FDFLAGS_SYNC beneath a Mount through preview1 must answer \
2255
- ENOTSUP"
3430
+ 0,
3431
+ "path_open of `file.txt` with FDFLAGS_SYNC beneath a Mount through preview1 must succeed, \
3432
+ as Linux takes O_SYNC"
2256
3433
  );
2257
3434
  }
2258
3435
 
2259
3436
  // @behavior RT-092
2260
3437
  #[test]
2261
- fn an_open_of_a_directory_that_creates_or_truncates_is_invalid() {
3438
+ fn an_open_of_a_directory_answers_its_other_flags_as_linux_does() {
2262
3439
  let held = vec!["file.txt".to_string()];
2263
3440
  assert_eq!(
2264
3441
  (
2265
3442
  open_flagged(NEW_AS_DIRECTORY, OFLAGS_DIRECTORY | OFLAGS_CREAT, 0),
2266
- open_flagged(FILE, OFLAGS_DIRECTORY | OFLAGS_TRUNC, 0)
3443
+ open_flagged(FILE, OFLAGS_DIRECTORY | OFLAGS_TRUNC, 0),
3444
+ open_flagged(FILE, OFLAGS_DIRECTORY, 0),
3445
+ ),
3446
+ (
3447
+ (ERRNO_INVAL, held.clone()),
3448
+ (ERRNO_NOTDIR, held.clone()),
3449
+ (ERRNO_NOTDIR, held)
2267
3450
  ),
2268
- ((ERRNO_INVAL, held.clone()), (ERRNO_INVAL, held)),
2269
- "path_open with OFLAGS_DIRECTORY and CREAT or TRUNC beneath a Mount through preview1 \
2270
- must answer EINVAL and make nothing"
3451
+ "path_open with OFLAGS_DIRECTORY beneath a Mount through preview1 must answer EINVAL \
3452
+ with CREAT and ENOTDIR for a file, and make nothing, as Linux does"
2271
3453
  );
2272
3454
  }
2273
3455
 
3456
+ #[cfg(unix)]
2274
3457
  const UP: (i32, i32) = (1070, 2);
3458
+ #[cfg(unix)]
2275
3459
  const THROUGH_UPDIR: (i32, i32) = (1080, 7);
3460
+ #[cfg(unix)]
2276
3461
  const IN_LINKED: (i32, i32) = (1090, 4);
3462
+ #[cfg(unix)]
2277
3463
  const TWISTY: (i32, i32) = (1100, 6);
3464
+ #[cfg(unix)]
2278
3465
  const DANGLE: (i32, i32) = (1110, 6);
3466
+ #[cfg(unix)]
2279
3467
  const DIR_UP: (i32, i32) = (1120, 6);
3468
+ #[cfg(unix)]
2280
3469
  const NOWHERE: (i32, i32) = (1130, 7);
3470
+ #[cfg(unix)]
3471
+ const OUT_OF_IN: (i32, i32) = (1160, 20);
3472
+ #[cfg(unix)]
3473
+ const LOOP: (i32, i32) = (1184, 4);
3474
+ #[cfg(unix)]
3475
+ const DIR_SUB: (i32, i32) = (1190, 7);
3476
+ #[cfg(unix)]
3477
+ const DIR_IN_Y: (i32, i32) = (1400, 8);
3478
+ #[cfg(unix)]
3479
+ const DIR_SUB_Y: (i32, i32) = (1420, 9);
2281
3480
 
2282
3481
  /// A host directory whose `dir` holds links staying within it (`in`,
2283
- /// `twisty`), links leading out of it (`up`, `updir`), and links pointing
2284
- /// at nothing out of it (`dangle`) and within it (`nowhere`).
3482
+ /// `twisty`), links leading out of it (`up`, `updir`), links pointing at
3483
+ /// nothing out of it (`dangle`) and within it (`nowhere`), and a link
3484
+ /// pointing at itself (`loop`).
2285
3485
  #[cfg(unix)]
2286
3486
  struct LinkedBeneath(std::path::PathBuf);
2287
3487
 
@@ -2291,7 +3491,8 @@ impl LinkedBeneath {
2291
3491
  let host =
2292
3492
  std::env::temp_dir().join(format!("kobako-beneath-{name}-{}", std::process::id()));
2293
3493
  let _ = std::fs::remove_dir_all(&host);
2294
- std::fs::create_dir_all(host.join("dir/sub")).expect("the host directory must be created");
3494
+ std::fs::create_dir_all(host.join("dir/sub/inner"))
3495
+ .expect("the host directory must be created");
2295
3496
  std::fs::create_dir_all(host.join("other")).expect("the host directory must be created");
2296
3497
  for file in ["secret", "other/x", "dir/sub/y"] {
2297
3498
  std::fs::write(host.join(file), "x").expect("the host file must be written");
@@ -2303,21 +3504,24 @@ impl LinkedBeneath {
2303
3504
  ("sub/../sub/y", "dir/twisty"),
2304
3505
  ("../escaped", "dir/dangle"),
2305
3506
  ("missing", "dir/nowhere"),
3507
+ ("loop", "dir/loop"),
2306
3508
  ] {
2307
3509
  std::os::unix::fs::symlink(target, host.join(link)).expect("the link must be made");
2308
3510
  }
2309
3511
  Self(host)
2310
3512
  }
2311
3513
 
2312
- /// A guest over this host directory as a Directory Mount, or as an
2313
- /// Overlay's writable Directory Layer above an empty Memory.
3514
+ /// A guest over this host directory as a Bind Mount, or as an
3515
+ /// Overlay's lower Bind Layer beneath an empty upper.
2314
3516
  fn guest(&self, overlay: bool) -> Guest {
2315
- let directory = Arc::new(Directory::new(&self.0).expect("the host directory must open"));
2316
- let filesystem: Arc<dyn Filesystem> = if overlay {
3517
+ let directory = Arc::new(Bind::new(&self.0).expect("the host directory must open"));
3518
+ let filesystem: Arc<dyn FileSystemType> = if overlay {
2317
3519
  Arc::new(
2318
- Overlay::new()
2319
- .layer(directory, Access::ReadWrite)
2320
- .layer(Arc::new(Memory::new()), Access::Read),
3520
+ Overlay::new(
3521
+ vec![Filesystem::new(directory).expect("the instance must stand")],
3522
+ Some(Filesystem::new(Tmpfs::new()).expect("the instance must stand")),
3523
+ )
3524
+ .expect("an upper over a lower Layer must make a view"),
2321
3525
  )
2322
3526
  } else {
2323
3527
  directory
@@ -2338,7 +3542,7 @@ impl Drop for LinkedBeneath {
2338
3542
  // @behavior RT-140
2339
3543
  #[cfg(unix)]
2340
3544
  #[test]
2341
- fn a_link_leading_out_of_an_opened_directory_is_not_permitted() {
3545
+ fn a_link_leading_out_of_an_opened_directory_escapes_it() {
2342
3546
  let host = LinkedBeneath::new("out");
2343
3547
  let answers = |overlay| {
2344
3548
  let mut guest = host.guest(overlay);
@@ -2356,10 +3560,85 @@ fn a_link_leading_out_of_an_opened_directory_is_not_permitted() {
2356
3560
  answers(true),
2357
3561
  host.0.join("escaped").exists()
2358
3562
  ),
2359
- ([ERRNO_PERM; 5], [ERRNO_PERM; 5], false),
3563
+ ([ERRNO_NOTCAPABLE; 5], [ERRNO_NOTCAPABLE; 5], false),
2360
3564
  "an open, a stat, or a create through preview1 of a path whose link leads out of a \
2361
- directory opened beneath a Directory Mount, or an Overlay's Directory Layer, must answer \
2362
- EPERM, as wasmtime-wasi does, and create nothing"
3565
+ directory opened beneath a Bind Mount, or an Overlay's Bind Layer, must answer \
3566
+ ENOTCAPABLE, as a `..` leading out does, and create nothing"
3567
+ );
3568
+ }
3569
+
3570
+ // The second `..` leaves `sub`, where `in` led, two names after the link, so
3571
+ // only a walk standing where the link led reaches `sub/y` from `dir`.
3572
+ // @behavior RT-119
3573
+ #[cfg(unix)]
3574
+ #[test]
3575
+ fn a_step_out_of_where_a_link_led_lands_beside_it() {
3576
+ let host = LinkedBeneath::new("led");
3577
+ let answers = |overlay| host.guest(overlay).call("open_beneath_dir", OUT_OF_IN);
3578
+ assert_eq!(
3579
+ (answers(false), answers(true)),
3580
+ (0, 0),
3581
+ "an open through preview1 of `in/inner/../../sub/y`, where `in` is a link within a \
3582
+ directory opened beneath a Bind Mount or an Overlay's Bind Layer, must reach the file \
3583
+ beside where the link points, as Linux's walk does"
3584
+ );
3585
+ }
3586
+
3587
+ // A Policy lets no directory move, and each side of the rename is walked
3588
+ // on its own, so only a rename recognised as onto its own path, rather
3589
+ // than by the directory each walk opened, changes nothing and succeeds.
3590
+ // @behavior RT-155
3591
+ #[cfg(unix)]
3592
+ #[test]
3593
+ fn a_directory_renamed_onto_its_own_path_beneath_a_policy_stays() {
3594
+ let host = LinkedBeneath::new("onto-itself");
3595
+ let directory = Arc::new(Bind::new(&host.0).expect("the host directory must open"));
3596
+ let mut guest = Guest::new(&[grant(
3597
+ directory,
3598
+ Access::ReadWrite,
3599
+ Some(Arc::new(AllowsAll)),
3600
+ )]);
3601
+ assert_eq!(
3602
+ (
3603
+ guest.call_pair("rename_paths", DIR_SUB, DIR_SUB),
3604
+ host.0.join("dir/sub/y").is_file()
3605
+ ),
3606
+ (0, true),
3607
+ "path_rename of `dir/sub` onto itself beneath a Bind Mount with a Policy through \
3608
+ preview1 must change nothing and succeed, as rename(2) does"
3609
+ );
3610
+ }
3611
+
3612
+ // The two paths differ, so only the walk ending on one dentry tells the
3613
+ // rename it is onto itself; otherwise it waits on that name's lock twice.
3614
+ // @behavior RT-168
3615
+ #[cfg(unix)]
3616
+ #[test]
3617
+ fn a_file_renamed_onto_itself_through_a_link_stays() {
3618
+ let host = LinkedBeneath::new("onto-itself-linked");
3619
+ let mut guest = host.guest(false);
3620
+ assert_eq!(
3621
+ (
3622
+ guest.call_pair("rename_paths", DIR_IN_Y, DIR_SUB_Y),
3623
+ host.0.join("dir/sub/y").is_file()
3624
+ ),
3625
+ (0, true),
3626
+ "path_rename of `dir/in/y` onto `dir/sub/y`, where `in` links to `sub`, beneath a Bind \
3627
+ Mount through preview1 must change nothing and succeed, as rename(2) does"
3628
+ );
3629
+ }
3630
+
3631
+ // @behavior RT-154
3632
+ #[cfg(unix)]
3633
+ #[test]
3634
+ fn a_link_loop_answers_eloop() {
3635
+ let host = LinkedBeneath::new("loop");
3636
+ let answers = |overlay| host.guest(overlay).call("open_following_beneath_dir", LOOP);
3637
+ assert_eq!(
3638
+ (answers(false), answers(true)),
3639
+ (ERRNO_LOOP, ERRNO_LOOP),
3640
+ "an open through preview1 following a link pointing at itself, beneath a Directory \
3641
+ Mount or an Overlay's Bind Layer, must answer ELOOP"
2363
3642
  );
2364
3643
  }
2365
3644
 
@@ -2379,38 +3658,37 @@ fn a_link_staying_within_an_opened_directory_is_followed() {
2379
3658
  (answers(false), answers(true)),
2380
3659
  ([0; 2], [0; 2]),
2381
3660
  "an open through preview1 of a path whose links stay within a directory opened beneath \
2382
- a Directory Mount, or an Overlay's Directory Layer, must reach the file they lead to"
3661
+ a Bind Mount, or an Overlay's Bind Layer, must reach the file they lead to"
2383
3662
  );
2384
3663
  }
2385
3664
 
2386
- // The link's target lies within `dir`, where Linux would create it, so only
2387
- // the refusal to create through a link it cannot resolve answers ELOOP.
3665
+ // An Overlay's change lands in its upper, so only a Bind shows it on the host.
2388
3666
  // @behavior RT-142
2389
3667
  #[cfg(unix)]
2390
3668
  #[test]
2391
- fn a_create_through_a_dangling_link_beneath_an_opened_directory_is_refused() {
2392
- let host = LinkedBeneath::new("dangle");
2393
- let answers = |overlay| {
3669
+ fn a_create_through_a_dangling_link_beneath_an_opened_directory_makes_its_target() {
3670
+ let answers = |name, overlay| {
3671
+ let host = LinkedBeneath::new(name);
2394
3672
  let errno = host
2395
3673
  .guest(overlay)
2396
3674
  .call("create_following_beneath_dir", NOWHERE);
2397
3675
  (errno, host.0.join("dir/missing").exists())
2398
3676
  };
2399
3677
  assert_eq!(
2400
- (answers(false), answers(true)),
2401
- ((ERRNO_LOOP, false), (ERRNO_LOOP, false)),
3678
+ (answers("dangle", false), answers("dangle-overlay", true)),
3679
+ ((0, true), (0, false)),
2402
3680
  "an open through preview1 creating a file through a link pointing at nothing beneath a \
2403
- directory opened beneath a Directory Mount, or an Overlay's Directory Layer, must answer \
2404
- ELOOP and create nothing"
3681
+ directory opened beneath a Bind Mount must make the file where the link points, as \
3682
+ Linux's open does, and beneath an Overlay's Bind Layer must leave that Layer as it was"
2405
3683
  );
2406
3684
  }
2407
3685
 
2408
- // The link names a file outside the host directory, so cap-std refuses it
2409
- // with no OS code, which wasmtime-wasi answers as EPERM.
3686
+ // The link names a file outside the host directory by an absolute path, so
3687
+ // the walk refuses it before any host call is made.
2410
3688
  // @behavior RT-143
2411
3689
  #[cfg(unix)]
2412
3690
  #[test]
2413
- fn a_link_leading_out_of_a_mount_is_not_permitted() {
3691
+ fn a_link_leading_out_of_a_mount_escapes_it() {
2414
3692
  let host = LinkedBeneath::new("mount");
2415
3693
  let outside =
2416
3694
  std::env::temp_dir().join(format!("kobako-beneath-outside-{}", std::process::id()));
@@ -2420,9 +3698,9 @@ fn a_link_leading_out_of_a_mount_is_not_permitted() {
2420
3698
  let errno = host.guest(false).call("open_following", DIR_UP);
2421
3699
  let _ = std::fs::remove_file(&outside);
2422
3700
  assert_eq!(
2423
- errno, ERRNO_PERM,
2424
- "an open through preview1 from a Directory Mount's root of a link to a file outside its \
2425
- host directory must answer EPERM, as wasmtime-wasi does"
3701
+ errno, ERRNO_NOTCAPABLE,
3702
+ "an open through preview1 from a Bind Mount's root of a link to a file outside its \
3703
+ host directory must answer ENOTCAPABLE, as an absolute path does"
2426
3704
  );
2427
3705
  }
2428
3706
 
@@ -2430,7 +3708,7 @@ fn a_link_leading_out_of_a_mount_is_not_permitted() {
2430
3708
  // of the bound and the access check decides between a trap and EBADF.
2431
3709
  // @behavior RT-144
2432
3710
  #[test]
2433
- fn a_buffer_outside_memory_is_bounded_before_a_files_access_is_checked() {
3711
+ fn a_files_access_is_checked_before_a_buffer_outside_memory_is_bounded() {
2434
3712
  let call = |name, rights| {
2435
3713
  Guest::new(&[grant(file_and_directory(), Access::ReadWrite, None)])
2436
3714
  .try_call_at(name, rights)
@@ -2442,13 +3720,14 @@ fn a_buffer_outside_memory_is_bounded_before_a_files_access_is_checked() {
2442
3720
  call("pwrite_far_with", RIGHTS_FD_READ),
2443
3721
  call("pread_far_with", RIGHTS_FD_WRITE),
2444
3722
  ],
2445
- [None, None, None, Some(ERRNO_BADF)],
3723
+ [Some(ERRNO_BADF); 4],
2446
3724
  "through preview1 on a file opened without the access each call needs, with a buffer \
2447
- past memory, fd_read, fd_write, and fd_pwrite must trap, and fd_pread must answer \
2448
- EBADF, as wasmtime-wasi does"
3725
+ past memory, fd_read, fd_write, fd_pwrite, and fd_pread must answer EBADF, as Linux \
3726
+ asks f_mode before it touches the buffer"
2449
3727
  );
2450
3728
  }
2451
3729
 
3730
+ #[cfg(unix)]
2452
3731
  const PUB_X: (i32, i32) = (1150, 5);
2453
3732
 
2454
3733
  /// A Policy allowing `/data/pub/` alone, which swaps `pub` for a link to
@@ -2458,20 +3737,20 @@ const PUB_X: (i32, i32) = (1150, 5);
2458
3737
  struct SwapsWhileAsked(std::path::PathBuf, std::sync::atomic::AtomicBool);
2459
3738
 
2460
3739
  #[cfg(unix)]
2461
- impl Policy for SwapsWhileAsked {
2462
- fn allows(&self, path: &str, _access: Access) -> bool {
3740
+ impl Policy<MountRequest<'_>> for SwapsWhileAsked {
3741
+ fn allows(&self, request: &MountRequest<'_>) -> bool {
2463
3742
  if self.1.swap(false, Ordering::SeqCst) {
2464
3743
  std::fs::rename(self.0.join("pub"), self.0.join("pub_old")).expect("pub must move");
2465
3744
  std::os::unix::fs::symlink("secret", self.0.join("pub"))
2466
3745
  .expect("the link must be made");
2467
3746
  }
2468
- path.starts_with("/data/pub/")
3747
+ request.path.starts_with("/data/pub/")
2469
3748
  }
2470
3749
  }
2471
3750
 
2472
- // The swap happens inside the Policy's own judgment, so only a call that
2473
- // reaches the path without following the link swapped in meanwhile is
2474
- // refused; a plain Directory would read `secret/x`.
3751
+ // The swap happens inside the Policy's own judgment, after the walk opened
3752
+ // `pub`, so only a call acting on the directory it walked to, rather than
3753
+ // on the path again, keeps from reading `secret/x`.
2475
3754
  // @behavior RT-145
2476
3755
  #[cfg(unix)]
2477
3756
  #[test]
@@ -2483,17 +3762,19 @@ fn a_link_swapped_in_after_a_policy_judges_a_path_is_not_followed() {
2483
3762
  std::fs::write(host.join(dir).join("x"), dir).expect("the host file must be written");
2484
3763
  }
2485
3764
  let policy = SwapsWhileAsked(host.clone(), std::sync::atomic::AtomicBool::new(true));
2486
- let directory = Directory::new(&host).expect("the host directory must open");
2487
- let errno = Guest::new(&[grant(
3765
+ let directory = Bind::new(&host).expect("the host directory must open");
3766
+ let mut guest = Guest::new(&[grant(
2488
3767
  Arc::new(directory),
2489
3768
  Access::Read,
2490
3769
  Some(Arc::new(policy)),
2491
- )])
2492
- .call("open_following", PUB_X);
3770
+ )]);
3771
+ let answer = (guest.call("read_file", PUB_X), guest.read_back());
2493
3772
  let _ = std::fs::remove_dir_all(&host);
2494
3773
  assert_eq!(
2495
- errno, ERRNO_LOOP,
2496
- "an open through preview1 beneath a Directory Mount with a Policy, of a path whose \
2497
- directory another writer swaps for a link as the Policy judges it, must answer ELOOP"
3774
+ answer,
3775
+ (0, b"pub".to_vec()),
3776
+ "a read through preview1 beneath a Bind Mount with a Policy, of a path whose \
3777
+ directory another writer swaps for a link as the Policy judges it, must read the \
3778
+ directory the walk held and nothing where the link points"
2498
3779
  );
2499
3780
  }