kobako 0.30.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (288) hide show
  1. checksums.yaml +4 -4
  2. data/.githooks/linux-tests.sh +29 -0
  3. data/.release-please-manifest.json +1 -1
  4. data/CHANGELOG.md +460 -0
  5. data/Cargo.lock +868 -447
  6. data/README.md +43 -4
  7. data/ROADMAP.md +1 -2
  8. data/crates/kobako-runtime/CHANGELOG.md +309 -0
  9. data/crates/kobako-runtime/Cargo.toml +58 -11
  10. data/crates/kobako-runtime/README.md +7 -4
  11. data/crates/kobako-runtime/src/cred.rs +136 -0
  12. data/crates/kobako-runtime/src/dispatch.rs +4 -5
  13. data/crates/kobako-runtime/src/endpoint/buffer.rs +153 -44
  14. data/crates/kobako-runtime/src/endpoint/dispatch.rs +80 -41
  15. data/crates/kobako-runtime/src/endpoint/invoke.rs +23 -36
  16. data/crates/kobako-runtime/src/endpoint.rs +137 -36
  17. data/crates/kobako-runtime/src/errno.rs +391 -0
  18. data/crates/kobako-runtime/src/error.rs +31 -10
  19. data/crates/kobako-runtime/src/filesystem/anon_inodes.rs +52 -0
  20. data/crates/kobako-runtime/src/filesystem/bind/fid.rs +300 -22
  21. data/crates/kobako-runtime/src/filesystem/bind/lookup.rs +101 -29
  22. data/crates/kobako-runtime/src/filesystem/bind/unicode.rs +109 -0
  23. data/crates/kobako-runtime/src/filesystem/bind/walk.rs +52 -34
  24. data/crates/kobako-runtime/src/filesystem/bind.rs +812 -447
  25. data/crates/kobako-runtime/src/filesystem/overlay/file.rs +6 -6
  26. data/crates/kobako-runtime/src/filesystem/overlay/path.rs +43 -65
  27. data/crates/kobako-runtime/src/filesystem/overlay/stack/copy_up.rs +11 -16
  28. data/crates/kobako-runtime/src/filesystem/overlay/stack/dir.rs +47 -72
  29. data/crates/kobako-runtime/src/filesystem/overlay/stack/namei.rs +12 -12
  30. data/crates/kobako-runtime/src/filesystem/overlay/stack/readdir.rs +4 -7
  31. data/crates/kobako-runtime/src/filesystem/overlay/stack.rs +120 -37
  32. data/crates/kobako-runtime/src/filesystem/overlay.rs +578 -388
  33. data/crates/kobako-runtime/src/filesystem/pipe.rs +12 -9
  34. data/crates/kobako-runtime/src/filesystem/rdir.rs +14 -50
  35. data/crates/kobako-runtime/src/filesystem/testing.rs +31 -0
  36. data/crates/kobako-runtime/src/filesystem/tmpfs/seed.rs +32 -0
  37. data/crates/kobako-runtime/src/filesystem/tmpfs/tmpfile.rs +3 -3
  38. data/crates/kobako-runtime/src/filesystem/tmpfs/whiteout.rs +57 -35
  39. data/crates/kobako-runtime/src/filesystem/tmpfs/xattr.rs +2 -2
  40. data/crates/kobako-runtime/src/filesystem/tmpfs.rs +219 -173
  41. data/crates/kobako-runtime/src/filesystem/wrap.rs +36 -52
  42. data/crates/kobako-runtime/src/filesystem.rs +8 -3
  43. data/crates/kobako-runtime/src/fork.rs +319 -0
  44. data/crates/kobako-runtime/src/grant.rs +3 -0
  45. data/crates/kobako-runtime/src/hashtable.rs +4 -2
  46. data/crates/kobako-runtime/src/lib.rs +18 -7
  47. data/crates/kobako-runtime/src/limits.rs +171 -0
  48. data/crates/kobako-runtime/src/locking/seqlock.rs +29 -3
  49. data/crates/kobako-runtime/src/locking.rs +518 -113
  50. data/crates/kobako-runtime/src/memcg.rs +306 -0
  51. data/crates/kobako-runtime/src/mount.rs +37 -9
  52. data/crates/kobako-runtime/src/net/backends.rs +43 -0
  53. data/crates/kobako-runtime/src/net/connections.rs +219 -0
  54. data/crates/kobako-runtime/src/net/credential.rs +125 -0
  55. data/crates/kobako-runtime/src/net/egress.rs +180 -0
  56. data/crates/kobako-runtime/src/net/family.rs +181 -0
  57. data/crates/kobako-runtime/src/net/http.rs +3165 -0
  58. data/crates/kobako-runtime/src/net/lookup.rs +385 -0
  59. data/crates/kobako-runtime/src/net/mock.rs +251 -0
  60. data/crates/kobako-runtime/src/net/namespace.rs +1368 -0
  61. data/crates/kobako-runtime/src/net/reactor.rs +626 -0
  62. data/crates/kobako-runtime/src/net/resolv/darwin.rs +280 -0
  63. data/crates/kobako-runtime/src/net/resolv/stub/tests.rs +519 -0
  64. data/crates/kobako-runtime/src/net/resolv/stub.rs +542 -0
  65. data/crates/kobako-runtime/src/net/resolv/windows.rs +218 -0
  66. data/crates/kobako-runtime/src/net/resolv.rs +251 -0
  67. data/crates/kobako-runtime/src/net/skbuff.rs +109 -0
  68. data/crates/kobako-runtime/src/net/socket.rs +869 -0
  69. data/crates/kobako-runtime/src/net/task.rs +223 -0
  70. data/crates/kobako-runtime/src/net/tcp.rs +1840 -0
  71. data/crates/kobako-runtime/src/net/tls.rs +120 -0
  72. data/crates/kobako-runtime/src/net/transport.rs +304 -0
  73. data/crates/kobako-runtime/src/net/udp.rs +1105 -0
  74. data/crates/kobako-runtime/src/net.rs +45 -0
  75. data/crates/kobako-runtime/src/network/builder.rs +177 -0
  76. data/crates/kobako-runtime/src/network/ruleset.rs +777 -0
  77. data/crates/kobako-runtime/src/network.rs +551 -0
  78. data/crates/kobako-runtime/src/policy.rs +16 -0
  79. data/crates/kobako-runtime/src/profile.rs +29 -144
  80. data/crates/kobako-runtime/src/runtime.rs +3 -5
  81. data/crates/kobako-runtime/src/sched.rs +338 -51
  82. data/crates/kobako-runtime/src/security/entry_policy.rs +22 -0
  83. data/crates/kobako-runtime/src/{vfs/cred.rs → security/hooks.rs} +52 -144
  84. data/crates/kobako-runtime/src/security/mount_policy.rs +158 -0
  85. data/crates/kobako-runtime/src/security.rs +125 -209
  86. data/crates/kobako-runtime/src/snapshot.rs +121 -2
  87. data/crates/kobako-runtime/src/vfs/attr.rs +5 -5
  88. data/crates/kobako-runtime/src/vfs/dentry.rs +210 -117
  89. data/crates/kobako-runtime/src/vfs/file.rs +243 -248
  90. data/crates/kobako-runtime/src/vfs/inode.rs +41 -45
  91. data/crates/kobako-runtime/src/vfs/kern_path.rs +62 -53
  92. data/crates/kobako-runtime/src/vfs/mount.rs +10 -9
  93. data/crates/kobako-runtime/src/vfs/namei.rs +1162 -818
  94. data/crates/kobako-runtime/src/vfs/namespace.rs +245 -0
  95. data/crates/kobako-runtime/src/vfs/open_files.rs +69 -0
  96. data/crates/kobako-runtime/src/vfs/openat2.rs +3 -3
  97. data/crates/kobako-runtime/src/vfs/path.rs +6 -6
  98. data/crates/kobako-runtime/src/vfs/readdir.rs +6 -6
  99. data/crates/kobako-runtime/src/vfs/stat.rs +248 -23
  100. data/crates/kobako-runtime/src/vfs/super_block.rs +18 -14
  101. data/crates/kobako-runtime/src/vfs/utimes.rs +37 -27
  102. data/crates/kobako-runtime/src/vfs.rs +10 -6
  103. data/crates/kobako-runtime/src/wait.rs +381 -0
  104. data/crates/kobako-transport/CHANGELOG.md +38 -0
  105. data/crates/kobako-transport/Cargo.toml +1 -1
  106. data/crates/kobako-transport/README.md +3 -4
  107. data/crates/kobako-transport/src/abi.rs +78 -72
  108. data/crates/kobako-transport/src/envelope/bytes.rs +17 -6
  109. data/crates/kobako-transport/src/envelope/call.rs +32 -4
  110. data/crates/kobako-transport/src/envelope/error_record.rs +21 -0
  111. data/crates/kobako-transport/src/envelope/name.rs +99 -0
  112. data/crates/kobako-transport/src/envelope/outcome.rs +9 -9
  113. data/crates/kobako-transport/src/envelope/preamble.rs +24 -21
  114. data/crates/kobako-transport/src/envelope/reply.rs +27 -27
  115. data/crates/kobako-transport/src/envelope/unsupported.rs +10 -10
  116. data/crates/kobako-transport/src/envelope.rs +13 -8
  117. data/crates/kobako-wasmtime/CHANGELOG.md +208 -0
  118. data/crates/kobako-wasmtime/Cargo.toml +47 -7
  119. data/crates/kobako-wasmtime/README.md +4 -3
  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 +18 -37
  123. data/crates/kobako-wasmtime/src/ambient.rs +43 -19
  124. data/crates/kobako-wasmtime/src/cache/unix.rs +95 -0
  125. data/crates/kobako-wasmtime/src/cache/windows.rs +359 -0
  126. data/crates/kobako-wasmtime/src/cache.rs +106 -113
  127. data/crates/kobako-wasmtime/src/config.rs +52 -68
  128. data/crates/kobako-wasmtime/src/driver.rs +80 -82
  129. data/crates/kobako-wasmtime/src/exports.rs +143 -17
  130. data/crates/kobako-wasmtime/src/guest.rs +12 -6
  131. data/crates/kobako-wasmtime/src/guest_binary.rs +14 -0
  132. data/crates/kobako-wasmtime/src/imports.rs +42 -18
  133. data/crates/kobako-wasmtime/src/instance_pre.rs +4 -4
  134. data/crates/kobako-wasmtime/src/invocation.rs +91 -15
  135. data/crates/kobako-wasmtime/src/lib.rs +7 -3
  136. data/crates/kobako-wasmtime/src/limiter.rs +130 -12
  137. data/crates/kobako-wasmtime/src/preview1/descriptors.rs +305 -0
  138. data/crates/kobako-wasmtime/src/preview1/differential/mount.rs +9 -20
  139. data/crates/kobako-wasmtime/src/preview1/differential.rs +27 -31
  140. data/crates/kobako-wasmtime/src/preview1/errno.rs +55 -66
  141. data/crates/kobako-wasmtime/src/preview1/fd.rs +347 -312
  142. data/crates/kobako-wasmtime/src/preview1/memory.rs +21 -12
  143. data/crates/kobako-wasmtime/src/preview1/mount_view/wrap.rs +34 -53
  144. data/crates/kobako-wasmtime/src/preview1/mount_view.rs +335 -388
  145. data/crates/kobako-wasmtime/src/preview1/path.rs +56 -121
  146. data/crates/kobako-wasmtime/src/preview1/poll.rs +255 -125
  147. data/crates/kobako-wasmtime/src/preview1/random.rs +125 -0
  148. data/crates/kobako-wasmtime/src/preview1/sock.rs +10 -8
  149. data/crates/kobako-wasmtime/src/preview1/testing.rs +31 -0
  150. data/crates/kobako-wasmtime/src/preview1/testsuite.rs +5 -15
  151. data/crates/kobako-wasmtime/src/preview1.rs +131 -51
  152. data/crates/kobako-wasmtime/src/preview2/abi.rs +227 -0
  153. data/crates/kobako-wasmtime/src/preview2/error.rs +118 -0
  154. data/crates/kobako-wasmtime/src/preview2/filesystem.rs +122 -0
  155. data/crates/kobako-wasmtime/src/preview2/host.rs +4319 -0
  156. data/crates/kobako-wasmtime/src/preview2/http.rs +1587 -0
  157. data/crates/kobako-wasmtime/src/preview2/io.rs +328 -0
  158. data/crates/kobako-wasmtime/src/preview2/sockets.rs +379 -0
  159. data/crates/kobako-wasmtime/src/preview2/table.rs +257 -0
  160. data/crates/kobako-wasmtime/src/preview2.rs +57 -0
  161. data/crates/kobako-wasmtime/src/trap.rs +88 -28
  162. data/crates/kobako-wasmtime/src/waits.rs +59 -0
  163. data/crates/kobako-wasmtime/src/wasi.rs +291 -81
  164. data/crates/kobako-wasmtime/wit/deps/cli.wit +233 -0
  165. data/crates/kobako-wasmtime/wit/deps/clocks.wit +162 -0
  166. data/crates/kobako-wasmtime/wit/deps/filesystem.wit +589 -0
  167. data/crates/kobako-wasmtime/wit/deps/http.wit +733 -0
  168. data/crates/kobako-wasmtime/wit/deps/io.wit +299 -0
  169. data/crates/kobako-wasmtime/wit/deps/random.wit +92 -0
  170. data/crates/kobako-wasmtime/wit/deps/sockets.wit +949 -0
  171. data/crates/kobako-wasmtime/witx/wasi_snapshot_preview1.witx +13 -0
  172. data/data/kobako.wasm +0 -0
  173. data/ext/kobako/Cargo.toml +6 -2
  174. data/ext/kobako/src/{runtime/errors.rs → errors.rs} +34 -26
  175. data/ext/kobako/src/escape.rs +404 -0
  176. data/ext/kobako/src/{runtime/filesystem → filesystem}/grants.rs +34 -32
  177. data/ext/kobako/src/{runtime/filesystem → filesystem}/ruby.rs +158 -170
  178. data/ext/kobako/src/{runtime/filesystem.rs → filesystem.rs} +71 -23
  179. data/ext/kobako/src/fork.rs +72 -0
  180. data/ext/kobako/src/gvl.rs +729 -0
  181. data/ext/kobako/src/handoff.rs +490 -0
  182. data/ext/kobako/src/lib.rs +74 -3
  183. data/ext/kobako/src/network/mock.rs +187 -0
  184. data/ext/kobako/src/network.rs +593 -0
  185. data/ext/kobako/src/pinned_value.rs +44 -0
  186. data/ext/kobako/src/runtime/bridge.rs +58 -50
  187. data/ext/kobako/src/runtime/snapshot.rs +4 -4
  188. data/ext/kobako/src/runtime.rs +272 -163
  189. data/ext/kobako/src/wire.rs +42 -0
  190. data/lib/kobako/catalog/extensions.rb +14 -2
  191. data/lib/kobako/catalog/flags.rb +3 -5
  192. data/lib/kobako/catalog/grants.rb +5 -4
  193. data/lib/kobako/catalog/handles.rb +14 -32
  194. data/lib/kobako/catalog/mount.rb +11 -3
  195. data/lib/kobako/catalog/network.rb +35 -0
  196. data/lib/kobako/catalog/replacements.rb +28 -0
  197. data/lib/kobako/catalog/services.rb +5 -19
  198. data/lib/kobako/catalog/snippets.rb +3 -18
  199. data/lib/kobako/catalog.rb +3 -0
  200. data/lib/kobako/codec/{utils.rb → boundary.rb} +4 -2
  201. data/lib/kobako/codec/decoder.rb +5 -5
  202. data/lib/kobako/codec/ext_types.rb +3 -3
  203. data/lib/kobako/codec/handle_walk.rb +3 -43
  204. data/lib/kobako/codec/state.rb +2 -18
  205. data/lib/kobako/codec/value_budget.rb +133 -41
  206. data/lib/kobako/codec.rb +6 -7
  207. data/lib/kobako/context.rb +24 -11
  208. data/lib/kobako/errors.rb +18 -18
  209. data/lib/kobako/extension.rb +3 -2
  210. data/lib/kobako/filesystem.rb +10 -3
  211. data/lib/kobako/fork.rb +42 -0
  212. data/lib/kobako/handle.rb +2 -3
  213. data/lib/kobako/names.rb +28 -0
  214. data/lib/kobako/network.rb +210 -0
  215. data/lib/kobako/outcome.rb +7 -7
  216. data/lib/kobako/runtime.rb +3 -2
  217. data/lib/kobako/sandbox.rb +73 -35
  218. data/lib/kobako/sandbox_options.rb +42 -109
  219. data/lib/kobako/transport/argument_wrap.rb +64 -0
  220. data/lib/kobako/transport/block_failure.rb +1 -1
  221. data/lib/kobako/transport/dispatcher.rb +6 -6
  222. data/lib/kobako/transport/exposure.rb +26 -15
  223. data/lib/kobako/transport/reflection.rb +21 -4
  224. data/lib/kobako/transport/run.rb +8 -23
  225. data/lib/kobako/transport/yielder.rb +2 -9
  226. data/lib/kobako/transport.rb +1 -0
  227. data/lib/kobako/usage.rb +4 -2
  228. data/lib/kobako/version.rb +1 -1
  229. data/lib/kobako.rb +8 -4
  230. data/release-please-config.json +15 -0
  231. data/sig/kobako/catalog/extensions.rbs +2 -0
  232. data/sig/kobako/catalog/grants.rbs +7 -4
  233. data/sig/kobako/catalog/handles.rbs +2 -2
  234. data/sig/kobako/catalog/mount.rbs +3 -1
  235. data/sig/kobako/catalog/network.rbs +20 -0
  236. data/sig/kobako/catalog/replacements.rbs +14 -0
  237. data/sig/kobako/catalog/services.rbs +0 -4
  238. data/sig/kobako/catalog/snippets.rbs +0 -2
  239. data/sig/kobako/codec/{utils.rbs → boundary.rbs} +2 -2
  240. data/sig/kobako/codec/handle_walk.rbs +0 -6
  241. data/sig/kobako/codec/state.rbs +0 -4
  242. data/sig/kobako/codec/value_budget.rbs +48 -5
  243. data/sig/kobako/codec.rbs +2 -2
  244. data/sig/kobako/context.rbs +3 -1
  245. data/sig/kobako/errors.rbs +4 -7
  246. data/sig/kobako/filesystem.rbs +21 -3
  247. data/sig/kobako/fork.rbs +17 -0
  248. data/sig/kobako/network.rbs +115 -0
  249. data/sig/kobako/outcome.rbs +1 -1
  250. data/sig/kobako/runtime.rbs +32 -3
  251. data/sig/kobako/sandbox.rbs +10 -2
  252. data/sig/kobako/sandbox_options.rbs +29 -40
  253. data/sig/kobako/transport/argument_wrap.rbs +15 -0
  254. data/sig/kobako/transport/error.rbs +1 -1
  255. data/sig/kobako/transport/exposure.rbs +2 -4
  256. data/sig/kobako/transport/reflection.rbs +10 -0
  257. data/sig/kobako/transport/run.rbs +0 -2
  258. data/sig/kobako/transport/yielder.rbs +0 -3
  259. data/sig/kobako/transport.rbs +1 -1
  260. data/sig/kobako.rbs +13 -0
  261. metadata +97 -37
  262. data/crates/kobako-runtime/src/endpoint/capture.rs +0 -115
  263. data/crates/kobako-runtime/src/endpoint/memory_cap.rs +0 -238
  264. data/crates/kobako-runtime/src/filesystem/path.rs +0 -21
  265. data/crates/kobako-runtime/src/vfs/errno.rs +0 -153
  266. data/crates/kobako-runtime/tests/linux_baseline/calls.rs +0 -171
  267. data/crates/kobako-runtime/tests/linux_baseline/concurrent.rs +0 -276
  268. data/crates/kobako-runtime/tests/linux_baseline/kobako.rs +0 -323
  269. data/crates/kobako-runtime/tests/linux_baseline/linux-baseline-expected.txt +0 -16
  270. data/crates/kobako-runtime/tests/linux_baseline/linux.rs +0 -449
  271. data/crates/kobako-runtime/tests/linux_baseline/main.rs +0 -611
  272. data/crates/kobako-runtime/tests/linux_baseline/permissions.rs +0 -236
  273. data/crates/kobako-wasmtime/src/descriptors.rs +0 -200
  274. data/crates/kobako-wasmtime/tests/integration/compile_posture.rs +0 -43
  275. data/crates/kobako-wasmtime/tests/integration/guest_file.rs +0 -1085
  276. data/crates/kobako-wasmtime/tests/integration/main.rs +0 -29
  277. data/crates/kobako-wasmtime/tests/integration/preamble_flags.rs +0 -70
  278. data/crates/kobako-wasmtime/tests/integration/snippet_compile.rs +0 -95
  279. data/crates/kobako-wasmtime/tests/integration/support/mod.rs +0 -30
  280. data/crates/kobako-wasmtime/tests/integration/unanswered_call.rs +0 -86
  281. data/crates/kobako-wasmtime/tests/integration/unsupported_call.rs +0 -51
  282. data/ext/kobako/src/runtime/escape.rs +0 -67
  283. data/ext/kobako/src/runtime/gvl.rs +0 -147
  284. data/ext/kobako/src/runtime/pinned_value.rs +0 -31
  285. data/lib/kobako/constant_name.rb +0 -8
  286. data/lib/kobako/pool.rb +0 -140
  287. data/sig/kobako/constant_name.rbs +0 -3
  288. data/sig/kobako/pool.rbs +0 -42
@@ -0,0 +1,16 @@
1
+ //! Generates the host side of the WASI 0.2 imports a Guest Binary links as a
2
+ //! core module, from the vendored WIT, as wiggle generates preview1's from
3
+ //! `witx/`.
4
+
5
+ #[path = "build/preview2.rs"]
6
+ mod preview2;
7
+
8
+ fn main() {
9
+ let wit = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("wit/deps");
10
+ println!("cargo:rerun-if-changed=build/preview2.rs");
11
+ println!("cargo:rerun-if-changed={}", wit.display());
12
+ let out = std::path::Path::new(&std::env::var("OUT_DIR").expect("cargo sets OUT_DIR"))
13
+ .join("preview2_bindings.rs");
14
+ let source = preview2::generate(&wit).expect("the vendored WIT generates");
15
+ std::fs::write(&out, source).expect("OUT_DIR takes the generated bindings");
16
+ }
@@ -1,10 +1,11 @@
1
- //! Reading the Guest Binary's declared ABI version for the endpoint to
2
- //! accept or refuse.
1
+ //! Reading the Guest Binary's declared ABI version, from its export names,
2
+ //! for the endpoint to accept or refuse, once the artifact has shown it
3
+ //! instantiates.
3
4
  //!
4
5
  //! An artifact reports one ABI version, so the answer belongs to the
5
6
  //! module and not to the sandbox asking for it. The check therefore runs
6
7
  //! alongside the `InstancePre` it guards (`crate::instance_pre`) and is
7
- //! amortised with it, rather than once per `Driver::new`.
8
+ //! amortised with it, rather than once per `Driver::from_file`.
8
9
 
9
10
  use std::time::Duration;
10
11
 
@@ -19,41 +20,29 @@ use kobako_runtime::error::{SetupError, Trap};
19
20
 
20
21
  /// An absent or unequal version is a deterministic artifact fault, so
21
22
  /// every failure is a `SetupError`. `setup_timeout` bounds instantiating
22
- /// the artifact and reading its version, so a start function that never
23
- /// returns fails construction instead of hanging it.
23
+ /// the artifact, so a start function that never returns fails construction
24
+ /// instead of hanging it.
24
25
  pub(crate) fn verify(
25
26
  pre: &InstancePre<Invocation>,
26
27
  setup_timeout: Option<Duration>,
27
28
  ) -> Result<(), SetupError> {
28
29
  let wasi = Wasi::for_probe().map_err(|t| SetupError::Dead(t.to_string()))?;
29
- // The memory cap stays off: it arms per invocation, and the probe is
30
+ // The memory budget stays off: it arms per invocation, and the probe is
30
31
  // none.
31
- let mut store = WtStore::new(load_engine()?, Invocation::new(None, wasi));
32
+ let mut store = WtStore::try_new(load_engine()?, Invocation::new(wasi))
33
+ .map_err(|err| SetupError::Dead(format!("failed to create the probe's store: {err}")))?;
32
34
  trap::arm_deadline(&mut store, setup_timeout);
33
35
  let past_deadline = |err: &wasmtime::Error| {
34
- matches!(trap::cap_trap(err), Some(Trap::Timeout(_))).then(|| {
36
+ matches!(trap::cap_trap_of(err), Some(Trap::Timeout(_))).then(|| {
35
37
  SetupError::Dead(format!(
36
38
  "the Guest Binary did not finish being set up within {:?}",
37
39
  setup_timeout.unwrap_or_default()
38
40
  ))
39
41
  })
40
42
  };
41
- let instance = pre
42
- .instantiate(store.as_context_mut())
43
- .map_err(|e| past_deadline(&e).unwrap_or_else(|| trap::instantiate_err(e)))?;
44
- let Ok(probe) =
45
- instance.get_typed_func::<(), u32>(store.as_context_mut(), "__kobako_abi_version")
46
- else {
47
- return endpoint::verify_abi_version(None);
48
- };
49
- let reported = probe.call(store.as_context_mut(), ()).map_err(|e| {
50
- past_deadline(&e).unwrap_or_else(|| {
51
- SetupError::Dead(format!(
52
- "failed to read the Guest Binary's ABI version: {e}"
53
- ))
54
- })
55
- })?;
56
- endpoint::verify_abi_version(Some(reported))
43
+ pre.instantiate(store.as_context_mut())
44
+ .map_err(|e| past_deadline(&e).unwrap_or_else(|| trap::to_setup_error(e)))?;
45
+ endpoint::verify_abi_version(pre.module().exports().map(|export| export.name()))
57
46
  }
58
47
 
59
48
  #[cfg(test)]
@@ -73,21 +62,13 @@ mod tests {
73
62
  env!("CARGO_MANIFEST_DIR"),
74
63
  "/../../test/fixtures/minimal_spinning_start.wat"
75
64
  );
76
- let config = Config {
77
- timeout: None,
78
- setup_timeout: Some(Duration::from_millis(300)),
79
- memory_limit: None,
80
- stdout_limit: None,
81
- stderr_limit: None,
82
- open_file_limit: None,
83
- profile: Profile::Hermetic,
84
- security: Vec::new(),
85
- };
86
- let built = Driver::new(Path::new(FIXTURE), config);
65
+ let mut config = Config::for_profile(Profile::Hermetic);
66
+ config.limits.setup_timeout = Some(Duration::from_millis(300));
67
+ let built = Driver::from_file(Path::new(FIXTURE), config);
87
68
  assert!(
88
69
  matches!(&built, Err(SetupError::Dead(message)) if message.contains("within 300ms")),
89
- "a Guest Binary whose start never returns through Driver::new must fail construction \
90
- once the setup deadline passes, saying so"
70
+ "a Guest Binary whose start never returns must fail the Driver's construction once \
71
+ the setup deadline passes, saying so"
91
72
  );
92
73
  }
93
74
  }
@@ -1,14 +1,14 @@
1
1
  //! The guest's time and entropy at the WASI layer — the one ambient
2
- //! authority that separates the hermetic rung from permissive. `Wasi::new`
3
- //! wires the frozen sources on `Hermetic` and the live clock on
4
- //! `Permissive`; `Clocks` is what the guest's waits pass on under either.
2
+ //! authority that separates the hermetic profile from permissive. `Wasi::new`
3
+ //! wires the frozen sources on `Hermetic`, and the live clock and the OS's
4
+ //! entropy on `Permissive`; `Clocks` is what the guest reads its time from under either.
5
5
  //!
6
6
  //! `wasmtime-wasi`'s `WasiCtxBuilder` defaults the guest's `wasi:clocks` to
7
7
  //! the host wall / monotonic clock and `wasi:random` to a fresh per-context
8
8
  //! seed. No allowlisted mrbgem reaches these preview1 imports today
9
9
  //! (`build_config/wasi.rb`), but a future libc-backed gem would silently
10
10
  //! obtain real time and host entropy — a covert timing channel and a
11
- //! nondeterminism source the hermetic posture deliberately excludes.
11
+ //! nondeterminism source the hermetic profile deliberately excludes.
12
12
  //! Pinning the clocks to the Unix epoch and the RNG to a constant stream
13
13
  //! makes that denial a property of the host, not merely of the gem allowlist.
14
14
  //!
@@ -16,11 +16,16 @@
16
16
  //! wasmtime epoch interruption against a host `Instant`, never the guest's
17
17
  //! frozen `wasi:clocks/monotonic-clock`.
18
18
 
19
- use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
19
+ use std::time::{Duration, Instant};
20
20
 
21
+ use rand::rand_core::UnwrapErr;
22
+ use rand::rngs::SysRng;
23
+ use wasmtime_wasi::clocks::WallClock;
21
24
  use wasmtime_wasi::random::Deterministic;
22
25
  use wasmtime_wasi::{HostMonotonicClock, HostWallClock};
23
26
 
27
+ use crate::preview2::to_nanos;
28
+
24
29
  /// Wall clock frozen at the Unix epoch — the guest observes no real time.
25
30
  pub(crate) struct FrozenWallClock;
26
31
 
@@ -53,6 +58,13 @@ pub(crate) fn deterministic_rng() -> Deterministic {
53
58
  Deterministic::new(vec![0])
54
59
  }
55
60
 
61
+ /// The host's entropy, asked of the OS on each draw: a generator seeded once
62
+ /// from a thread's `ThreadRng`, as wasmtime-wasi's default is, draws the
63
+ /// same bytes in a forked child as in its parent.
64
+ pub(crate) fn host_rng() -> UnwrapErr<SysRng> {
65
+ UnwrapErr(SysRng)
66
+ }
67
+
56
68
  /// The host's monotonic clock read from a fixed origin. The guest's
57
69
  /// `clock_time_get` and a wait it subscribes to share it, so both agree on
58
70
  /// what an instant means.
@@ -75,39 +87,51 @@ impl HostMonotonicClock for LiveMonotonicClock {
75
87
  }
76
88
 
77
89
  fn now(&self) -> u64 {
78
- u64::try_from(self.origin.elapsed().as_nanos()).unwrap_or(u64::MAX)
90
+ to_nanos(self.origin.elapsed())
79
91
  }
80
92
  }
81
93
 
82
- /// The clocks the guest observes. A wait it subscribes to passes on the
83
- /// same clocks: frozen ones never advance, so the wait ends at once.
94
+ /// The host's wall clock, read as wasmtime-wasi's own. The guest's
95
+ /// `clock_time_get` and a wait it subscribes to share it, so both agree on
96
+ /// what a time means.
97
+ #[derive(Clone, Copy)]
98
+ pub(crate) struct LiveWallClock;
99
+
100
+ impl HostWallClock for LiveWallClock {
101
+ fn resolution(&self) -> Duration {
102
+ WallClock.resolution()
103
+ }
104
+
105
+ fn now(&self) -> Duration {
106
+ WallClock.now()
107
+ }
108
+ }
109
+
110
+ /// The clocks the guest observes, which a clock subscription reads its
111
+ /// absolute time against.
84
112
  #[derive(Clone, Copy)]
85
113
  pub(crate) enum Clocks {
86
114
  Frozen,
87
- Live(LiveMonotonicClock),
115
+ Live {
116
+ monotonic: LiveMonotonicClock,
117
+ wall: LiveWallClock,
118
+ },
88
119
  }
89
120
 
90
121
  impl Clocks {
91
122
  pub(crate) fn monotonic_now(&self) -> u64 {
92
123
  match self {
93
124
  Self::Frozen => FrozenMonotonicClock.now(),
94
- Self::Live(clock) => clock.now(),
125
+ Self::Live { monotonic, .. } => monotonic.now(),
95
126
  }
96
127
  }
97
128
 
98
129
  pub(crate) fn wall_now(&self) -> u64 {
99
130
  let since_epoch = match self {
100
131
  Self::Frozen => FrozenWallClock.now(),
101
- Self::Live(_) => SystemTime::now()
102
- .duration_since(UNIX_EPOCH)
103
- .unwrap_or(Duration::ZERO),
132
+ Self::Live { wall, .. } => wall.now(),
104
133
  };
105
- u64::try_from(since_epoch.as_nanos()).unwrap_or(u64::MAX)
106
- }
107
-
108
- /// Whether a wait on these clocks takes host time.
109
- pub(crate) fn advances(&self) -> bool {
110
- matches!(self, Self::Live(_))
134
+ to_nanos(since_epoch)
111
135
  }
112
136
  }
113
137
 
@@ -0,0 +1,95 @@
1
+ //! The cache directory on Unix, reached through one descriptor: every step
2
+ //! after the trust check goes through it, so a path swapped after the check
3
+ //! reaches nothing.
4
+
5
+ use std::ffi::{OsStr, OsString};
6
+ use std::fs;
7
+ use std::io;
8
+ use std::os::unix::ffi::OsStrExt;
9
+ use std::os::unix::fs::DirBuilderExt;
10
+ use std::path::{Path, PathBuf};
11
+ use std::sync::atomic::{AtomicU64, Ordering};
12
+ use std::time::{Duration, SystemTime, UNIX_EPOCH};
13
+
14
+ use rustix::fd::OwnedFd;
15
+ use rustix::fs::{
16
+ fstat, fsync, open, openat, renameat, statat, unlinkat, AtFlags, Dir, Mode, OFlags,
17
+ };
18
+
19
+ pub(super) struct PrivateDir(OwnedFd);
20
+
21
+ impl PrivateDir {
22
+ /// Create `dir` owner-only (`0700`) so no other local user can plant an
23
+ /// artifact the unsafe deserialize would trust.
24
+ pub(super) fn create(dir: &Path) -> io::Result<()> {
25
+ fs::DirBuilder::new()
26
+ .recursive(true)
27
+ .mode(0o700)
28
+ .create(dir)
29
+ }
30
+
31
+ /// `dir`, once it upholds the trust the unsafe deserialize relies on: a
32
+ /// directory rather than a link in its place, owned by the current
33
+ /// effective user and writable by no one else.
34
+ pub(super) fn open(dir: &Path) -> Option<Self> {
35
+ let flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
36
+ let fd = open(dir, flags, Mode::empty()).ok()?;
37
+ let stat = fstat(&fd).ok()?;
38
+ let owned = stat.st_uid == rustix::process::geteuid().as_raw();
39
+ (owned && stat.st_mode & 0o022 == 0).then_some(Self(fd))
40
+ }
41
+
42
+ /// The entry `name`, opened to read without following a link.
43
+ pub(super) fn open_entry(&self, name: &OsStr) -> Option<fs::File> {
44
+ let flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
45
+ let fd = openat(&self.0, name, flags, Mode::empty()).ok()?;
46
+ Some(fs::File::from(fd))
47
+ }
48
+
49
+ /// A temp file no other writer shares: two threads of one process storing
50
+ /// the same artifact at once would otherwise write into one file, and a
51
+ /// reader could load the interleaved bytes the unsafe deserialize trusts.
52
+ pub(super) fn create_temp(&self, name: &OsStr) -> Option<(PathBuf, fs::File)> {
53
+ static NEXT_TEMP: AtomicU64 = AtomicU64::new(0);
54
+ let serial = NEXT_TEMP.fetch_add(1, Ordering::Relaxed);
55
+ let tmp = Path::new(name).with_extension(format!("tmp{}.{serial}", std::process::id()));
56
+ let flags =
57
+ OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC;
58
+ let fd = openat(&self.0, &tmp, flags, Mode::RUSR | Mode::WUSR).ok()?;
59
+ Some((tmp, fs::File::from(fd)))
60
+ }
61
+
62
+ /// Move `tmp` over `name`, syncing the directory so the new name
63
+ /// survives a crash; whether it moved.
64
+ pub(super) fn rename(&self, tmp: &Path, name: &OsStr) -> bool {
65
+ let moved = renameat(&self.0, tmp, &self.0, name).is_ok();
66
+ if moved {
67
+ let _ = fsync(&self.0);
68
+ }
69
+ moved
70
+ }
71
+
72
+ /// Each entry's name and when it was last modified, read without
73
+ /// following a link; one whose time cannot be read is left out.
74
+ pub(super) fn entries(&self) -> Vec<(OsString, SystemTime)> {
75
+ let Ok(mut entries) = Dir::read_from(&self.0) else {
76
+ return Vec::new();
77
+ };
78
+ let mut found = Vec::new();
79
+ while let Some(Ok(entry)) = entries.read() {
80
+ let name = entry.file_name();
81
+ let modified = statat(&self.0, name, AtFlags::SYMLINK_NOFOLLOW)
82
+ .ok()
83
+ .and_then(|stat| u64::try_from(stat.st_mtime).ok())
84
+ .map(|secs| UNIX_EPOCH + Duration::from_secs(secs));
85
+ if let Some(modified) = modified {
86
+ found.push((OsStr::from_bytes(name.to_bytes()).to_owned(), modified));
87
+ }
88
+ }
89
+ found
90
+ }
91
+
92
+ pub(super) fn remove(&self, name: &OsStr) {
93
+ let _ = unlinkat(&self.0, name, AtFlags::empty());
94
+ }
95
+ }
@@ -0,0 +1,359 @@
1
+ //! The cache directory on Windows, held open without sharing deletion, so it
2
+ //! is neither renamed nor replaced while held. An entry is reached by its path
3
+ //! beneath it, so each one opened is checked to stand in the held directory
4
+ //! itself; Windows lets anyone bypass traversal, so an entry is trusted only
5
+ //! as its directory is.
6
+
7
+ use std::ffi::{c_void, OsStr, OsString};
8
+ use std::fs;
9
+ use std::io;
10
+ use std::os::windows::ffi::{OsStrExt, OsStringExt};
11
+ use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
12
+ use std::os::windows::io::AsRawHandle;
13
+ use std::path::{Path, PathBuf};
14
+ use std::ptr;
15
+ use std::sync::atomic::{AtomicU64, Ordering};
16
+ use std::time::SystemTime;
17
+
18
+ use windows_sys::Win32::Foundation::{
19
+ CloseHandle, LocalFree, ERROR_ALREADY_EXISTS, GENERIC_ALL, GENERIC_WRITE, HANDLE,
20
+ };
21
+ use windows_sys::Win32::Security::Authorization::{
22
+ ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, GetSecurityInfo,
23
+ SDDL_REVISION_1, SE_FILE_OBJECT,
24
+ };
25
+ use windows_sys::Win32::Security::{
26
+ EqualSid, GetAce, GetTokenInformation, IsWellKnownSid, TokenUser, WinBuiltinAdministratorsSid,
27
+ WinLocalSystemSid, ACCESS_ALLOWED_ACE, ACL, DACL_SECURITY_INFORMATION,
28
+ OWNER_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, PSID, SECURITY_ATTRIBUTES, TOKEN_QUERY,
29
+ TOKEN_USER,
30
+ };
31
+ use windows_sys::Win32::Storage::FileSystem::{
32
+ CreateDirectoryW, GetFinalPathNameByHandleW, DELETE, FILE_APPEND_DATA,
33
+ FILE_ATTRIBUTE_REPARSE_POINT, FILE_DELETE_CHILD, FILE_FLAG_BACKUP_SEMANTICS,
34
+ FILE_FLAG_OPEN_REPARSE_POINT, FILE_GENERIC_EXECUTE, FILE_GENERIC_READ, FILE_LIST_DIRECTORY,
35
+ FILE_NAME_NORMALIZED, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, FILE_SHARE_WRITE,
36
+ FILE_WRITE_ATTRIBUTES, FILE_WRITE_DATA, FILE_WRITE_EA, READ_CONTROL, WRITE_DAC, WRITE_OWNER,
37
+ };
38
+ use windows_sys::Win32::System::SystemServices::ACCESS_ALLOWED_ACE_TYPE;
39
+ use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
40
+
41
+ /// Every right that changes what an object holds or who may change it.
42
+ const WRITE_RIGHTS: u32 = FILE_WRITE_DATA
43
+ | FILE_APPEND_DATA
44
+ | FILE_WRITE_EA
45
+ | FILE_DELETE_CHILD
46
+ | FILE_WRITE_ATTRIBUTES
47
+ | DELETE
48
+ | WRITE_DAC
49
+ | WRITE_OWNER
50
+ | GENERIC_WRITE
51
+ | GENERIC_ALL;
52
+
53
+ pub(super) struct PrivateDir {
54
+ path: PathBuf,
55
+ /// Held so the directory stays where it was checked.
56
+ _held: fs::File,
57
+ /// Where the directory stands, as each entry opened is compared to it.
58
+ resolved: PathBuf,
59
+ }
60
+
61
+ impl PrivateDir {
62
+ /// Create `dir` and the directories above it; `dir` itself takes a
63
+ /// protected DACL granting only the current user, SYSTEM, and the
64
+ /// Administrators, so no other local user can plant an artifact the
65
+ /// unsafe deserialize would trust.
66
+ pub(super) fn create(dir: &Path) -> io::Result<()> {
67
+ if let Some(parent) = dir.parent() {
68
+ fs::create_dir_all(parent)?;
69
+ }
70
+ let user = current_user()?;
71
+ let sddl = format!(
72
+ "D:P(A;OICI;FA;;;{})(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)",
73
+ user.string()?
74
+ );
75
+ let descriptor = Descriptor::from_sddl(&sddl)?;
76
+ let attributes = SECURITY_ATTRIBUTES {
77
+ nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
78
+ lpSecurityDescriptor: descriptor.0,
79
+ bInheritHandle: 0,
80
+ };
81
+ let wide = wide(dir.as_os_str());
82
+ // SAFETY: `wide` is NUL-terminated and `attributes` points at a
83
+ // descriptor that lives until the call returns.
84
+ if unsafe { CreateDirectoryW(wide.as_ptr(), &attributes) } != 0 {
85
+ return Ok(());
86
+ }
87
+ match io::Error::last_os_error() {
88
+ err if err.raw_os_error() == Some(ERROR_ALREADY_EXISTS as i32) => Ok(()),
89
+ err => Err(err),
90
+ }
91
+ }
92
+
93
+ /// `dir`, once it upholds the trust the unsafe deserialize relies on: a
94
+ /// directory rather than a link in its place, owned by the current user,
95
+ /// and writable by no one else but SYSTEM and the Administrators, who may
96
+ /// write anything.
97
+ pub(super) fn open(dir: &Path) -> Option<Self> {
98
+ let held = fs::OpenOptions::new()
99
+ .access_mode(FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES | READ_CONTROL)
100
+ .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
101
+ .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
102
+ .open(dir)
103
+ .ok()?;
104
+ let metadata = held.metadata().ok()?;
105
+ if !metadata.is_dir() || is_reparse_point(&metadata) || !trusted(&held) {
106
+ return None;
107
+ }
108
+ let resolved = resolved_path(&held)?;
109
+ Some(Self {
110
+ path: dir.to_path_buf(),
111
+ _held: held,
112
+ resolved,
113
+ })
114
+ }
115
+
116
+ /// The entry `name`, opened without following a link as wasmtime opens a
117
+ /// file to map: readable and executable, its code mapped as such, and
118
+ /// shared only with readers, so its bytes stay as read while mapped. It
119
+ /// may also refresh its own time.
120
+ pub(super) fn open_entry(&self, name: &OsStr) -> Option<fs::File> {
121
+ let file = fs::OpenOptions::new()
122
+ .access_mode(FILE_GENERIC_READ | FILE_GENERIC_EXECUTE | FILE_WRITE_ATTRIBUTES)
123
+ .share_mode(FILE_SHARE_READ)
124
+ .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
125
+ .open(self.path.join(name))
126
+ .ok()?;
127
+ let metadata = file.metadata().ok()?;
128
+ let beneath = resolved_path(&file)?.parent() == Some(self.resolved.as_path());
129
+ (metadata.is_file() && !is_reparse_point(&metadata) && beneath && trusted(&file))
130
+ .then_some(file)
131
+ }
132
+
133
+ /// A temp file no other writer shares: two threads of one process storing
134
+ /// the same artifact at once would otherwise write into one file, and a
135
+ /// reader could load the interleaved bytes the unsafe deserialize trusts.
136
+ pub(super) fn create_temp(&self, name: &OsStr) -> Option<(PathBuf, fs::File)> {
137
+ static NEXT_TEMP: AtomicU64 = AtomicU64::new(0);
138
+ let serial = NEXT_TEMP.fetch_add(1, Ordering::Relaxed);
139
+ let tmp = Path::new(name).with_extension(format!("tmp{}.{serial}", std::process::id()));
140
+ let file = fs::OpenOptions::new()
141
+ .write(true)
142
+ .create_new(true)
143
+ .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
144
+ .open(self.path.join(&tmp))
145
+ .ok()?;
146
+ Some((tmp, file))
147
+ }
148
+
149
+ /// Move `tmp` over `name`; whether it moved. One another process holds
150
+ /// open stays, as Windows refuses to replace it.
151
+ pub(super) fn rename(&self, tmp: &Path, name: &OsStr) -> bool {
152
+ fs::rename(self.path.join(tmp), self.path.join(name)).is_ok()
153
+ }
154
+
155
+ /// Each entry's name and when it was last modified, read without
156
+ /// following a link; one whose time cannot be read is left out.
157
+ pub(super) fn entries(&self) -> Vec<(OsString, SystemTime)> {
158
+ let Ok(entries) = fs::read_dir(&self.path) else {
159
+ return Vec::new();
160
+ };
161
+ entries
162
+ .filter_map(Result::ok)
163
+ .filter_map(|entry| {
164
+ let modified = fs::symlink_metadata(entry.path()).ok()?.modified().ok()?;
165
+ Some((entry.file_name(), modified))
166
+ })
167
+ .collect()
168
+ }
169
+
170
+ pub(super) fn remove(&self, name: &OsStr) {
171
+ let _ = fs::remove_file(self.path.join(name));
172
+ }
173
+ }
174
+
175
+ fn is_reparse_point(metadata: &fs::Metadata) -> bool {
176
+ metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
177
+ }
178
+
179
+ /// Where `file` stands once every link on its way is resolved.
180
+ fn resolved_path(file: &fs::File) -> Option<PathBuf> {
181
+ let handle = file.as_raw_handle() as HANDLE;
182
+ let mut buf = vec![0u16; 512];
183
+ loop {
184
+ // SAFETY: `buf` holds `buf.len()` wide characters for the call to fill.
185
+ let len = unsafe {
186
+ GetFinalPathNameByHandleW(
187
+ handle,
188
+ buf.as_mut_ptr(),
189
+ buf.len() as u32,
190
+ FILE_NAME_NORMALIZED,
191
+ )
192
+ } as usize;
193
+ match len {
194
+ 0 => return None,
195
+ len if len < buf.len() => return Some(OsString::from_wide(&buf[..len]).into()),
196
+ len => buf.resize(len, 0),
197
+ }
198
+ }
199
+ }
200
+
201
+ /// Whether only the user, SYSTEM, and the Administrators own `file` or hold
202
+ /// a right to change it, its inheritable entries included, as what they
203
+ /// grant reaches each entry created beneath. An owner may grant itself any
204
+ /// right, and an elevated process's objects are owned by the Administrators.
205
+ fn trusted(file: &fs::File) -> bool {
206
+ let Ok(user) = current_user() else {
207
+ return false;
208
+ };
209
+ let mut owner: PSID = ptr::null_mut();
210
+ let mut dacl: *mut ACL = ptr::null_mut();
211
+ let mut descriptor: PSECURITY_DESCRIPTOR = ptr::null_mut();
212
+ // SAFETY: each out-pointer is valid; `descriptor` owns the owner and the
213
+ // DACL, and is freed below.
214
+ let status = unsafe {
215
+ GetSecurityInfo(
216
+ file.as_raw_handle() as HANDLE,
217
+ SE_FILE_OBJECT,
218
+ OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
219
+ &mut owner,
220
+ ptr::null_mut(),
221
+ &mut dacl,
222
+ ptr::null_mut(),
223
+ &mut descriptor,
224
+ )
225
+ };
226
+ if status != 0 {
227
+ return false;
228
+ }
229
+ let descriptor = Descriptor(descriptor);
230
+ // SAFETY: `owner` and `dacl` point into `descriptor`, alive for the scope.
231
+ let trusted =
232
+ unsafe { user.permits(owner) && !dacl.is_null() && grants_write_only_to(dacl, &user) };
233
+ drop(descriptor);
234
+ trusted
235
+ }
236
+
237
+ /// Whether every allowing entry of `dacl` that grants a right to change the
238
+ /// object names the user, SYSTEM, or the Administrators.
239
+ ///
240
+ /// # Safety
241
+ ///
242
+ /// `dacl` must point at a valid ACL.
243
+ unsafe fn grants_write_only_to(dacl: *mut ACL, user: &User) -> bool {
244
+ for index in 0..unsafe { (*dacl).AceCount } {
245
+ let mut ace: *mut c_void = ptr::null_mut();
246
+ // SAFETY: `index` is below the ACL's count.
247
+ if unsafe { GetAce(dacl, u32::from(index), &mut ace) } == 0 {
248
+ return false;
249
+ }
250
+ let allowed = ace.cast::<ACCESS_ALLOWED_ACE>();
251
+ // SAFETY: every ACE starts with its header; an allowing one carries
252
+ // its mask and SID after it.
253
+ let (kind, mask) = unsafe { ((*allowed).Header.AceType, (*allowed).Mask) };
254
+ if u32::from(kind) != ACCESS_ALLOWED_ACE_TYPE || mask & WRITE_RIGHTS == 0 {
255
+ continue;
256
+ }
257
+ let sid: PSID = unsafe { ptr::addr_of_mut!((*allowed).SidStart).cast() };
258
+ // SAFETY: `sid` is the SID the allowing entry holds.
259
+ if !unsafe { user.permits(sid) } {
260
+ return false;
261
+ }
262
+ }
263
+ true
264
+ }
265
+
266
+ /// The current process's user, as its token names it.
267
+ struct User(Vec<u8>);
268
+
269
+ impl User {
270
+ fn sid(&self) -> PSID {
271
+ // SAFETY: the buffer holds a `TOKEN_USER` whose SID points within it.
272
+ unsafe { (*self.0.as_ptr().cast::<TOKEN_USER>()).User.Sid }
273
+ }
274
+
275
+ /// Whether `sid` is the user, SYSTEM, or the Administrators.
276
+ ///
277
+ /// # Safety
278
+ ///
279
+ /// `sid` must point at a valid SID.
280
+ unsafe fn permits(&self, sid: PSID) -> bool {
281
+ unsafe {
282
+ EqualSid(sid, self.sid()) != 0
283
+ || IsWellKnownSid(sid, WinLocalSystemSid) != 0
284
+ || IsWellKnownSid(sid, WinBuiltinAdministratorsSid) != 0
285
+ }
286
+ }
287
+
288
+ /// The SID as SDDL writes it.
289
+ fn string(&self) -> io::Result<String> {
290
+ let mut text = ptr::null_mut();
291
+ // SAFETY: `text` receives a buffer freed below.
292
+ if unsafe { ConvertSidToStringSidW(self.sid(), &mut text) } == 0 {
293
+ return Err(io::Error::last_os_error());
294
+ }
295
+ // SAFETY: `text` is NUL-terminated.
296
+ let len = (0..).take_while(|&i| unsafe { *text.add(i) } != 0).count();
297
+ let string = String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(text, len) });
298
+ unsafe { LocalFree(text.cast()) };
299
+ Ok(string)
300
+ }
301
+ }
302
+
303
+ fn current_user() -> io::Result<User> {
304
+ let mut token: HANDLE = ptr::null_mut();
305
+ // SAFETY: `token` receives a handle closed below.
306
+ if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
307
+ return Err(io::Error::last_os_error());
308
+ }
309
+ let mut len = 0;
310
+ // SAFETY: a first call with no buffer answers the length it needs.
311
+ unsafe { GetTokenInformation(token, TokenUser, ptr::null_mut(), 0, &mut len) };
312
+ let mut buf = vec![0u8; len as usize];
313
+ // SAFETY: `buf` holds `len` bytes.
314
+ let filled =
315
+ unsafe { GetTokenInformation(token, TokenUser, buf.as_mut_ptr().cast(), len, &mut len) };
316
+ let result = match filled {
317
+ 0 => Err(io::Error::last_os_error()),
318
+ _ => Ok(User(buf)),
319
+ };
320
+ unsafe { CloseHandle(token) };
321
+ result
322
+ }
323
+
324
+ /// A security descriptor Windows allocated, freed once dropped.
325
+ struct Descriptor(PSECURITY_DESCRIPTOR);
326
+
327
+ impl Descriptor {
328
+ fn from_sddl(sddl: &str) -> io::Result<Self> {
329
+ let wide = wide(OsStr::new(sddl));
330
+ let mut descriptor = ptr::null_mut();
331
+ // SAFETY: `wide` is NUL-terminated; `descriptor` receives a buffer
332
+ // the drop frees.
333
+ let made = unsafe {
334
+ ConvertStringSecurityDescriptorToSecurityDescriptorW(
335
+ wide.as_ptr(),
336
+ SDDL_REVISION_1,
337
+ &mut descriptor,
338
+ ptr::null_mut(),
339
+ )
340
+ };
341
+ match made {
342
+ 0 => Err(io::Error::last_os_error()),
343
+ _ => Ok(Self(descriptor)),
344
+ }
345
+ }
346
+ }
347
+
348
+ impl Drop for Descriptor {
349
+ fn drop(&mut self) {
350
+ if !self.0.is_null() {
351
+ // SAFETY: Windows allocated the descriptor with `LocalAlloc`.
352
+ unsafe { LocalFree(self.0) };
353
+ }
354
+ }
355
+ }
356
+
357
+ fn wide(text: &OsStr) -> Vec<u16> {
358
+ text.encode_wide().chain(Some(0)).collect()
359
+ }