packages feed

workcell (empty) → 0.1.2

raw patch · 14 files changed

+4285/−0 lines, 14 filesdep +aesondep +basedep +bytestring

Dependencies added: aeson, base, bytestring, directory, extra, filepath, hspec, network, process, simple-cmd, simple-cmd-args, tasty, tasty-bench, unix

Files

+ COPYING.md view
@@ -0,0 +1,502 @@+# GNU LESSER GENERAL PUBLIC LICENSE++Version 2.1, February 1999++    Copyright (C) 1991, 1999 Free Software Foundation, Inc.+    <https://fsf.org/>++    Everyone is permitted to copy and distribute verbatim copies+    of this license document, but changing it is not allowed.++    [This is the first released version of the Lesser GPL.  It also counts+     as the successor of the GNU Library Public License, version 2, hence+     the version number 2.1.]++## Preamble++The licenses for most software are designed to take away your freedom+to share and change it. By contrast, the GNU General Public Licenses+are intended to guarantee your freedom to share and change free+software--to make sure the software is free for all its users.++This license, the Lesser General Public License, applies to some+specially designated software packages--typically libraries--of the+Free Software Foundation and other authors who decide to use it. You+can use it too, but we suggest you first think carefully about whether+this license or the ordinary General Public License is the better+strategy to use in any particular case, based on the explanations+below.++When we speak of free software, we are referring to freedom of use,+not price. Our General Public Licenses are designed to make sure that+you have the freedom to distribute copies of free software (and charge+for this service if you wish); that you receive source code or can get+it if you want it; that you can change the software and use pieces of+it in new free programs; and that you are informed that you can do+these things.++To protect your rights, we need to make restrictions that forbid+distributors to deny you these rights or to ask you to surrender these+rights. These restrictions translate to certain responsibilities for+you if you distribute copies of the library or if you modify it.++For example, if you distribute copies of the library, whether gratis+or for a fee, you must give the recipients all the rights that we gave+you. You must make sure that they, too, receive or can get the source+code. If you link other code with the library, you must provide+complete object files to the recipients, so that they can relink them+with the library after making changes to the library and recompiling+it. And you must show them these terms so they know their rights.++We protect your rights with a two-step method: (1) we copyright the+library, and (2) we offer you this license, which gives you legal+permission to copy, distribute and/or modify the library.++To protect each distributor, we want to make it very clear that there+is no warranty for the free library. Also, if the library is modified+by someone else and passed on, the recipients should know that what+they have is not the original version, so that the original author's+reputation will not be affected by problems that might be introduced+by others.++Finally, software patents pose a constant threat to the existence of+any free program. We wish to make sure that a company cannot+effectively restrict the users of a free program by obtaining a+restrictive license from a patent holder. Therefore, we insist that+any patent license obtained for a version of the library must be+consistent with the full freedom of use specified in this license.++Most GNU software, including some libraries, is covered by the+ordinary GNU General Public License. This license, the GNU Lesser+General Public License, applies to certain designated libraries, and+is quite different from the ordinary General Public License. We use+this license for certain libraries in order to permit linking those+libraries into non-free programs.++When a program is linked with a library, whether statically or using a+shared library, the combination of the two is legally speaking a+combined work, a derivative of the original library. The ordinary+General Public License therefore permits such linking only if the+entire combination fits its criteria of freedom. The Lesser General+Public License permits more lax criteria for linking other code with+the library.++We call this license the "Lesser" General Public License because it+does Less to protect the user's freedom than the ordinary General+Public License. It also provides other free software developers Less+of an advantage over competing non-free programs. These disadvantages+are the reason we use the ordinary General Public License for many+libraries. However, the Lesser license provides advantages in certain+special circumstances.++For example, on rare occasions, there may be a special need to+encourage the widest possible use of a certain library, so that it+becomes a de-facto standard. To achieve this, non-free programs must+be allowed to use the library. A more frequent case is that a free+library does the same job as widely used non-free libraries. In this+case, there is little to gain by limiting the free library to free+software only, so we use the Lesser General Public License.++In other cases, permission to use a particular library in non-free+programs enables a greater number of people to use a large body of+free software. For example, permission to use the GNU C Library in+non-free programs enables many more people to use the whole GNU+operating system, as well as its variant, the GNU/Linux operating+system.++Although the Lesser General Public License is Less protective of the+users' freedom, it does ensure that the user of a program that is+linked with the Library has the freedom and the wherewithal to run+that program using a modified version of the Library.++The precise terms and conditions for copying, distribution and+modification follow. Pay close attention to the difference between a+"work based on the library" and a "work that uses the library". The+former contains code derived from the library, whereas the latter must+be combined with the library in order to run.++## TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION++**0.** This License Agreement applies to any software library or other+program which contains a notice placed by the copyright holder or+other authorized party saying it may be distributed under the terms of+this Lesser General Public License (also called "this License"). Each+licensee is addressed as "you".++A "library" means a collection of software functions and/or data+prepared so as to be conveniently linked with application programs+(which use some of those functions and data) to form executables.++The "Library", below, refers to any such software library or work+which has been distributed under these terms. A "work based on the+Library" means either the Library or any derivative work under+copyright law: that is to say, a work containing the Library or a+portion of it, either verbatim or with modifications and/or translated+straightforwardly into another language. (Hereinafter, translation is+included without limitation in the term "modification".)++"Source code" for a work means the preferred form of the work for+making modifications to it. For a library, complete source code means+all the source code for all modules it contains, plus any associated+interface definition files, plus the scripts used to control+compilation and installation of the library.++Activities other than copying, distribution and modification are not+covered by this License; they are outside its scope. The act of+running a program using the Library is not restricted, and output from+such a program is covered only if its contents constitute a work based+on the Library (independent of the use of the Library in a tool for+writing it). Whether that is true depends on what the Library does and+what the program that uses the Library does.++**1.** You may copy and distribute verbatim copies of the Library's+complete source code as you receive it, in any medium, provided that+you conspicuously and appropriately publish on each copy an+appropriate copyright notice and disclaimer of warranty; keep intact+all the notices that refer to this License and to the absence of any+warranty; and distribute a copy of this License along with the+Library.++You may charge a fee for the physical act of transferring a copy, and+you may at your option offer warranty protection in exchange for a+fee.++**2.** You may modify your copy or copies of the Library or any+portion of it, thus forming a work based on the Library, and copy and+distribute such modifications or work under the terms of Section 1+above, provided that you also meet all of these conditions:++-   **a)** The modified work must itself be a software library.+-   **b)** You must cause the files modified to carry prominent+    notices stating that you changed the files and the date of+    any change.+-   **c)** You must cause the whole of the work to be licensed at no+    charge to all third parties under the terms of this License.+-   **d)** If a facility in the modified Library refers to a function+    or a table of data to be supplied by an application program that+    uses the facility, other than as an argument passed when the+    facility is invoked, then you must make a good faith effort to+    ensure that, in the event an application does not supply such+    function or table, the facility still operates, and performs+    whatever part of its purpose remains meaningful.++    (For example, a function in a library to compute square roots has+    a purpose that is entirely well-defined independent of+    the application. Therefore, Subsection 2d requires that any+    application-supplied function or table used by this function must+    be optional: if the application does not supply it, the square+    root function must still compute square roots.)++These requirements apply to the modified work as a whole. If+identifiable sections of that work are not derived from the Library,+and can be reasonably considered independent and separate works in+themselves, then this License, and its terms, do not apply to those+sections when you distribute them as separate works. But when you+distribute the same sections as part of a whole which is a work based+on the Library, the distribution of the whole must be on the terms of+this License, whose permissions for other licensees extend to the+entire whole, and thus to each and every part regardless of who wrote+it.++Thus, it is not the intent of this section to claim rights or contest+your rights to work written entirely by you; rather, the intent is to+exercise the right to control the distribution of derivative or+collective works based on the Library.++In addition, mere aggregation of another work not based on the Library+with the Library (or with a work based on the Library) on a volume of+a storage or distribution medium does not bring the other work under+the scope of this License.++**3.** You may opt to apply the terms of the ordinary GNU General+Public License instead of this License to a given copy of the Library.+To do this, you must alter all the notices that refer to this License,+so that they refer to the ordinary GNU General Public License, version+2, instead of to this License. (If a newer version than version 2 of+the ordinary GNU General Public License has appeared, then you can+specify that version instead if you wish.) Do not make any other+change in these notices.++Once this change is made in a given copy, it is irreversible for that+copy, so the ordinary GNU General Public License applies to all+subsequent copies and derivative works made from that copy.++This option is useful when you wish to copy part of the code of the+Library into a program that is not a library.++**4.** You may copy and distribute the Library (or a portion or+derivative of it, under Section 2) in object code or executable form+under the terms of Sections 1 and 2 above provided that you accompany+it with the complete corresponding machine-readable source code, which+must be distributed under the terms of Sections 1 and 2 above on a+medium customarily used for software interchange.++If distribution of object code is made by offering access to copy from+a designated place, then offering equivalent access to copy the source+code from the same place satisfies the requirement to distribute the+source code, even though third parties are not compelled to copy the+source along with the object code.++**5.** A program that contains no derivative of any portion of the+Library, but is designed to work with the Library by being compiled or+linked with it, is called a "work that uses the Library". Such a work,+in isolation, is not a derivative work of the Library, and therefore+falls outside the scope of this License.++However, linking a "work that uses the Library" with the Library+creates an executable that is a derivative of the Library (because it+contains portions of the Library), rather than a "work that uses the+library". The executable is therefore covered by this License. Section+6 states terms for distribution of such executables.++When a "work that uses the Library" uses material from a header file+that is part of the Library, the object code for the work may be a+derivative work of the Library even though the source code is not.+Whether this is true is especially significant if the work can be+linked without the Library, or if the work is itself a library. The+threshold for this to be true is not precisely defined by law.++If such an object file uses only numerical parameters, data structure+layouts and accessors, and small macros and small inline functions+(ten lines or less in length), then the use of the object file is+unrestricted, regardless of whether it is legally a derivative work.+(Executables containing this object code plus portions of the Library+will still fall under Section 6.)++Otherwise, if the work is a derivative of the Library, you may+distribute the object code for the work under the terms of Section 6.+Any executables containing that work also fall under Section 6,+whether or not they are linked directly with the Library itself.++**6.** As an exception to the Sections above, you may also combine or+link a "work that uses the Library" with the Library to produce a work+containing portions of the Library, and distribute that work under+terms of your choice, provided that the terms permit modification of+the work for the customer's own use and reverse engineering for+debugging such modifications.++You must give prominent notice with each copy of the work that the+Library is used in it and that the Library and its use are covered by+this License. You must supply a copy of this License. If the work+during execution displays copyright notices, you must include the+copyright notice for the Library among them, as well as a reference+directing the user to the copy of this License. Also, you must do one+of these things:++-   **a)** Accompany the work with the complete corresponding+    machine-readable source code for the Library including whatever+    changes were used in the work (which must be distributed under+    Sections 1 and 2 above); and, if the work is an executable linked+    with the Library, with the complete machine-readable "work that+    uses the Library", as object code and/or source code, so that the+    user can modify the Library and then relink to produce a modified+    executable containing the modified Library. (It is understood that+    the user who changes the contents of definitions files in the+    Library will not necessarily be able to recompile the application+    to use the modified definitions.)+-   **b)** Use a suitable shared library mechanism for linking with+    the Library. A suitable mechanism is one that (1) uses at run time+    a copy of the library already present on the user's computer+    system, rather than copying library functions into the executable,+    and (2) will operate properly with a modified version of the+    library, if the user installs one, as long as the modified version+    is interface-compatible with the version that the work was+    made with.+-   **c)** Accompany the work with a written offer, valid for at least+    three years, to give the same user the materials specified in+    Subsection 6a, above, for a charge no more than the cost of+    performing this distribution.+-   **d)** If distribution of the work is made by offering access to+    copy from a designated place, offer equivalent access to copy the+    above specified materials from the same place.+-   **e)** Verify that the user has already received a copy of these+    materials or that you have already sent this user a copy.++For an executable, the required form of the "work that uses the+Library" must include any data and utility programs needed for+reproducing the executable from it. However, as a special exception,+the materials to be distributed need not include anything that is+normally distributed (in either source or binary form) with the major+components (compiler, kernel, and so on) of the operating system on+which the executable runs, unless that component itself accompanies+the executable.++It may happen that this requirement contradicts the license+restrictions of other proprietary libraries that do not normally+accompany the operating system. Such a contradiction means you cannot+use both them and the Library together in an executable that you+distribute.++**7.** You may place library facilities that are a work based on the+Library side-by-side in a single library together with other library+facilities not covered by this License, and distribute such a combined+library, provided that the separate distribution of the work based on+the Library and of the other library facilities is otherwise+permitted, and provided that you do these two things:++-   **a)** Accompany the combined library with a copy of the same work+    based on the Library, uncombined with any other+    library facilities. This must be distributed under the terms of+    the Sections above.+-   **b)** Give prominent notice with the combined library of the fact+    that part of it is a work based on the Library, and explaining+    where to find the accompanying uncombined form of the same work.++**8.** You may not copy, modify, sublicense, link with, or distribute+the Library except as expressly provided under this License. Any+attempt otherwise to copy, modify, sublicense, link with, or+distribute the Library is void, and will automatically terminate your+rights under this License. However, parties who have received copies,+or rights, from you under this License will not have their licenses+terminated so long as such parties remain in full compliance.++**9.** You are not required to accept this License, since you have not+signed it. However, nothing else grants you permission to modify or+distribute the Library or its derivative works. These actions are+prohibited by law if you do not accept this License. Therefore, by+modifying or distributing the Library (or any work based on the+Library), you indicate your acceptance of this License to do so, and+all its terms and conditions for copying, distributing or modifying+the Library or works based on it.++**10.** Each time you redistribute the Library (or any work based on+the Library), the recipient automatically receives a license from the+original licensor to copy, distribute, link with or modify the Library+subject to these terms and conditions. You may not impose any further+restrictions on the recipients' exercise of the rights granted herein.+You are not responsible for enforcing compliance by third parties with+this License.++**11.** If, as a consequence of a court judgment or allegation of+patent infringement or for any other reason (not limited to patent+issues), conditions are imposed on you (whether by court order,+agreement or otherwise) that contradict the conditions of this+License, they do not excuse you from the conditions of this License.+If you cannot distribute so as to satisfy simultaneously your+obligations under this License and any other pertinent obligations,+then as a consequence you may not distribute the Library at all. For+example, if a patent license would not permit royalty-free+redistribution of the Library by all those who receive copies directly+or indirectly through you, then the only way you could satisfy both it+and this License would be to refrain entirely from distribution of the+Library.++If any portion of this section is held invalid or unenforceable under+any particular circumstance, the balance of the section is intended to+apply, and the section as a whole is intended to apply in other+circumstances.++It is not the purpose of this section to induce you to infringe any+patents or other property right claims or to contest validity of any+such claims; this section has the sole purpose of protecting the+integrity of the free software distribution system which is+implemented by public license practices. Many people have made+generous contributions to the wide range of software distributed+through that system in reliance on consistent application of that+system; it is up to the author/donor to decide if he or she is willing+to distribute software through any other system and a licensee cannot+impose that choice.++This section is intended to make thoroughly clear what is believed to+be a consequence of the rest of this License.++**12.** If the distribution and/or use of the Library is restricted in+certain countries either by patents or by copyrighted interfaces, the+original copyright holder who places the Library under this License+may add an explicit geographical distribution limitation excluding+those countries, so that distribution is permitted only in or among+countries not thus excluded. In such case, this License incorporates+the limitation as if written in the body of this License.++**13.** The Free Software Foundation may publish revised and/or new+versions of the Lesser General Public License from time to time. Such+new versions will be similar in spirit to the present version, but may+differ in detail to address new problems or concerns.++Each version is given a distinguishing version number. If the Library+specifies a version number of this License which applies to it and+"any later version", you have the option of following the terms and+conditions either of that version or of any later version published by+the Free Software Foundation. If the Library does not specify a+license version number, you may choose any version ever published by+the Free Software Foundation.++**14.** If you wish to incorporate parts of the Library into other+free programs whose distribution conditions are incompatible with+these, write to the author to ask for permission. For software which+is copyrighted by the Free Software Foundation, write to the Free+Software Foundation; we sometimes make exceptions for this. Our+decision will be guided by the two goals of preserving the free status+of all derivatives of our free software and of promoting the sharing+and reuse of software generally.++**NO WARRANTY**++**15.** BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++**16.** IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH+DAMAGES.++END OF TERMS AND CONDITIONS++## How to Apply These Terms to Your New Libraries++If you develop a new library, and you want it to be of the greatest+possible use to the public, we recommend making it free software that+everyone can redistribute and change. You can do so by permitting+redistribution under these terms (or, alternatively, under the terms+of the ordinary General Public License).++To apply these terms, attach the following notices to the library. It+is safest to attach them to the start of each source file to most+effectively convey the exclusion of warranty; and each file should+have at least the "copyright" line and a pointer to where the full+notice is found.++    one line to give the library's name and an idea of what it does.+    Copyright (C) year  name of author++    This library is free software; you can redistribute it and/or+    modify it under the terms of the GNU Lesser General Public+    License as published by the Free Software Foundation; either+    version 2.1 of the License, or (at your option) any later version.++    This library is distributed in the hope that it will be useful,+    but WITHOUT ANY WARRANTY; without even the implied warranty of+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU+    Lesser General Public License for more details.++    You should have received a copy of the GNU Lesser General Public+    License along with this library; if not, see <https://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper+mail.++You should also get your employer (if you work as a programmer) or+your school, if any, to sign a "copyright disclaimer" for the library,+if necessary. Here is a sample; alter the names:++    Yoyodyne, Inc., hereby disclaims all copyright interest in+    the library `Frob' (a library for tweaking knobs) written+    by James Random Hacker.++    signature of Moe Ghoul, 1 April 1990+    Moe Ghoul, President of Vice++That's all there is to it!
+ ChangeLog.md view
@@ -0,0 +1,12 @@+## 0.1.2 (2026-12-03)+- `run` is now the default command+- fix rootful sandbox startup and report base sandbox setup failures directly+- if session dir is unsafe, run without session tracking++## 0.1.1 (2026-11-05)+- preserve user and group name for SSSD or Directory account++## 0.1.0 (2026-10-30)+- initial bwrap isolator+- private networking through pasta by default, with offline and host modes+- introduce run, enter, and list subcommands
+ README.md view
@@ -0,0 +1,246 @@+# Workcell++Workcell is a Linux CLI tool using Bubblewrap to setup Linux namespaces+to run programs with a read-only sysroot, an isolated homedir and restricted+to a writable project/work dir (and runtime). By default it attempts private+networking using pasta, falling back to host networking if it fails.++## Usage++`$ workcell --version`++```+0.1.2+```++`$ workcell --help`++```+workcell++Usage: workcell [--version]+                [COMMAND | [--dryrun] [-p|--project DIR[:(ro|rw|O)]]+                  [-H|--home DIR] [-v|--volume SOURCE[:DEST][:(ro|rw|O)]]+                  [-e|--env KEY[=VALUE]] [--wayland] [--x11] [--dbus]+                  [--share-processes] [--share-filesystem]+                  [--network-host | --network-none | --network-private]+                  [[--] CMD ARG...]]++  Run inside bwrap with an isolated home and writable project++Available options:+  -h,--help                Show this help text+  --version                Show version+  --dryrun                 Print the bubblewrap command without changing files+  -p,--project DIR[:(ro|rw|O)]+                           Project access (default: rw; :O for temporary+                           overlay; directory defaults to cwd, excluding HOME+                           and ancestors)+  -H,--home DIR            Persistent writable home (created if missing)+  -v,--volume SOURCE[:DEST][:(ro|rw|O)]+                           Extra mount (:O for temporary directory overlay;+                           default: same path, read-only)+  -e,--env KEY[=VALUE]     Set or pass through an environment variable+  --wayland                Expose the Wayland display socket for graphical+                           applications+  --x11                    Expose the local X11 display socket and+                           authentication file+  --dbus                   Expose the desktop D-Bus session socket (unfiltered)+  --share-processes        Share enclosing processes and /proc instead of+                           isolating them+  --share-filesystem       Expose the enclosing filesystem read-only, retaining+                           isolated home+  --network-host           Use host networking+  --network-none           Disable networking except private loopback+  --network-private        Use a private pasta network (attempted by default)++Available commands:+  list                     List active workcells in this PID namespace+  enter                    Enter an active workcell+  run                      Run a workcell bwrap session [default command]+```++Default networking tries to set up private networking+but falls back to host networking if its setup fails.+Workcell will print a warning before launching the command.+`--network-private` requires successful private setup.++User and group names are resolved before isolation.+For SSSD and other directory accounts, workcell adds missing entries+for the invoking user and groups to read-only sandbox copies of+`/etc/passwd` and `/etc/group`.++### Starting a workcell++Run `workcell ...` to start a shell, or+`workcell ... -- CMD ARG...` to run a command.++The explicit `run` subcommand is optional:++`$ workcell run --help`++```+Usage: workcell run [--dryrun] [-p|--project DIR[:(ro|rw|O)]] [-H|--home DIR]+                    [-v|--volume SOURCE[:DEST][:(ro|rw|O)]]+                    [-e|--env KEY[=VALUE]] [--wayland] [--x11] [--dbus]+                    [--share-processes] [--share-filesystem]+                    [--network-host | --network-none | --network-private]+                    [[--] CMD ARG...]++  Run a workcell bwrap session [default command]++Available options:+  --dryrun                 Print the bubblewrap command without changing files+  -p,--project DIR[:(ro|rw|O)]+                           Project access (default: rw; :O for temporary+                           overlay; directory defaults to cwd, excluding HOME+                           and ancestors)+  -H,--home DIR            Persistent writable home (created if missing)+  -v,--volume SOURCE[:DEST][:(ro|rw|O)]+                           Extra mount (:O for temporary directory overlay;+                           default: same path, read-only)+  -e,--env KEY[=VALUE]     Set or pass through an environment variable+  --wayland                Expose the Wayland display socket for graphical+                           applications+  --x11                    Expose the local X11 display socket and+                           authentication file+  --dbus                   Expose the desktop D-Bus session socket (unfiltered)+  --share-processes        Share enclosing processes and /proc instead of+                           isolating them+  --share-filesystem       Expose the enclosing filesystem read-only, retaining+                           isolated home+  --network-host           Use host networking+  --network-none           Disable networking except private loopback+  --network-private        Use a private pasta network (attempted by default)+  -h,--help                Show this help text+```++These work also without explicit `run`: the `workcell run --help` output+here is clearer than the earlier `workcell --help` output, which showed+also the other commands available.++In a rootful container where UID 0 lacks `CAP_SYS_ADMIN`, workcell asks+bubblewrap to create a user namespace. The container must permit nested user+namespaces and the required mounts. `--share-processes` can help when only+private PID or `/proc` setup is blocked.++### `list`++Use `workcell list` to list running workcell sessions.++`$ workcell list --help`++```+Usage: workcell list++  List active workcells in this PID namespace++Available options:+  -h,--help                Show this help text+```++### `enter`++Use `workcell enter [--root] [--dryrun] [SESSION] [-- COMMAND ARG...]`+to join a session without sudo.+The session ID is optional when starting a shell;+supply an explicit ID when passing a command.++Ending the original workcell session currently kills sessions entered through+`enter`. Recommend running tmux inside workcell instead, if you need multiple+sessions.+++`$ workcell enter --help`++```+Usage: workcell enter [--dryrun] [--root] [SESSION [--] CMD ARG...]++  Enter an active workcell++Available options:+  --dryrun                 Print the entry command without entering+  --root                   Enter as root inside the workcell+  -h,--help                Show this help text+```++## Examples++```shellsession+$ workcell   # open a workcell shell on the cwd+$ workcell --project /path/to/project -- git status+$ workcell -p /path/to/project:ro -- git diff   # read-only project+$ workcell -p /path/to/project:O -- make   # discard project changes on exit+$ workcell --home /path/to/sandbox-home   # persistent home, created if missing+$ workcell -v ~/.gitconfig -- git status    # mount file ro+$ workcell -v ~/.cargo:rw -- cargo build+$ workcell -v ~/.config/cabal -v ~/.cache/cabal:rw -v ~/.local/state/cabal:rw -- cabal build --offline+$ workcell -v /path/to/data:/tmp/data:ro -- ls /tmp/data+$ workcell -v /path/to/data:/tmp/data:O   # temporary writable view of data+$ workcell -e LANG -e MY_VAR=hello -- env+$ workcell --dryrun -- gcc --version+$ workcell --share-processes   # fallback for restricted containers+$ workcell --share-filesystem -- ls /var/log   # expose enclosing filesystem read-only+$ workcell --network-none   # offline, separate loopback network+$ workcell --network-host -- curl localhost:8000   # share enclosing network+$ workcell --wayland gtk4-demo+$ workcell --x11 xterm+```++`:O` requires a directory and bubblewrap with overlay support. Changes to that+mount are discarded when the workcell exits; the source directory stays unchanged.++### Entering an active workcell++From another terminal in the same enclosing environment:++```sh+workcell list+workcell enter                       # use the only active session; starts Bash+workcell enter s123456               # use an ID from workcell list; starts Bash+workcell enter s123456 -- git status+workcell enter s123456 --root        # root inside the workcell+workcell enter s123456 --dryrun+```++The session ID is optional. With one active session, `enter` uses it automatically.+With multiple sessions and terminal input, it shows a numbered menu and prompts+for a choice; press Enter to cancel. Without terminal input, it lists the sessions+and returns an error asking for an ID. With no active sessions, it reports an error.+`--root` and `--dryrun` also work without an ID. Supply an explicit ID when passing+a command.++If the session storage directory is unsafe or unwritable, workcell warns and+runs without session tracking. To enable listing and entry, set `XDG_RUNTIME_DIR`+to a private writable directory and use the same setting from both terminals.++## Requirements+Linux++- bwrap (bubblewrap)+- pasta (passt)+- nsenter (util-linux)++## Installation++workcell is packaged in Fedora Copr:++<https://copr.fedorainfracloud.org/coprs/petersen/workcell/>++## Building++Requires ghc and cabal-install (or stack).++On Fedora: install system deps: `cabal-rpm builddep`.++Then run `cabal install` (or `stack install`)++There is also an extensive testsuite and benchmarking.++## Contributing and development++Workcell is distributed under LGPLv2.1+++<https://github.com/juhp/workcell>++See also the generated [Notes](NOTES.md) for various more details.
+ bench/Bench.hs view
@@ -0,0 +1,42 @@+-- SPDX-License-Identifier: LGPL-2.1-or-later+module Main (main) where++import Data.Maybe (fromMaybe)+import SimpleCmd ((+-+))+import System.Environment (lookupEnv)+import System.Exit (ExitCode(..))+import System.Process (readProcessWithExitCode)+import Test.Tasty (localOption)+import Test.Tasty.Bench++main :: IO ()+main = do+  exe <- fromMaybe "workcell" <$> lookupEnv "WORKCELL"+  host <- run exe True False ["--network-host"]+  priv <- run exe True False ["--network-private"]+  none <- run exe True False ["--network-none"]+  -- CPU time would exclude the time spent in workcell and bubblewrap.+  defaultMain+    [ localOption WallTime $+      bgroup "workcell" $+      bench "dryrun" (nfIO $ run exe False True ["--network-host"]) :+      [bench "run none" $ nfIO $ run exe False False ["--network-none"]| none] +++      [bench "run host" $ nfIO $ run exe False False ["--network-host"]| host] +++      [bench "run private" $ nfIO $ run exe False False ["--network-private"]| priv] +++      [bench "run auto" $ nfIO $ run exe False False []| host]+    ]+  where+    run exe test dryrun net = do+      (code, out, err) <- readProcessWithExitCode exe ("run" : net ++ ["--dryrun" | dryrun] ++ ["true"]) ""+      case code of+        ExitSuccess -> pure ()+        ExitFailure n ->+          if test+          then putStrLn $ "Skipping" +-+ showNet net ++ ": sandbox startup failed\n" ++ err+          else fail $ "workcell failed (" ++ show n ++ "): " ++ out ++ err+      return $ code == ExitSuccess++    showNet net =+      if null net+      then "auto"+      else unwords net
+ src/Child.hs view
@@ -0,0 +1,89 @@+-- SPDX-License-Identifier: LGPL-2.1-or-later+module Child (+  Child,+  childHandle,+  withChild,+  withChildStreams,+  stopChild,+  waitChild,+  childExited,+  waitEither+  )+where++import Control.Concurrent (forkIO)+import Control.Concurrent.MVar+  (MVar, newEmptyMVar, putMVar, readMVar, tryReadMVar)+import Control.Exception+  (AsyncException(UserInterrupt), SomeException, bracket, fromException, throwIO, try)+import Control.Monad (void)+import Control.Monad.Extra (whenJust)+import System.Exit (ExitCode(..))+import System.IO (Handle)+import System.Posix.Signals (sigKILL, signalProcess)+import System.Process+  (CreateProcess, ProcessHandle, createProcess, getPid, terminateProcess, waitForProcess)+import System.Timeout (timeout)++-- A child is reaped by exactly one thread; everyone else reads its result.+-- This avoids concurrent waitpid calls and repeated polling.+data Child = Child+  { childHandle :: ProcessHandle+  , childResult :: MVar (Either SomeException ExitCode)+  }++type Streams = (Maybe Handle, Maybe Handle, Maybe Handle)++spawn :: CreateProcess -> IO (Streams, Child)+spawn command = do+  (input, output, err, handle) <- createProcess command+  result <- newEmptyMVar+  _ <- forkIO $ try (waitForProcess handle) >>= putMVar result+  pure ((input, output, err), Child handle result)++withChild :: CreateProcess -> (Child -> IO a) -> IO a+withChild command action = withChildStreams command $ \(_, _, _, child) -> action child++-- Stopped (if still running) when the action finishes or fails.+withChildStreams :: CreateProcess -> ((Maybe Handle, Maybe Handle, Maybe Handle, Child) -> IO a) -> IO a+withChildStreams command action =+  bracket (spawn command) (stopChild . snd) $ \((input, output, err), child) ->+    action (input, output, err, child)++waitChild :: Child -> IO ExitCode+waitChild child = readMVar (childResult child) >>= either rethrow pure+  where+    -- delegate_ctlc reports a child killed by SIGINT as UserInterrupt.+    rethrow err = case fromException err of+      Just UserInterrupt -> pure $ ExitFailure 130+      _ -> throwIO err++childExited :: Child -> IO (Maybe ExitCode)+childExited child = do+  result <- tryReadMVar (childResult child)+  case result of+    Nothing -> pure Nothing+    Just _ -> Just <$> waitChild child++-- Wait for whichever child exits first.+waitEither :: Child -> Child -> IO (Either ExitCode ExitCode)+waitEither left right = do+  first <- newEmptyMVar+  _ <- forkIO $ try (waitChild left) >>= putMVar first . fmap Left+  _ <- forkIO $ try (waitChild right) >>= putMVar first . fmap Right+  readMVar first >>= either (throwIO :: SomeException -> IO a) pure++stopChild :: Child -> IO ()+stopChild child = do+  status <- tryReadMVar (childResult child)+  case status of+    Just _ -> pure ()+    Nothing -> do+      terminateProcess (childHandle child)+      result <- timeout (5 * 1000000) (readMVar $ childResult child)+      case result of+        Just _ -> pure ()+        Nothing -> do+          pid <- getPid (childHandle child)+          whenJust pid $ signalProcess sigKILL+          void $ readMVar (childResult child)
+ src/Enter.hs view
@@ -0,0 +1,102 @@+-- SPDX-License-Identifier: LGPL-2.1-or-later+module Enter (enterSession) where++import Control.Exception (bracket)+import Control.Monad (unless)+import qualified Data.ByteString.Char8 as BS+import SimpleCmd (needProgram)+import System.Directory (findExecutable)+import System.Exit (exitWith)+import System.FilePath ((</>))+import System.IO (hIsTerminalDevice, stdin, stdout)+import System.Posix.Files (readSymbolicLink)+import System.Posix.IO (closeFd)+import System.Posix.Process (getProcessID)+import System.Process (CreateProcess(..), proc)++import Child (waitChild, withChild)+import Sandbox (NetworkMode(..))+import Session (Session(..), SessionDetails(..), findSession, validSession)+import Util (invalid, ownerNamespace, procPath, shellQuote, withDescriptors)++enterSession :: Bool -> Bool -> [String] -> IO ()+enterSession dry root idcmd = do+  let (ident,command) =+        case idcmd of+          [] -> (Nothing,[])+          (h:t) -> (Just h,t)+  record <- findSession ident+  interactive <- (&&) <$> hIsTerminalDevice stdin <*> hIsTerminalDevice stdout+  entryCommand <-+    let cmd = if null command then ["/bin/bash"] else command in+      if interactive then terminalCommand cmd else pure cmd+  let pid = sessionPID record+      details = sessionDetails record+      namespaces = ["mnt"] ++ ["pid" | not $ sessionSharedProcesses details] +++        ["net" | sessionNetwork details /= HostNetwork]+      flag "mnt" = "--mount"+      flag name = "--" ++ name+      -- Preserve the mapped host credentials in either mode: setup-namespace+      -- UID/GID 0 already maps to the invoking account, and setgroups is denied+      -- in unprivileged user namespaces.+      tailArgs = ["--target", show pid, "--env", "--preserve-credentials"]+  withDescriptors [procPath pid ("ns" </> name) | name <- namespaces] $ \fds ->+    case fds of+      mount:_ -> bracket (ownerNamespace mount) closeFd $ \owner -> do+        supervisor <- getProcessID+        let reference fd = "/proc/" ++ show supervisor ++ "/fd/" ++ show fd+        ownerUser <- readSymbolicLink $ reference owner+        targetUser <- readSymbolicLink $ procPath pid "ns/user"+        -- Mount/network entry requires their owning user namespace. Bubblewrap+        -- may then use a child user namespace to restore the invoking UID/GID.+        -- Join that final namespace only after entering the other namespaces.+        finalCommand <-+          if root || ownerUser == targetUser+          then pure entryCommand+          else do+            insidePID <-+              if sessionSharedProcesses details+              then pure (show pid)+              else do+                status <- lines . BS.unpack <$> BS.readFile (procPath pid "status")+                case [inside | line <- status, "NSpid:":ids <- [words line], inside:_ <- [reverse ids]] of+                  [inside] -> pure inside+                  _ -> invalid "cannot determine session PID inside its namespace"+            nsenter <- findExecutable "nsenter" >>= maybe (invalid "nsenter is required for entry") pure+            pure $ [nsenter, "--user=/proc/" ++ insidePID ++ "/ns/user", "--preserve-credentials", "--"] ++ entryCommand+        if dry+          then putStrLn $ unwords $ map shellQuote $+               ["nsenter", "--user=" ++ procPath pid "ns/user"] +++               ["--user-parent" | ownerUser /= targetUser] +++               [flag name ++ "=" ++ procPath pid ("ns" </> name) | name <- namespaces] +++               tailArgs ++ ["--root", "--wd", "--"] ++ finalCommand+          else do+          needProgram "nsenter"+          withDescriptors [procPath pid "root", procPath pid "cwd"] $ \directories -> do+            valid <- validSession record+            unless valid $ invalid "session exited while preparing entry"+            -- Explicit descriptors avoid nsenter's mixed pidfd/FD join ordering.+            let args = ["--user=" ++ reference owner] +++                  zipWith (\name fd -> flag name ++ "=" ++ reference fd) namespaces fds +++                  tailArgs ++ zipWith (\name fd -> name ++ "=" ++ reference fd)+                    ["--root", "--wd"] directories ++ ["--"] ++ finalCommand+            -- nsenter opens the supervisor's descriptors before joining. Its+            -- command inherits none of our namespace/root directory handles.+            result <- withChild ((proc "nsenter" args)+              {delegate_ctlc = True, close_fds = True}) waitChild+            exitWith result+      _ -> invalid "missing mount namespace descriptor"++-- The caller's terminal belongs to another devpts instance. Allocate the new+-- terminal after nsenter has joined the session, and relay input/output to it.+terminalCommand :: [String] -> IO [String]+terminalCommand command = do+  forward <- findExecutable "systemd-pty-forward"+  case forward of+    Just path -> pure $ [path, "--quiet", "--"] ++ command+    Nothing -> do+      script <- findExecutable "script"+      case script of+        Just path -> pure [path, "--quiet", "--return", "--command",+                           "exec " ++ unwords (map shellQuote command), "/dev/null"]+        Nothing -> invalid "interactive entry requires systemd-pty-forward or script (from util-linux)"
+ src/Identity.hs view
@@ -0,0 +1,82 @@+{-# LANGUAGE CPP #-}+-- SPDX-License-Identifier: LGPL-2.1-or-later+module Identity (identityFiles, passwdEntries, groupEntries, appendEntries) where++import Control.Monad (forM, unless, when)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BSC+import Data.List (intercalate, nub)+import Data.Maybe (catMaybes, maybeToList)+import SimpleCmd (warning)+import System.IO.Error (catchIOError, isDoesNotExistError)+import System.Posix.Files (getFileStatus, linkCount)+import System.Posix.User+#if MIN_VERSION_unix(2,8,0)+import System.Posix.User.ByteString (UserEntry, GroupEntry)+#endif++import Util (invalid)++-- Resolve NSS records while the host's SSSD socket/cache is still visible.+-- Retain local accounts, and copy no password hashes or remote directory dump.+identityFiles :: IO [(FilePath, BS.ByteString)]+identityFiles = do+  uid <- getEffectiveUserID+  user <- optional $ getUserEntryForID uid+  gid <- getEffectiveGroupID+  supplementary <- getGroups+  groups <- catMaybes <$> mapM (optional . getGroupEntryForID)+    (nub $ gid : supplementary ++ map userGroupID (maybeToList user))+  files <- forM [("/etc/passwd", passwdEntries $ maybeToList user),+                 ("/etc/group", groupEntries groups)] $ \(path, missing) -> optional $ do+    original <- catchIOError (BS.readFile path) $ \err ->+      if isDoesNotExistError err then pure BS.empty else ioError err+    let entries = missing original+    -- An enclosing sandbox's --ro-bind-data copy cannot be mounted over.+    unless (null entries) $ do+      status <- getFileStatus path+      when (linkCount status == 0) $+        invalid $ path ++ " is a sandbox copy which cannot be replaced"+    pure (path, original, entries)+  pure [(path, appendEntries original entries)+       | Just (path, original, entries) <- files, not (null entries)]+  where+    -- Names are a convenience: never let a directory failure block a launch.+    optional action = catchIOError (Just <$> action) $ \err -> do+      unless (isDoesNotExistError err) $+        warning $ "cannot preserve account names: " ++ show err+      pure Nothing++-- Directory values are copied unchecked: a ':' or newline (e.g. in a GECOS+-- display name), or a ',' in a group member, would shift or add fields.+-- Only the sandbox's read-only copies are affected.++-- Records for users whose UID is absent from the original passwd file.+passwdEntries :: [UserEntry] -> BS.ByteString -> [String]+passwdEntries users = missingEntries+  [(show $ userID user, intercalate ":"+    [userName user, "x", show $ userID user, show $ userGroupID user,+     userGecos user, homeDirectory user, userShell user]) | user <- users]++-- Records for groups whose GID is absent from the original group file.+groupEntries :: [GroupEntry] -> BS.ByteString -> [String]+groupEntries groups = missingEntries+  [(show $ groupID group, intercalate ":"+    [groupName group, "x", show $ groupID group, intercalate "," $ groupMembers group])+   | group <- groups]++-- Both files keep the numeric ID in their third field.+missingEntries :: [(String, String)] -> BS.ByteString -> [String]+missingEntries entries original =+  [entry | (ident, entry) <- entries, BSC.pack ident `notElem` existing]+  where+    existing = [ident | _:_:ident:_ <- map (BSC.split ':') (BSC.lines original)]++-- The unix package unpacks NSS strings one Char per byte, so packing them+-- restores the directory's bytes in whatever encoding it uses.+appendEntries :: BS.ByteString -> [String] -> BS.ByteString+appendEntries original entries+  | BS.null original || BSC.last original == '\n' = original `BS.append` added+  | otherwise = BSC.snoc original '\n' `BS.append` added+  where+    added = BSC.pack $ unlines entries
+ src/Main.hs view
@@ -0,0 +1,67 @@+-- SPDX-License-Identifier: LGPL-2.1-or-later++module Main (main) where++import Control.Concurrent (myThreadId)+import Control.Exception (Handler(..), IOException, bracket, catches, throwTo)+import Control.Monad (void)+import SimpleCmdArgs+import System.Exit (ExitCode(..), die)+import System.Posix.Signals (Handler(CatchOnce), Signal, installHandler, sigHUP, sigTERM)++import Enter (enterSession)+import Paths_workcell (version)+import Run (Options(..), runWorkcell, NetworkMode(..))+import Sandbox (NetworkSetupFailure)+import Session (listSessions)++main :: IO ()+main =+  simpleCmdArgs' (Just version) "workcell"+  "Run inside bwrap with an isolated home and writable project" $+  execute <$> (commands <|> run)+  where+    commands = subcommands+      [ Subcommand "list" "List active workcells in this PID namespace" $+        pure listSessions+      , Subcommand "enter" "Enter an active workcell" $+        enterSession+        <$> switchLongWith "dryrun" "Print the entry command without entering"+        <*> switchLongWith "root" "Enter as root inside the workcell"+        <*> many (strArg "SESSION [--] CMD ARG...")+      , Subcommand "run" "Run a workcell bwrap session [default command]" run+      ]+    run = runWorkcell <$> options++    execute action = withTermination action `catches`+      [Handler $ \err -> die $ "workcell: " ++ show (err :: IOException),+       Handler $ \err -> die $ "workcell: " ++ show (err :: NetworkSetupFailure)]++-- Turn termination and hangup into exceptions so session/helper brackets+-- can clean up.+withTermination :: IO a -> IO a+withTermination action =+  withSignal sigTERM 143 $ withSignal sigHUP 129 action+  where+    withSignal :: Signal -> Int -> IO a -> IO a+    withSignal signal code inner = do+      thread <- myThreadId+      bracket (installHandler signal (CatchOnce $ throwTo thread $ ExitFailure code) Nothing)+        (\previous -> void (installHandler signal previous Nothing)) $ const inner++options :: Parser Options+options = Options+  <$> switchLongWith "dryrun" "Print the bubblewrap command without changing files"+  <*> optional (strOptionWith 'p' "project" "DIR[:(ro|rw|O)]" "Project access (default: rw; :O for temporary overlay; directory defaults to cwd, excluding HOME and ancestors)")+  <*> optional (strOptionWith 'H' "home" "DIR" "Persistent writable home (created if missing)")+  <*> many (strOptionWith 'v' "volume" "SOURCE[:DEST][:(ro|rw|O)]" "Extra mount (:O for temporary directory overlay; default: same path, read-only)")+  <*> many (strOptionWith 'e' "env" "KEY[=VALUE]" "Set or pass through an environment variable")+  <*> switchLongWith "wayland" "Expose the Wayland display socket for graphical applications"+  <*> switchLongWith "x11" "Expose the local X11 display socket and authentication file"+  <*> switchLongWith "dbus" "Expose the desktop D-Bus session socket (unfiltered)"+  <*> switchLongWith "share-processes" "Share enclosing processes and /proc instead of isolating them"+  <*> switchLongWith "share-filesystem" "Expose the enclosing filesystem read-only, retaining isolated home"+  <*> optional (flagLongWith' HostNetwork "network-host" "Use host networking" <|>+                flagLongWith' NoNetwork "network-none" "Disable networking except private loopback" <|>+                flagLongWith' PrivateNetwork "network-private" "Use a private pasta network (attempted by default)")+  <*> many (strArg "[--] CMD ARG...")
+ src/Run.hs view
@@ -0,0 +1,517 @@+-- SPDX-License-Identifier: LGPL-2.1-or-later+module Run (+  Options(..),+  NetworkMode(..),+  runWorkcell)+where++import Control.Exception (catch, onException)+import Control.Monad.Extra (allM, forM, unless, unlessM, when)+import Data.Char (digitToInt, isAsciiLower, isAsciiUpper, isDigit, isHexDigit, ord)+import qualified Data.ByteString as BS+import Data.List (intercalate, isPrefixOf, nub)+import Data.Maybe (fromMaybe, isJust, isNothing)+import GHC.Foreign (peekCString)+import GHC.IO.Encoding (getFileSystemEncoding)+import SimpleCmd (needProgram, warning, (+-+))+import System.Directory+  (canonicalizePath, createDirectoryIfMissing, doesDirectoryExist,+   doesPathExist, getHomeDirectory, getSymbolicLinkTarget, listDirectory, pathIsSymbolicLink,+   removeDirectory)+import System.Environment (getArgs, getEnvironment, getExecutablePath, lookupEnv)+import System.Exit (exitWith)+import System.FilePath ((</>), isAbsolute, normalise, splitDirectories, takeDirectory, takeFileName)+import System.IO.Error (catchIOError, isDoesNotExistError)+import System.Posix.Files (getFileStatus, isRegularFile, isSocket, linkCount)++import Sandbox+import Identity (identityFiles)+import Session (SessionDetails(..), withSession)+import Util (invalid, shellQuote)++data Options = Options+  { dryRun :: Bool+  , projectOption :: Maybe FilePath+  , homeOption :: Maybe FilePath+  , volumeOptions :: [String]+  , environmentOptions :: [String]+  , waylandOption :: Bool+  , x11Option :: Bool+  , dbusOption :: Bool+  , shareProcesses :: Bool+  , shareFilesystem :: Bool+  , networkOption :: Maybe NetworkMode+  , command :: [String]+  }++data MountMode = ReadOnlyMount | ReadWriteMount | OverlayMount+  deriving Eq++data Mount = Mount+  { source :: FilePath+  , destination :: FilePath+  , mountMode :: MountMode+  }++data Launch = Launch+  { launchSandbox :: Sandbox+  , persistentHome :: Maybe FilePath+  , selectedNetwork :: NetworkMode+  , resolverTarget :: FilePath+  , launchProject :: Maybe FilePath+  }++privateNetwork :: Launch -> Maybe PrivateNetwork+privateNetwork launch+  | selectedNetwork launch == PrivateNetwork =+      Just $ PrivateNetworkConfig [] (resolverTarget launch)+  | otherwise = Nothing++runWorkcell :: Options -> IO ()+runWorkcell opts = do+  userArgs <- userNamespaceArgs+  planned <- prepare userArgs opts+  if dryRun opts+    then preview opts planned+    else do+    needProgram "bwrap"+    let mode = selectedNetwork planned+        automatic = isNothing (networkOption opts)+    -- Check before creating a persistent home or running the requested command.+    failure <- probeNamespaces userArgs (not $ shareProcesses opts) (mode /= HostNetwork)+    available <- case failure of+      Just (BaseSandboxUnavailable err) -> invalid $+        "bubblewrap could not initialize the filesystem sandbox.\n" ++ err+      Just (ProcessIsolationUnavailable err) -> invalid $+        "private PID namespace and /proc are unavailable in this environment. "+        ++ "Use --share-processes only if sharing enclosing processes is acceptable.\n" ++ err+      Just (NetworkIsolationUnavailable err) -> pure $ Just err+      Nothing | mode == PrivateNetwork -> checkPrivateNetwork+      Nothing -> pure Nothing+    -- The command is still paused when private network setup fails,+    -- so falling back cannot run it twice.+    -- FIXME possibly use color (grey etc)?+    let unavailable reason+          | automatic && mode == PrivateNetwork = do+              warning $ "private networking is unavailable (" ++ takeWhile (/= '\n') reason +++                "): falling back to host networking"+              prepare userArgs opts {networkOption = Just HostNetwork} >>= launch False+          | otherwise = invalid $+              (if mode == PrivateNetwork then "private networking" else "network isolation")+              ++ " is unavailable. " ++ reason ++ "\n"+              ++ "Try --network-host, if sharing the enclosing network is acceptable."+    result <- case available of+      Just reason -> unavailable reason+      Nothing -> launch (not automatic) planned `catch`+        \(NetworkSetupFailure reason) -> unavailable reason+    exitWith result+  where+    launch removeHomeOnFailure plan =+      withPersistentHome removeHomeOnFailure (persistentHome plan) $+        runSandbox (privateNetwork plan) (withSession details) (launchSandbox plan)+      where+        details = SessionDetails (launchProject plan) (sandboxCommand $ launchSandbox plan)+          (selectedNetwork plan) (shareProcesses opts)++-- Undo creating a persistent home if the run fails while it is still empty,+-- such as when sandbox or network setup fails before the command starts.+-- Bubblewrap may already have created empty mountpoints inside it (for a+-- project beneath HOME); remove only empty directories, never files.+-- A fallback launch reuses the directory instead.+withPersistentHome :: Bool -> Maybe FilePath -> IO a -> IO a+withPersistentHome _ Nothing action = action+withPersistentHome removeOnFailure (Just dir) action = do+  exists <- doesDirectoryExist dir+  if exists then action else do+    warning $ "created" +-+ dir+    createDirectoryIfMissing True dir+    action `onException` when removeOnFailure (ignoreErrors $ do+      pristine <- onlyDirectories dir+      when pristine $ removeTree dir)+  where+    onlyDirectories path = do+      symlink <- pathIsSymbolicLink path+      isDir <- doesDirectoryExist path+      if not isDir || symlink then pure False else+        listDirectory path >>= allM (onlyDirectories . (path </>))+    removeTree path = do+      listDirectory path >>= mapM_ (removeTree . (path </>))+      removeDirectory path+    ignoreErrors act = catchIOError act $ const $ pure ()++preview :: Options -> Launch -> IO ()+preview opts plan = do+  let network = privateNetwork plan+      sandbox = launchSandbox plan+      descriptor (Arg _) = False+      descriptor _ = True+      copies = any descriptor (sandboxArgs sandbox)+      commands = map (unwords . map shellQuote) $ previewSandbox network sandbox+  when (isNothing $ networkOption opts) $+    putStrLn "# trying private networking; fall back to host if network setup fails"+  if isJust network || copies+    then do+      -- Descriptors only exist at launch, so show a plan and a runnable command.+      mapM_ (putStrLn . ("# " ++)) commands+      executable <- getExecutablePath+      argv <- getArgs+      let (options, cmd) = break (== "--") argv+      putStrLn $ unwords $ map shellQuote $ executable : filter (/= "--dryrun") options ++ cmd+    else mapM_ putStrLn commands++-- Validate paths and construct argv before creating any persistent home.+prepare :: [String] -> Options -> IO Launch+prepare userArgs opts = do+  let mode = fromMaybe PrivateNetwork $ networkOption opts+  (projectPath, projectMode) <-+    case splitMountSpec ReadWriteMount (fromMaybe "." $ projectOption opts) of+      ([path], access) | not (null path) -> pure (path, access)+      _ -> invalid "invalid project (expected DIR[:ro|rw|O])"+  candidate <- existingDirectory "project" projectPath+  originalHome <- getHomeDirectory+  unless (isAbsolute originalHome) $ invalid "HOME must be an absolute path"+  home <- existingDirectory "HOME" originalHome+  rejectRoot "HOME" home+  when (isJust (projectOption opts) && within candidate home) $+    invalid "project must not cover HOME; select a project directory with --project"+  let project = if within candidate home then Nothing else Just candidate+  suppliedHome <- traverse resolveHome (homeOption opts)+  displaySettings <- sequence $+    [waylandSetup | waylandOption opts] ++ [x11Setup home | x11Option opts]+  busSettings <- sequence [dbusSetup | dbusOption opts]+  let desktopSettings = displaySettings ++ busSettings+      desktopMounts = concatMap fst desktopSettings+      backends = ["wayland" | waylandOption opts] ++ ["x11" | x11Option opts]+      desktopEnv = concatMap snd desktopSettings +++        [("GDK_BACKEND", intercalate "," backends) | not (null backends)]+  mounts <- (desktopMounts ++) <$> mapM resolveMount (volumeOptions opts)+  identities <- filter (\(path, _) -> not $+    any (\mount -> within (destination mount) path) mounts) <$> identityFiles+  unless (shareProcesses opts) $ do+    when (maybe False (within "/proc") project || within home "/proc" || within "/proc" home) $+      invalid "home and project must not overlap private /proc"+    mapM_ (\mount -> when (within (destination mount) "/proc" || within "/proc" (destination mount)) $+      invalid "volume destination must not overlap private /proc") mounts+  filesystem <- filesystemArgs (shareFilesystem opts)+  resolverArgs <- if mode == PrivateNetwork then pure []+                  else liveResolverArgs (shareFilesystem opts) mounts+  inheritedSystemFiles <- preservedSystemFiles (shareFilesystem opts)+    (mode /= PrivateNetwork && null resolverArgs)+  let systemFiles =+        filter+        (\system -> not $+          any (\mount -> within (destination mount) (destination system) ||+                         within (destination mount) (source system)) mounts)+        inheritedSystemFiles+  systemMounts <-+    forM (zip [0 :: Int ..] systemFiles) $ \(index, mount) -> do+    status <- getFileStatus (source mount)+    -- Files produced by --ro-bind-data have no directory entry to re-bind.+    -- Open and copy their contents into the next sandbox instead.+    pure $ if linkCount status == 0+      then [Arg "--ro-bind-data", FileFd ("<system-file-" ++ show index ++ "-fd>") (source mount),+            Arg (destination mount)]+      else map Arg (mountArgs mount)+  resolver <- if mode /= PrivateNetwork then pure "/etc/resolv.conf" else do+    target <- catchIOError (hiddenSystemTarget (hiddenPath $ shareFilesystem opts) "/etc/resolv.conf") $ \err ->+      if isDoesNotExistError err then pure Nothing else ioError err+    maybe (canonicalizePath "/etc/resolv.conf") pure target+  let destinations = map destination mounts+  unless (length destinations == length (nub destinations)) $+    invalid "duplicate volume destinations"+  mapM_ (validateMount (shareFilesystem opts) project home) mounts+  env <- mapM resolveEnvironment (environmentOptions opts)+  locale <- filter (isLocaleVariable . fst) <$> getEnvironment+  term <- fromMaybe "dumb" <$> lookupEnv "TERM"+  let homeArgs = maybe ["--tmpfs", home]+        (\path -> ["--bind", path, home]) suppliedHome+      defaults = [("HOME", home), ("PATH", defaultPath home), ("TERM", term),+                  ("WORKCELL_ACTIVE", "1")] ++ locale+      cmd = if null (command opts)+        then ["/bin/bash"] else command opts+      beforeSystemFiles = userArgs ++ ["--die-with-parent"] ++ filesystem+        ++ concatMap (\path -> ["--tmpfs", path]) temporaryRoots+        ++ ["--dev", "/dev"]+        ++ (if shareProcesses opts then ["--ro-bind", "/proc", "/proc"] else privateProcArgs)+        ++ ["--dir", home]+        ++ homeArgs+        ++ resolverArgs+      afterSystemFiles = ["--unshare-net" | mode /= HostNetwork]+        ++ concatMap mountArgs mounts+        ++ maybe [] (\path -> mountArgs $ Mount path path projectMode) project+        ++ ["--chdir", fromMaybe home project, "--clearenv"]+        ++ concatMap (\(key, value) -> ["--setenv", key, value]) (defaults ++ desktopEnv ++ env)+        ++ (if shareFilesystem opts then [] else ["--remount-ro", "/"])+      identityArgs = concat+        [[Arg "--ro-bind-data", DataFd ("<" ++ name ++ "-fd>") bytes, Arg path]+        | (path, bytes) <- identities, let name = takeFileName path]+      args = map Arg beforeSystemFiles ++ concat systemMounts ++ identityArgs ++ map Arg afterSystemFiles+  pure $ Launch (Sandbox args cmd) suppliedHome mode resolver project++waylandSetup :: IO ([Mount], [(String, String)])+waylandSetup = do+  runtime <- lookupEnv "XDG_RUNTIME_DIR" >>= maybe+    (invalid "--wayland requires XDG_RUNTIME_DIR") pure+  unless (isAbsolute runtime) $ invalid "--wayland requires an absolute XDG_RUNTIME_DIR"+  display <- fromMaybe "wayland-0" <$> lookupEnv "WAYLAND_DISPLAY"+  when (null display) $ invalid "--wayland requires a nonempty WAYLAND_DISPLAY"+  let socket = normalise $ if isAbsolute display then display else runtime </> display+  status <- getFileStatus socket+  unless (isSocket status) $ invalid $ "Wayland display is not a socket: " ++ socket+  src <- canonicalizePath socket+  pure ([Mount src socket ReadOnlyMount],+        [("XDG_RUNTIME_DIR", runtime), ("WAYLAND_DISPLAY", display)])++x11Setup :: FilePath -> IO ([Mount], [(String, String)])+x11Setup home = do+  display <- lookupEnv "DISPLAY" >>= maybe (invalid "--x11 requires DISPLAY") pure+  number <- case break (== ':') display of+    (host, ':':suffix) | host `elem` ["", "unix", "unix/"] ->+      case span isDigit suffix of+        (digits, screen) | not (null digits) &&+          (null screen || case screen of+            '.':rest -> not (null rest) && all isDigit rest+            _ -> False) -> pure digits+        _ -> badDisplay+    _ -> badDisplay+  let socket = "/tmp/.X11-unix" </> ("X" ++ number)+      authTarget = "/run/workcell-xauthority"+  status <- getFileStatus socket+  unless (isSocket status) $ invalid $ "X11 display is not a socket: " ++ socket+  authority <- lookupEnv "XAUTHORITY" >>= canonicalizePath . fromMaybe (home </> ".Xauthority")+  authStatus <- getFileStatus authority+  unless (isRegularFile authStatus) $ invalid $ "X11 authority is not a regular file: " ++ authority+  pure ([Mount socket socket ReadOnlyMount, Mount authority authTarget ReadOnlyMount],+        [("DISPLAY", display), ("XAUTHORITY", authTarget)])+  where+    badDisplay = invalid "--x11 requires a local DISPLAY such as :0 or :0.0 (TCP displays are unsupported)"++dbusSetup :: IO ([Mount], [(String, String)])+dbusSetup = do+  address <- lookupEnv "DBUS_SESSION_BUS_ADDRESS" >>= maybe+    (invalid "--dbus requires DBUS_SESSION_BUS_ADDRESS") pure+  value <- case break (== ':') address of+    ("unix", parameters) | ';' `notElem` address ->+      case map (break (== '=')) $ splitComma $ drop 1 parameters of+        fields | all (\(key, val) -> key `elem` ["path", "guid"] && not (null $ drop 1 val)) fields,+                 [path] <- [path | ("path", '=':path) <- fields] -> pure path+        _ -> badAddress+    _ -> badAddress+  bytes <- either invalid pure $ unescape value+  -- D-Bus escapes bytes; decode using the same encoding as filesystem paths.+  encoding <- getFileSystemEncoding+  socket <- BS.useAsCString (BS.pack bytes) $ peekCString encoding+  unless (isAbsolute socket) $ invalid "--dbus requires an absolute Unix socket path"+  status <- getFileStatus socket+  unless (isSocket status) $ invalid $ "D-Bus session address is not a socket: " ++ socket+  src <- canonicalizePath socket+  let target = "/run/workcell-session-bus"+  pure ([Mount src target ReadOnlyMount], [("DBUS_SESSION_BUS_ADDRESS", "unix:path=" ++ target)])+  where+    badAddress = invalid "--dbus requires a single unix:path= session address (abstract and TCP sockets are unsupported)"+    splitComma input = case break (== ',') input of+      (part, []) -> [part]+      (part, _:rest) -> part : splitComma rest+    unescape [] = Right []+    unescape ('%':a:b:rest) | isHexDigit a && isHexDigit b = do+      let byte = digitToInt a * 16 + digitToInt b+      if byte == 0 then Left "D-Bus socket path contains a NUL byte"+      else (fromIntegral byte :) <$> unescape rest+    unescape ('%':_) = Left "invalid escape in D-Bus socket path"+    unescape (c:rest)+      | isAsciiLower c || isAsciiUpper c || c `elem` ['0'..'9'] || c `elem` "-_/.*\\" =+          (fromIntegral (ord c) :) <$> unescape rest+      | otherwise = Left "unescaped character in D-Bus socket path"++defaultPath :: FilePath -> String+defaultPath home = intercalate ":"+  [home </> ".local/bin", home </> "bin",+   "/usr/local/bin", "/usr/bin", "/bin", "/usr/local/sbin", "/usr/sbin", "/sbin"]++isLocaleVariable :: String -> Bool+isLocaleVariable key = key == "LANG" || key == "LANGUAGE" || "LC_" `isPrefixOf` key++temporaryRoots :: [FilePath]+temporaryRoots = ["/home", "/root", "/tmp", "/run"]++systemDirectories :: [FilePath]+systemDirectories = ["/usr", "/etc", "/bin", "/sbin", "/lib", "/lib64"]++filesystemArgs :: Bool -> IO [String]+filesystemArgs True = pure ["--ro-bind", "/", "/"]+filesystemArgs False = do+  aliases <- fmap concat $ forM (drop 2 systemDirectories) $ \path -> do+    exists <- doesDirectoryExist path+    if not exists then pure [] else do+      symlink <- pathIsSymbolicLink path+      if symlink+        then do+          target <- getSymbolicLinkTarget path+          pure ["--symlink", target, path]+        else pure ["--ro-bind", path, path]+  varHomeExists <- doesPathExist "/var/home"+  varHomeAlias <- if not varHomeExists then pure [] else do+    symlink <- pathIsSymbolicLink "/var/home"+    resolved <- canonicalizePath "/var/home"+    pure $ if symlink && resolved == "/home"+      then ["--symlink", "../home", "/var/home"] else []+  pure $ ["--ro-bind", "/usr", "/usr", "--ro-bind", "/etc", "/etc"]+    ++ aliases ++ concatMap (\path -> ["--dir", path]) ["/var", "/opt", "/srv", "/sys"]+    ++ ["--perms", "1777", "--tmpfs", "/var/tmp"] ++ varHomeAlias++-- Expose only the resolver directory, following atomic file replacements.+-- Toolbx may route /etc/resolv.conf through /run/host/etc first; recreate+-- that hidden link without exposing the rest of the host's /etc directory.+liveResolverArgs :: Bool -> [Mount] -> IO [String]+liveResolverArgs shared mounts = do+  exists <- doesPathExist "/etc/resolv.conf"+  if not exists then pure [] else do+    resolved <- canonicalizePath "/etc/resolv.conf"+    let directory = takeDirectory resolved+        covered path = any (\mount -> within (destination mount) path) mounts+    target <- hiddenSystemTarget (hiddenPath shared) "/etc/resolv.conf"+    status <- getFileStatus resolved+    pure $ case target of+      Just dest | directory `elem` ["/run/systemd/resolve", "/run/host/run/systemd/resolve"]+                  && linkCount status /= 0+                  && not (covered dest) ->+        (if covered resolved then [] else ["--ro-bind", directory, directory]) +++        [arg | dest /= resolved, arg <- ["--symlink", resolved, dest]]+      _ -> []++-- Toolbx links other configuration into /run/host. Mount only those files.+preservedSystemFiles :: Bool -> Bool -> IO [Mount]+preservedSystemFiles shared preserveResolver = fmap concat $ forM+  (["/etc/resolv.conf" | preserveResolver] +++   ["/etc/hosts", "/etc/host.conf", "/etc/localtime"]) $ \path -> do+  exists <- doesPathExist path+  if not exists then pure [] else do+    resolved <- canonicalizePath path+    target <- hiddenSystemTarget (hiddenPath shared) path+    pure $ maybe [] (\dest -> [Mount resolved dest ReadOnlyMount]) target++-- Paths outside the sandbox's view of the enclosing filesystem.+hiddenPath :: Bool -> FilePath -> Bool+hiddenPath shared path+  | shared = any (`within` path) temporaryRoots+  | otherwise = not $ any (`within` path) systemDirectories++-- Stop at the first hidden part of a symlink chain. Its final target may be+-- exposed under /usr, while an intermediate link under /run is still hidden.+-- Inspect parent components too, and resolve relative links against their parent.+hiddenSystemTarget :: (FilePath -> Bool) -> FilePath -> IO (Maybe FilePath)+hiddenSystemTarget hidden = restart+  where+    restart path = walk "/" (drop 1 $ splitDirectories path)+    walk _ [] = pure Nothing+    walk parent (".":rest) = walk parent rest+    walk parent ("..":rest) = walk (takeDirectory parent) rest+    walk parent (part:rest) = do+      let path = parent </> part+      if hidden path+        then pure $ Just $ foldl (</>) path rest+        else do+          symlink <- pathIsSymbolicLink path+          if symlink then do+            target <- getSymbolicLinkTarget path+            let absolute = if isAbsolute target then target else parent </> target+            restart $ foldl (</>) absolute rest+          else walk path rest++existingDirectory :: String -> FilePath -> IO FilePath+existingDirectory label path = do+  exists <- doesDirectoryExist path+  unless exists $ invalid $ label ++ " is not an existing directory: " ++ path+  canonicalizePath path++resolveHome :: FilePath -> IO FilePath+resolveHome path = do+  when (null path) $ invalid "home directory must not be empty"+  resolved <- canonicalizePath path+  rejectRoot "home directory" resolved+  exists <- doesPathExist resolved+  isDir <- doesDirectoryExist resolved+  when (exists && not isDir) $ invalid $ "home is not a directory: " ++ path+  pure resolved++resolveMount :: String -> IO Mount+resolveMount spec = do+  (src, dst, mode) <- either invalid pure (parseMount spec)+  exists <- doesPathExist src+  unless exists $ invalid $ "volume source does not exist: " ++ src+  srcPath <- canonicalizePath src+  when (mode == OverlayMount) $+    unlessM (doesDirectoryExist srcPath) $+      invalid $ "overlay source must be a directory: " ++ src+  dstPath <- canonicalizePath (fromMaybe src dst)+  rejectRoot "volume destination" dstPath+  pure $ Mount srcPath dstPath mode++parseMount :: String -> Either String (FilePath, Maybe FilePath, MountMode)+parseMount spec =+  case splitMountSpec ReadOnlyMount spec of+    ([src], access) | valid src -> Right (src, Nothing, access)+    ([src, dst], access) | valid src && valid dst -> Right (src, Just dst, access)+    _ -> Left $ "invalid volume (expected SOURCE[:DEST][:ro|rw|O]): " ++ spec+  where+    valid = not . null++-- Both project and volume specifications accept the same trailing access mode.+splitMountSpec :: MountMode -> String -> ([String], MountMode)+splitMountSpec fallback spec =+  case reverse parts of+    mode:rest | not (null rest), Just value <- access mode -> (reverse rest, value)+    _ -> (parts, fallback)+  where+    parts = splitColon spec+    access "ro" = Just ReadOnlyMount+    access "rw" = Just ReadWriteMount+    access "O" = Just OverlayMount+    access _ = Nothing++splitColon :: String -> [String]+splitColon input = case break (== ':') input of+  (part, []) -> [part]+  (part, _:rest) -> part : splitColon rest++-- Directory-component comparisons avoid treating /foo and /foobar as overlapping.+within :: FilePath -> FilePath -> Bool+within parent child = splitDirectories (normalise parent)+  `isPrefixOf` splitDirectories (normalise child)++validateMount :: Bool -> Maybe FilePath -> FilePath -> Mount -> IO ()+validateMount shared project home mount = do+  let dest = destination mount+  when (within dest home || maybe False (\path -> within dest path || within path dest) project) $+    invalid $ "volume destination overlaps home or project: " ++ dest+  let temporary = any (`within` dest) (home : temporaryRoots)+  exists <- doesPathExist dest+  when (not exists && not temporary &&+        (shared || any (`within` dest) systemDirectories)) $+    invalid $ "volume destination cannot be created beneath a read-only system mount: " ++ dest+  srcDir <- doesDirectoryExist (source mount)+  dstDir <- doesDirectoryExist dest+  when (exists && srcDir /= dstDir) $+    invalid $ "volume source and destination must both be files or both directories: " ++ dest++mountArgs :: Mount -> [String]+mountArgs mount = case mountMode mount of+  ReadOnlyMount -> ["--ro-bind", source mount, destination mount]+  ReadWriteMount -> ["--bind", source mount, destination mount]+  OverlayMount -> ["--overlay-src", source mount, "--tmp-overlay", destination mount]++resolveEnvironment :: String -> IO (String, String)+resolveEnvironment spec = do+  let (key, suffix) = break (== '=') spec+      letter c = isAsciiLower c || isAsciiUpper c || c == '_'+      valid = case key of+        [] -> False+        first:rest -> letter first && all (\c -> letter c || isDigit c) rest+  unless valid $ invalid $ "invalid environment variable name: " ++ key+  value <- case suffix of+    '=':rest -> pure rest+    _ -> lookupEnv key >>= maybe (invalid $ "environment variable is unset: " ++ key) pure+  pure (key, value)++rejectRoot :: String -> FilePath -> IO ()+rejectRoot label path = when (path == "/") $ invalid $ label ++ " must not be /"
+ src/Sandbox.hs view
@@ -0,0 +1,418 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+-- SPDX-License-Identifier: LGPL-2.1-or-later+module Sandbox+  (NetworkMode(..),+   networkName,+   Arg(..),+   Sandbox(..),+   PrivateNetwork(..),+   NetworkSetupFailure(..),+   Tracker,+   untracked,+   runSandbox,+   previewSandbox,+   pastaArguments,+   userNamespaceArgs,+   privateProcArgs,+   ProbeFailure(..),+   probeNamespaces,+   checkPrivateNetwork)+where++import Control.Concurrent (forkFinally, newEmptyMVar, putMVar, takeMVar, threadDelay)+import Control.Exception (Exception, Handler(..), bracket, catches, finally, throwIO)+import Control.Monad.Extra (unless, void, when)+import Data.Aeson (FromJSON(..), ToJSON(..), eitherDecodeStrict', withObject, withText, (.:))+import Data.Bits (testBit)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BSC+import Data.Maybe (isJust, catMaybes)+import Numeric (readHex)+import SimpleCmd (cmdFull)+import System.Directory+  (createDirectoryIfMissing, doesDirectoryExist, doesFileExist, doesPathExist,+   findExecutable, getFileSize, getHomeDirectory, getTemporaryDirectory, removeFile,+   removePathForcibly)+import System.Environment (lookupEnv)+import System.Exit (ExitCode(..))+import System.FilePath ((</>), isAbsolute)+import System.IO+  (Handle, IOMode(..), SeekMode(..), hClose, hFileSize, hFlush, hSeek,+   openBinaryTempFile, withBinaryFile)+import System.IO.Error (catchIOError, ioeGetErrorString)+import System.Posix.IO (OpenMode(..), closeFd, createPipe, fdToHandle, fdWrite, handleToFd)+import System.Posix.Files (createNamedPipe)+import System.Posix.Process (getProcessID)+import System.Posix.Temp (mkdtemp)+import System.Posix.Types (Fd)+import System.Posix.User (getRealUserID)+import System.Process (CreateProcess(..), StdStream(..), proc)+import System.Timeout (timeout)++import Child+import Util++data NetworkMode = PrivateNetwork | HostNetwork | NoNetwork+  deriving (Eq, Show)++networkName :: NetworkMode -> String+networkName PrivateNetwork = "private"+networkName HostNetwork = "host"+networkName NoNetwork = "none"++instance ToJSON NetworkMode where+  toJSON = toJSON . networkName++instance FromJSON NetworkMode where+  parseJSON = withText "network mode" $+    \case+      "private" -> pure PrivateNetwork+      "host" -> pure HostNetwork+      "none" -> pure NoNetwork+      _ -> fail "unknown network mode"++-- A bubblewrap option word, or a file whose contents bubblewrap reads from+-- a descriptor opened at launch (shown by its placeholder in previews).+data Arg = Arg String | FileFd String FilePath | DataFd String BS.ByteString++data Sandbox = Sandbox+  { sandboxArgs :: [Arg]+  , sandboxCommand :: [String]+  }++data PrivateNetwork = PrivateNetworkConfig+  { pastaExtraArgs :: [String]+  , resolverDestination :: FilePath+  }++-- Private networking failed before the command was released.+newtype NetworkSetupFailure = NetworkSetupFailure String++instance Show NetworkSetupFailure where+  show (NetworkSetupFailure message) = message++instance Exception NetworkSetupFailure++-- Brackets session registration around the released command.+type Tracker = Int -> IO ExitCode -> IO ExitCode++untracked :: Tracker+untracked _ action = action++pastaArguments :: FilePath -> FilePath -> FilePath -> [String]+pastaArguments netns userns pidfile =+  ["--foreground", "--config-net", "--no-map-gw", "--quiet",+   "--dns-forward", "169.254.1.1",+   "-t", "none", "-u", "none", "-T", "none", "-U", "none",+   "--netns", netns, "--userns", userns, "--pid", pidfile]++gateInside :: FilePath+gateInside = "/run/workcell-ready"++-- Wait after bubblewrap has installed its parent-death handling.+-- Blocking its setup with --block-fd could leave an orphan on failure.+gateCommand :: [String]+gateCommand =+  ["/bin/sh", "-c",+   "if IFS= read -r ready < \"$1\" && [ \"$ready\" = ready ]; then shift; exec \"$@\"; fi; exit 1",+   "workcell-session", gateInside]++-- The bubblewrap command (and pasta command, for private networking) with+-- placeholders for launch-time descriptors and paths.+previewSandbox :: Maybe PrivateNetwork -> Sandbox -> [[String]]+previewSandbox network sandbox =+  ("bwrap" : supervision ++ map render (sandboxArgs sandbox) ++ networkArgs +++    ["--"] ++ sandboxCommand sandbox) :+  [ "pasta" : pastaArguments "<netns>" "<userns>" "<pid-file>" | isJust network ]+  where+    render (Arg value) = value+    render (FileFd placeholder _) = placeholder+    render (DataFd placeholder _) = placeholder+    supervision = if isJust network then ["--info-fd", "<info-fd>"] else []+    networkArgs = case network of+      Just config -> ["--ro-bind-data", "<dns-fd>", resolverDestination config,+                      "--ro-bind", "<ready-pipe>", gateInside]+      Nothing -> []++-- Bubblewrap starts the command paused behind a FIFO. Private networking+-- attaches pasta to its network namespace before the command is released.+runSandbox :: Maybe PrivateNetwork -> Tracker -> Sandbox -> IO ExitCode+runSandbox Nothing track sandbox = launch Nothing track sandbox+runSandbox (Just config) track sandbox =+  withPastaLog $ \logHandle -> launch (Just (config, logHandle)) track sandbox++launch :: Maybe (PrivateNetwork, Handle) -> Tracker -> Sandbox -> IO ExitCode+launch network track sandbox =+  -- Pasta may run in a confined SELinux domain which cannot write under HOME,+  -- even when the invoking user has chosen a home directory as TMPDIR.+  withRuntimeDirectory $ \dir -> do+    let readyPipe = dir </> "ready"+    createNamedPipe readyPipe 0o600+    bracket (openSimpleFd readyPipe ReadWrite) closeFd $ \gate ->+      withArgDescriptors (sandboxArgs sandbox) $ \args argFds ->+      withResolver (fst <$> network) $ \resolverArgs resolverFds ->+      withPipe $ \(infoFd, reader, writer) -> do+        let argv = ["--info-fd", show infoFd] ++ args ++ resolverArgs +++              ["--ro-bind", readyPipe, gateInside, "--"] ++ gateCommand ++ sandboxCommand sandbox+        keepOnlyInheritedFds (infoFd : argFds ++ resolverFds)+        withChild ((proc "bwrap" argv) {delegate_ctlc = True, close_fds = False}) $ \child -> do+          hClose writer+          info <- deadline "waiting for bubblewrap namespace setup" $ BS.hGetContents reader+          when (BS.null info) $ do+            code <- waitChild child+            invalid $ "bubblewrap failed during sandbox setup: " ++ show code+          SandboxInfo pid <- either (invalid . ("invalid bubblewrap namespace info: " ++)) pure $+            eitherDecodeStrict' info+          withNetwork network dir pid child $ \wait ->+            track pid $ void (fdWrite gate "ready\n") >> wait++withNetwork :: Maybe (PrivateNetwork, Handle) -> FilePath -> Int -> Child+            -> (IO ExitCode -> IO a) -> IO a+withNetwork Nothing _ _ child action = action (waitChild child)+withNetwork (Just (config, logHandle)) dir pid child action = do+  let childNet = procPath pid "ns/net"+  bracket (setupFailure "cannot open sandbox network namespace" $ openSimpleFd childNet ReadOnly) closeFd $ \netFd ->+    bracket (setupFailure "cannot find network namespace owner" $ ownerNamespace netFd) closeFd $ \userFd -> do+      supervisor <- getProcessID+      confined <- selinuxEnforcing+      let reference fd = "/proc" </> show supervisor </> "fd" </> show fd+          pidfile = dir </> "pasta.pid"+          -- Pasta watches the directory holding its netns path to quit with+          -- the sandbox. Its SELinux policy (passt-selinux) forbids opening+          -- another process's /proc/PID/ns, so skip the watch when confined:+          -- workcell stops pasta itself when the command exits.+          helper = (proc "pasta" (pastaExtraArgs config ++ ["--no-netns-quit" | confined] +++            pastaArguments childNet (reference userFd) pidfile))+            {std_in = NoStream, std_out = NoStream, std_err = CreatePipe, close_fds = True}+      withPastaChild logHandle helper $ \pasta -> do+        timeout (10 * 1000000) (waitReady pidfile child pasta) >>=+          maybe (throwIO $ NetworkSetupFailure "network startup timed out waiting for pasta network setup") pure+        action $ do+          result <- waitEither child pasta+          case result of+            Left code -> pure code+            Right code -> invalid $ "pasta exited while the command was running: " ++ show code+  where+    setupFailure message act = act `catchIOError` \err ->+      throwIO $ NetworkSetupFailure $ message ++ ": " ++ ioeGetErrorString err++-- SELinux is hidden (and pasta unconfined) inside typical toolbox containers.+selinuxEnforcing :: IO Bool+selinuxEnforcing = catchIOError+  ((== "1") . takeWhile (/= '\n') . BSC.unpack <$> BS.readFile "/sys/fs/selinux/enforce")+  (const $ pure False)++waitReady :: FilePath -> Child -> Child -> IO ()+waitReady pidfile child helper = do+  childExited child >>= maybe (pure ()) (\code ->+    invalid $ "bubblewrap exited during network setup: " ++ show code)+  childExited helper >>= maybe (pure ()) (\code ->+    throwIO $ NetworkSetupFailure $ "pasta exited during network setup: " ++ show code)+  ready <- doesFileExist pidfile+  content <- if ready then BS.readFile pidfile else pure ""+  when (BS.null content) $ threadDelay 10000 >> waitReady pidfile child helper++newtype SandboxInfo = SandboxInfo Int++instance FromJSON SandboxInfo where+  parseJSON = withObject "bubblewrap namespace info" $ \object ->+    SandboxInfo <$> object .: "child-pid"++withRuntimeDirectory :: (FilePath -> IO a) -> IO a+withRuntimeDirectory action = do+  runtime <- lookupEnv "XDG_RUNTIME_DIR"+  base <- case runtime of+    Just directory | isAbsolute directory -> do+      exists <- doesDirectoryExist directory+      pure $ if exists then directory else "/tmp"+    _ -> pure "/tmp"+  bracket (mkdtemp $ base </> "workcell-session-") removePathForcibly action++withArgDescriptors :: [Arg] -> ([String] -> [Fd] -> IO a) -> IO a+withArgDescriptors args action = open args [] []+  where+    open [] values fds = action (reverse values) (reverse fds)+    open (Arg value : rest) values fds = open rest (value:values) fds+    open (FileFd _ path : rest) values fds =+      bracket (openSimpleFd path ReadOnly) closeFd $ \fd ->+        open rest (show fd:values) (fd:fds)+    open (DataFd _ bytes : rest) values fds =+      withDataFd "workcell-data-" bytes $ \fd ->+        open rest (show fd:values) (fd:fds)++-- An unlinked temporary file holding the bytes, for bubblewrap to read.+withDataFd :: String -> BS.ByteString -> (Fd -> IO a) -> IO a+withDataFd prefix bytes action = do+  base <- getTemporaryDirectory+  bracket (openBinaryTempFile base prefix) cleanup $ \(path, handle) -> do+    BS.hPut handle bytes+    hSeek handle AbsoluteSeek 0+    removeFile path+    bracket (handleToFd handle) closeFd action+  where+    cleanup (path, handle) = do+      hClose handle+      ignoreMissing $ removeFile path++withPipe :: ((Fd, Handle, Handle) -> IO a) -> IO a+withPipe = bracket acquire release+  where+    acquire = do+      (input, output) <- createPipe+      reader <- fdToHandle input+      writer <- fdToHandle output+      pure (output, reader, writer)+    release (_, reader, writer) = hClose reader >> hClose writer++-- An unlinked resolver file for private networking, pointing to pasta's+-- DNS forwarder and retaining the enclosing search and option settings.+withResolver :: Maybe PrivateNetwork -> ([String] -> [Fd] -> IO a) -> IO a+withResolver Nothing action = action [] []+withResolver (Just config) action = do+  config' <- readResolvConf+  let preserve line = case words line of+        key:_ -> key `elem` ["search", "domain", "options"]+        _ -> False+  withDataFd "workcell-resolv-"+    (BSC.pack $ unlines $ "nameserver 169.254.1.1" : filter preserve config') $ \fd ->+      action ["--ro-bind-data", show fd, resolverDestination config] [fd]++-- Workcell writes the state log itself: a confined pasta may be unable to+-- write an inherited file in HOME, while writing to a pipe is permitted.+withPastaChild :: Handle -> CreateProcess -> (Child -> IO a) -> IO a+withPastaChild logHandle command action =+  withChildStreams command $ \(_, _, output, pasta) -> do+    reader <- maybe (invalid "missing pasta diagnostics pipe") pure output+    finished <- newEmptyMVar+    _ <- forkFinally (copyDiagnostics reader) (putMVar finished)+    action pasta `finally` do+      -- Stopping pasta closes the pipe; wait until its output is logged.+      stopChild pasta+      takeMVar finished >>= either throwIO pure+      hClose reader+  where+    copyDiagnostics reader = do+      bytes <- BS.hGetSome reader 8192+      unless (BS.null bytes) $ do+        BS.hPut logHandle bytes+        hFlush logHandle+        copyDiagnostics reader++withPastaLog :: (Handle -> IO ExitCode) -> IO ExitCode+withPastaLog action = bracket acquire release $ \(path, handle) ->+  action handle `catches`+    [Handler $ \err -> do+       message <- withDiagnostics path handle (ioeGetErrorString err)+       invalid message,+     Handler $ \(NetworkSetupFailure err) -> do+       message <- withDiagnostics path handle err+       throwIO $ NetworkSetupFailure message]+  where+    -- The helper and diagnostics copier have stopped. Release the writer+    -- before opening the log for reading (GHC locks handles within a process).+    withDiagnostics path handle message = do+      hClose handle+      tailText <- catchIOError (diagnosticTail path) $ const $ pure "(unable to read pasta log)\n"+      pure $ message +++        (if null tailText then "" else "\nPasta log: " ++ path +++          "\nRecent pasta diagnostics:\n" ++ tailText)+    -- Empty logs are removed; logs with diagnostics are kept.+    release (path, handle) = do+      hClose handle+      ignoreMissing $ do+        size <- getFileSize path+        when (size == 0) $ removeFile path+    acquire = catchIOError openLog $ \err ->+      invalid $ "cannot open pasta log: " ++ ioeGetErrorString err+    openLog = do+      state <- lookupEnv "XDG_STATE_HOME"+      base <- case state of+        Just path | isAbsolute path -> pure path+        _ -> (</> ".local/state") <$> getHomeDirectory+      let directory = base </> "workcell/logs"+      createDirectoryIfMissing True directory+      -- openBinaryTempFile creates the file exclusively with mode 0600.+      openBinaryTempFile directory "pasta.log"++-- Bound both bytes and lines, even for a noisy helper or a huge single line.+diagnosticTail :: FilePath -> IO String+diagnosticTail path = withBinaryFile path ReadMode $ \handle -> do+  size <- hFileSize handle+  hSeek handle AbsoluteSeek (max 0 $ size - 8192)+  bytes <- BS.hGet handle 8192+  let recent = lines $ BSC.unpack bytes+  pure $ unlines $ drop (max 0 $ length recent - 20) recent++deadline :: String -> IO a -> IO a+deadline message action = timeout (10 * 1000000) action >>= maybe+  (invalid $ "sandbox startup timed out " ++ message) pure++-- Bubblewrap implicitly creates a user namespace for non-root callers.+-- Root without CAP_SYS_ADMIN needs to request it explicitly.+userNamespaceArgs :: IO [String]+userNamespaceArgs = do+  uid <- getRealUserID+  if uid /= 0 then pure [] else do+    status <- catchIOError (BSC.readFile "/proc/self/status") $ const $ pure BS.empty+    let effectiveCaps = [mask | line <- BSC.lines status,+                                ["CapEff:", value] <- [BSC.words line],+                                (mask, "") <- readHex (BSC.unpack value)]+    pure $ case effectiveCaps of+      [mask] | not (testBit (mask :: Integer) capSysAdmin) -> ["--unshare-user"]+      _ -> []+  where+    capSysAdmin = 21++privateProcArgs :: [String]+privateProcArgs = ["--unshare-pid", "--proc", "/proc"]++data ProbeFailure = BaseSandboxUnavailable String+                  | ProcessIsolationUnavailable String+                  | NetworkIsolationUnavailable String++-- Probe the namespaces together on the success path. On failure, check the+-- base mount setup before attributing the error to PID or network isolation.+probeNamespaces :: [String] -> Bool -> Bool -> IO (Maybe ProbeFailure)+probeNamespaces userArgs privateProc privateNet+  | not privateProc && not privateNet = pure Nothing+  | otherwise = do+      failure <- probe $ (if privateProc then privateProcArgs else []) +++                         ["--unshare-net" | privateNet]+      case failure of+        Nothing -> pure Nothing+        Just err -> do+          baseFailure <- probe []+          case baseFailure of+            Just baseErr -> pure $ Just $ BaseSandboxUnavailable baseErr+            Nothing | privateProc && privateNet -> do+              processFailure <- probe privateProcArgs+              pure $ Just $ maybe (NetworkIsolationUnavailable err)+                ProcessIsolationUnavailable processFailure+            Nothing -> pure $ Just $ if privateProc+              then ProcessIsolationUnavailable err else NetworkIsolationUnavailable err+  where+    probe args = do+      (ok, _, err) <- cmdFull "bwrap" (userArgs +++        ["--die-with-parent", "--ro-bind", "/", "/", "--dev", "/dev"] +++        args ++ ["--", "/bin/true"]) ""+      pure $ if ok then Nothing else Just err++-- Requirements for private networking which can be checked without+-- launching anything. Returns the reason if it is unavailable.+checkPrivateNetwork :: IO (Maybe String)+checkPrivateNetwork = do+  pasta <- findExecutable "pasta"+  tun <- doesPathExist "/dev/net/tun"+  config <- readResolvConf+  pure $ case catMaybes+    [ if isJust pasta then Nothing else Just "pasta is not installed or not on PATH"+    , if tun then Nothing else Just "/dev/net/tun is unavailable in the enclosing environment"+    , if any nameserver config then Nothing else Just "no nameserver is configured in /etc/resolv.conf"+    ] of+    reason:_ -> Just reason+    [] -> Nothing+  where+    nameserver line = case words line of+      "nameserver":(first:_):_ -> first /= '#'+      _ -> False
+ src/Session.hs view
@@ -0,0 +1,279 @@+{-# LANGUAGE DeriveGeneric #-}+-- SPDX-License-Identifier: LGPL-2.1-or-later++module Session (+  SessionDetails(..),+  Session(..),+  withSession,+  listSessions,+  findSession,+  validSession+  )+where++import Control.Exception (bracket)+import Control.Concurrent (threadDelay)+import Control.Monad (filterM, unless, when)+import Data.Aeson (FromJSON, ToJSON, eitherDecodeStrict', encode)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Lazy as BL+import qualified Data.ByteString.Char8 as BSC+import Data.Bits ((.&.))+import Data.Char (isDigit, isAsciiLower, isAsciiUpper)+import Data.List (intercalate, sort, transpose)+import Data.Maybe (catMaybes, fromMaybe, mapMaybe)+import GHC.Generics (Generic)+import SimpleCmd (warning)+import System.Directory+import System.Environment (lookupEnv)+import System.FilePath ((</>), isAbsolute, takeFileName)+import System.IO+  (Handle, hClose, hFlush, hIsTerminalDevice, isEOF, hPutStr, hPutStrLn,+   openBinaryTempFile, stderr, stdin, stdout)+import System.IO.Error (catchIOError, tryIOError)+import System.Posix.Files+import System.Posix.User (getEffectiveUserID)+import System.Timeout (timeout)+import Text.Read (readMaybe)++import Sandbox (NetworkMode, networkName)+import Util (ignoreMissing, invalid, procPath, shellQuote)++data SessionDetails = SessionDetails+  { sessionProject :: Maybe FilePath+  , sessionCommand :: [String]+  , sessionNetwork :: NetworkMode+  , sessionSharedProcesses :: Bool+  } deriving (Show, Generic)++instance FromJSON SessionDetails+instance ToJSON SessionDetails++data Session = Session+  { sessionID :: String+  , sessionPID :: Int+  , sessionStart :: String+  , sessionBoot :: String+  , sessionPIDNamespace :: String+  , sessionMountNamespace :: String+  , sessionDetails :: SessionDetails+  } deriving (Show, Generic)+instance FromJSON Session+instance ToJSON Session++strictRead :: FilePath -> IO String+strictRead path = map (toEnum . fromEnum) . BS.unpack <$> BS.readFile path++bootID :: IO String+bootID = unwords . words <$> strictRead "/proc/sys/kernel/random/boot_id"++pidNamespace :: IO String+pidNamespace = readSymbolicLink "/proc/self/ns/pid"++-- comm may contain spaces and closing parentheses; fields after its LAST ')'+-- start with state (field 3), making starttime (field 22) index 19.+processStart :: Int -> IO String+processStart pid = do+  content <- strictRead $ procPath pid "stat"+  let fields = words $ reverse $ takeWhile (/= ')') $ reverse content+  case fields of+    state:_ | state /= "Z" && state /= "X", length fields > 19 -> pure $ fields !! 19+    _ -> invalid "session process has exited or has invalid /proc metadata"++secureDirectory :: FilePath -> IO ()+secureDirectory path = do+  createDirectoryIfMissing True path+  status <- getSymbolicLinkStatus path+  uid <- getEffectiveUserID+  unless (isDirectory status && fileOwner status == uid) $+    invalid $ "unsafe session directory: " ++ path+  -- Only this user's processes should discover or replace session records.+  setFileMode path 0o700++sessionDirectory :: Bool -> IO FilePath+sessionDirectory create = do+  runtime <- lookupEnv "XDG_RUNTIME_DIR"+  base <- case runtime of+    Just path | isAbsolute path -> pure path+    _ -> do+      state <- lookupEnv "XDG_STATE_HOME"+      case state of+        Just path | isAbsolute path -> pure path+        _ -> (</> ".local/state") <$> getHomeDirectory+  ns <- pidNamespace+  let parent = base </> "workcell/sessions"+      path = parent </> filter isDigit ns+  if create+    then secureDirectory parent >> secureDirectory path+    else do+      exists <- doesPathExist parent+      when exists $ checkDirectory parent+      childExists <- doesPathExist path+      when childExists $ checkDirectory path+  pure path+  where+    checkDirectory path = do+      status <- getSymbolicLinkStatus path+      uid <- getEffectiveUserID+      unless (isDirectory status && fileOwner status == uid && fileMode status .&. 0o077 == 0) $+        invalid $ "unsafe session directory: " ++ path++withSession :: SessionDetails -> Int -> IO a -> IO a+withSession details pid action = do+  storage <- tryIOError $ sessionDirectory True+  case storage of+    Left err -> do+      warning $ "running without session tracking (" ++ show err ++ ")"+      action+    Right directory -> bracket (register directory) cleanup $ const action+  where+    register directory = do+      commandPID <- timeout (10 * 1000000) (findCommandPID pid) >>= maybe+        (invalid "timed out finding the paused sandbox command") pure+      start <- processStart commandPID+      boot <- bootID+      ns <- pidNamespace+      mount <- readSymbolicLink $ procPath commandPID "ns/mnt"+      bracket (openBinaryTempFile directory "pending-")+        (\(path, handle) -> hClose handle >> ignoreMissing (removeFile path)) $ \(path, handle) -> do+          let ident = "s" ++ drop (length "pending-") (takeFileName path)+              record = Session ident commandPID start boot ns mount details+              final = directory </> ident+          BL.hPut handle $ encode record+          hClose handle+          renameFile path final+          pure final+    cleanup = ignoreMissing . removeFile++-- With private PIDs, bubblewrap reports its tiny init process. Register the+-- paused exec shell underneath it: its PID survives exec, and /proc/environ+-- reflects the sandbox environment rather than bubblewrap's original one.+findCommandPID :: Int -> IO Int+findCommandPID pid = do+  result <- search pid+  case result of+    Just found -> pure found+    Nothing -> do+      _ <- catchIOError (processStart pid) $ const $+        invalid "the sandbox exited during setup"+      threadDelay 10000+      findCommandPID pid+  where+    -- Processes may exit while being inspected; retry from the top.+    search candidate = flip catchIOError (const $ pure Nothing) $ do+      argv <- BS.split 0 <$> BS.readFile (procPath candidate "cmdline")+      if take 2 argv == map BSC.pack ["/bin/sh", "-c"] && BSC.pack "workcell-session" `elem` argv+        then pure $ Just candidate+        else do+          children <- words <$> strictRead (procPath candidate $ "task" </> show candidate </> "children")+          results <- mapM search $ mapMaybe readMaybe children+          pure $ case catMaybes results of+            found:_ -> Just found+            [] -> Nothing++validSession :: Session -> IO Bool+validSession record = catchIOError check $ const $ pure False+  where+    check = do+      start <- processStart $ sessionPID record+      boot <- bootID+      ns <- pidNamespace+      mount <- readSymbolicLink $ procPath (sessionPID record) "ns/mnt"+      pure $ start == sessionStart record && boot == sessionBoot record &&+        ns == sessionPIDNamespace record && mount == sessionMountNamespace record++sessions :: IO [Session]+sessions = do+  directory <- sessionDirectory False+  exists <- doesDirectoryExist directory+  if not exists then pure [] else do+    paths <- sort <$> listDirectory directory+    records <- mapM (readRecord directory) $ filter validID paths+    filterM (removeStale directory) $ catMaybes records+  where+    -- Records left behind by an uncatchable stop (or SIGKILL) are removed+    -- once their process is gone.+    removeStale directory record = do+      valid <- validSession record+      unless valid $ ignoreMissing $ removeFile $ directory </> sessionID record+      pure valid+    readRecord directory ident = catchIOError (do+      let path = directory </> ident+      status <- getSymbolicLinkStatus path+      uid <- getEffectiveUserID+      if not (isRegularFile status && fileOwner status == uid && fileMode status .&. 0o077 == 0)+        then pure Nothing+        else do+          bytes <- BS.readFile path+          pure $ case eitherDecodeStrict' bytes of+            Right record | sessionID record == ident -> Just record+            _ -> Nothing) $ const $ pure Nothing++validID :: String -> Bool+validID ('s':suffix) = not (null suffix) && all (\c -> isDigit c || isAsciiLower c || isAsciiUpper c || c == '-') suffix+validID _ = False++listSessions :: IO ()+listSessions = sessions >>= printSessions++printSessions :: [Session] -> IO ()+printSessions = printSessionRows stdout False++printSessionRows :: Handle -> Bool -> [Session] -> IO ()+printSessionRows output numbered records =+  unless (null records) $ do+    let header = ["#" | numbered] ++ ["ID", "PROJECT", "NETWORK", "COMMAND"]+        rows = header : zipWith (\index record ->+          [show index | numbered] ++ row record) [1 :: Int ..] records+        widths = map (maximum . map length) (transpose $ map init rows) ++ [0]+        pad width value = value ++ replicate (width - length value) ' '+    mapM_ (hPutStrLn output . intercalate "  " . zipWith pad widths) rows+  where+    row record =+      let details = sessionDetails record+      in [sessionID record, fromMaybe "-" $ sessionProject details,+         networkName (sessionNetwork details), unwords $ map shellQuote $ sessionCommand details]++findSession :: Maybe String -> IO Session+findSession Nothing = do+  records <- sessions+  case records of+    [found] -> pure found+    [] -> invalid "no active sessions in this PID namespace (use workcell list)"+    _ -> do+      interactive <- hIsTerminalDevice stdin+      if interactive+        then chooseSession records+        else do+          printSessions records+          hFlush stdout+          invalid "multiple active sessions; specify a session ID"+findSession (Just ident) = do+  unless (validID ident) $ invalid "invalid session ID (use workcell list)"+  matches <- filter ((== ident) . sessionID) <$> sessions+  case matches of+    [found] -> pure found+    _ -> invalid $ "unknown or expired session " ++ ident ++ " in this PID namespace (use workcell list)"++-- Keep the displayed snapshot stable while the user chooses its row number.+chooseSession :: [Session] -> IO Session+chooseSession records = do+  printSessionRows stderr True records+  prompt+  where+    count = length records+    prompt = do+      hPutStr stderr $ "Select a workcell [1-" ++ show count ++ "] (Enter to cancel): "+      hFlush stderr+      eof <- isEOF+      when eof $ invalid "session selection cancelled"+      answer <- getLine+      when (null $ words answer) $ invalid "session selection cancelled"+      case readMaybe answer :: Maybe Integer of+        Just index | index >= 1 && index <= toInteger count ->+          case drop (fromInteger index - 1) records of+            selected:_ -> pure selected+            [] -> invalid "invalid session selection"+        _ -> do+          warning $ "Please enter a number from 1 to " ++ show count ++ "."+          prompt
+ src/Util.hs view
@@ -0,0 +1,90 @@+{-# LANGUAGE CApiFFI #-}+{-# LANGUAGE CPP #-}+-- SPDX-License-Identifier: LGPL-2.1-or-later+module Util (+  invalid,+  ignoreMissing,+  procPath,+  shellQuote,+  openSimpleFd,+  ownerNamespace,+  withDescriptors,+  readResolvConf,+  keepOnlyInheritedFds+  )+where++import Control.Exception (bracket)+import Control.Monad (forM_, unless)+import Data.Maybe (mapMaybe)+import Foreign.C.Error (throwErrnoIfMinus1)+import Foreign.C.Types (CInt(..), CULong(..))+import System.Directory (doesFileExist, listDirectory)+import System.FilePath ((</>))+import System.IO.Error (catchIOError, isDoesNotExistError)+import System.Posix.IO+  (FdOption(CloseOnExec), OpenMode(..), closeFd, defaultFileFlags, openFd, setFdOption)+import System.Posix.Types (Fd(..))+import Text.Read (readMaybe)++invalid :: String -> IO a+invalid = ioError . userError++ignoreMissing :: IO () -> IO ()+ignoreMissing action = catchIOError action $ \err ->+  unless (isDoesNotExistError err) $ ioError err++procPath :: Int -> FilePath -> FilePath+procPath pid suffix = "/proc" </> show pid </> suffix++shellQuote :: String -> String+shellQuote value = "'" ++ concatMap escape value ++ "'"+  where+    escape '\'' = "'\\''"+    escape c = [c]++-- taken from shake General.FileLock+openSimpleFd :: FilePath -> OpenMode -> IO Fd+#if MIN_VERSION_unix(2,8,0)+openSimpleFd file mode = openFd file mode defaultFileFlags+#else+openSimpleFd file mode = openFd file mode Nothing defaultFileFlags+#endif++withDescriptors :: [FilePath] -> ([Fd] -> IO a) -> IO a+withDescriptors [] action = action []+withDescriptors (path:rest) action =+  bracket (openSimpleFd path ReadOnly) closeFd $ \fd ->+    withDescriptors rest $ \fds -> action (fd:fds)++-- ioctl is variadic: capi calls it through its C prototype.+foreign import capi unsafe "sys/ioctl.h ioctl"+  namespaceIoctl :: CInt -> CULong -> CULong -> IO CInt++foreign import capi unsafe "linux/nsfs.h value NS_GET_USERNS"+  getOwnerNamespace :: CULong++-- The user namespace owning a namespace, even if bubblewrap later enters+-- a child user namespace to restore the invoking UID after devpts setup.+ownerNamespace :: Fd -> IO Fd+ownerNamespace (Fd fd) = Fd <$> throwErrnoIfMinus1 "namespace owner"+  (namespaceIoctl fd getOwnerNamespace 0)++readResolvConf :: IO [String]+readResolvConf = do+  exists <- doesFileExist "/etc/resolv.conf"+  if exists then lines <$> readFile "/etc/resolv.conf" else pure []++-- Mark every descriptor above stderr close-on-exec except those listed,+-- including ones opened by the GHC runtime, so that a child started with+-- close_fds = False inherits only the descriptors it is meant to consume.+keepOnlyInheritedFds :: [Fd] -> IO ()+keepOnlyInheritedFds keep = do+  open <- mapMaybe readMaybe <$> listDirectory "/proc/self/fd"+  forM_ open $ \n -> do+    let fd = Fd n+    unless (n <= 2) $+      -- The listing's own directory descriptor is already closed.+      ignoreBadFd $ setFdOption fd CloseOnExec (fd `notElem` keep)+  where+    ignoreBadFd action = catchIOError action $ const $ pure ()
+ test/Spec.hs view
@@ -0,0 +1,1734 @@+-- SPDX-License-Identifier: LGPL-2.1-or-later+{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}++module Main (main) where++import Control.Exception (bracket, throwIO, throwTo)+import Control.Concurrent (forkFinally, myThreadId, newEmptyMVar, putMVar, takeMVar, threadDelay)+import Control.Monad (forM_, unless, void, when, (>=>))+import Data.Aeson (Value(..), eitherDecodeStrict', encode)+import qualified Data.Aeson.KeyMap as KM+import qualified Data.ByteString.Lazy as BL+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BSC+import Data.List (isPrefixOf)+import Data.Maybe (fromMaybe, isNothing)+import qualified Network.Socket as Net+import System.Directory hiding (executable)+import System.Environment (getArgs, getEnvironment, getExecutablePath, lookupEnv)+import System.Exit (ExitCode(..), die, exitWith)+import System.FilePath ((</>), takeDirectory)+import System.IO (hClose, hFlush, hGetLine, hPutStr, hPutStrLn)+import System.IO.Error (catchIOError, isDoesNotExistError)+import System.Posix.Files (fileMode, fileOwner, getFileStatus, readSymbolicLink, setFileMode)+import Data.Bits ((.&.))+import qualified System.Posix.IO as Posix+import System.Posix.Temp (mkdtemp)+import System.Posix.Terminal (openPseudoTerminal)+#if MIN_VERSION_unix(2,8,0)+import System.Posix.User.ByteString (UserEntry(UserEntry),+                                     GroupEntry(GroupEntry))+import System.Posix.User (userName, groupName, getEffectiveGroupID,+                          getEffectiveUserID, getUserEntryForID,+                          getGroupEntryForID)+#else+import System.Posix.User (UserEntry(..), GroupEntry(..), getEffectiveGroupID, getEffectiveUserID,+                          getUserEntryForID, getGroupEntryForID)+#endif+import System.Posix.Signals (Handler(CatchOnce), installHandler, signalProcess, sigKILL, sigTERM)+import System.Process hiding (shell)+import System.Timeout (timeout)+import Test.Hspec++import qualified Sandbox as WorkcellSandbox+import qualified Identity as WorkcellIdentity+import qualified Session as WorkcellSession+import qualified Util as WorkcellUtil++data Context = Context+  { binary :: FilePath+  , privateProc :: Bool+  , privateNet :: Bool+  , pastaNet :: Bool+  , root :: FilePath+  , project :: FilePath+  , home :: FilePath+  }++directoryUser :: UserEntry+directoryUser = UserEntry "workcell-nss-test" "secret" 424242 424242+  "Directory User" "/home/directory" "/bin/bash"++directoryGroup :: GroupEntry+directoryGroup = GroupEntry "workcell-nss-test" "secret" 424242 ["workcell-nss-test"]++withEntries :: (BS.ByteString -> [String]) -> BS.ByteString -> BS.ByteString+withEntries missing original = WorkcellIdentity.appendEntries original (missing original)++main :: IO ()+main = do+  args <- getArgs+  case args of+    "--test-identity-files":bwrapArgs -> withTestTermination $ do+      let sandbox = testSandbox bwrapArgs+          snapshots = concat+            [[WorkcellSandbox.Arg "--ro-bind-data", WorkcellSandbox.DataFd name content,+              WorkcellSandbox.Arg path]+            | (path, name, content) <-+              [("/etc/passwd", "<passwd-fd>", withEntries (WorkcellIdentity.passwdEntries [directoryUser]) "root:x:0:0::/root:/bin/sh\n"),+               ("/etc/group", "<group-fd>", withEntries (WorkcellIdentity.groupEntries [directoryGroup]) "root:x:0:\n")]]+      WorkcellSandbox.runSandbox Nothing WorkcellSandbox.untracked+        sandbox {WorkcellSandbox.sandboxArgs = WorkcellSandbox.sandboxArgs sandbox ++ snapshots} >>= exitWith+    "--test-tracked-loopback-network":bwrapArgs -> withTestTermination $+      WorkcellSandbox.runSandbox loopbackNetwork+        (WorkcellSession.withSession $ WorkcellSession.SessionDetails Nothing ["sleep", "30"]+           WorkcellSandbox.PrivateNetwork False)+        (testSandbox bwrapArgs) >>= exitWith+    "--test-loopback-network":bwrapArgs -> withTestTermination $+      WorkcellSandbox.runSandbox loopbackNetwork WorkcellSandbox.untracked+        (testSandbox bwrapArgs) >>= exitWith+    _ -> testMain+  where+    loopbackNetwork = Just $+      WorkcellSandbox.PrivateNetworkConfig ["--splice-only"] "/tmp/workcell-test-resolv"+    testSandbox args =+      let (options, cmd) = break (== "--") args+      in WorkcellSandbox.Sandbox (map WorkcellSandbox.Arg options) (drop 1 cmd)++-- Match the CLI's SIGTERM handling so the helper exercises bracket cleanup.+withTestTermination :: IO a -> IO a+withTestTermination action = do+  thread <- myThreadId+  bracket (installHandler sigTERM (CatchOnce $ throwTo thread $ ExitFailure 143) Nothing)+    (\previous -> void (installHandler sigTERM previous Nothing)) $ const action++testMain :: IO ()+testMain = do+  bwrap <- findExecutable "bwrap" >>= maybe+    (die "workcell integration tests require bubblewrap (bwrap) on PATH") pure+  executable <- lookupEnv "WORKCELL" >>= maybe+    (findExecutable "workcell" >>= maybe (fail "workcell executable not found") pure) pure+  resolved <- canonicalizePath executable+  (code, _, _) <- capture $ proc bwrap+    ["--die-with-parent", "--ro-bind", "/", "/", "--dev", "/dev",+     "--unshare-pid", "--proc", "/proc", "--", "/bin/true"]+  (netCode, _, _) <- capture $ proc bwrap+    ["--die-with-parent", "--ro-bind", "/", "/", "--dev", "/dev",+     "--unshare-net", "--", "/bin/true"]+  pasta <- findExecutable "pasta"+  tun <- doesPathExist "/dev/net/tun"+  resolverExists <- doesFileExist "/etc/resolv.conf"+  resolver <- if resolverExists then readFile "/etc/resolv.conf" else pure ""+  let nameservers = [address | "nameserver":address:_ <- map words (lines resolver)]+  -- Probe the helper independently: a workcell regression must fail its tests,+  -- rather than making private-network examples appear unsupported.+  (pastaCode, _, _) <- case pasta of+    Just helper | tun && not (null nameservers) -> capture $ proc helper+      ["--config-net", "--no-map-gw", "--no-pidns",+       "--dns-forward", "169.254.1.1", "-t", "none", "-u", "none",+       "-T", "none", "-U", "none", "--", "/bin/true"]+    _ -> pure (ExitFailure 1, "", "pasta, /dev/net/tun, or resolver configuration is missing")+  hspec $ around (withContext resolved (code == ExitSuccess)+                 (netCode == ExitSuccess) (pastaCode == ExitSuccess)) spec++withContext :: FilePath -> Bool -> Bool -> Bool -> ActionWith Context -> IO ()+withContext executable supported netSupported pastaSupported action = do+  hostHome <- getHomeDirectory >>= canonicalizePath+  bracket (mkdtemp $ hostHome </> "workcell tests ") removePathForcibly $ \dir -> do+    let workdir = dir </> "project with spaces"+    createDirectory workdir+    action $ Context executable supported netSupported pastaSupported dir workdir hostHome++-- Each command has a timeout; process's bracket cleanup stops it on timeout.+capture :: CreateProcess -> IO (ExitCode, String, String)+capture command = timeout (30 * 1000000) (readCreateProcessWithExitCode command "")+  >>= maybe (fail "command timed out after 30 seconds") pure++invoke :: Context -> Maybe Bool -> Maybe [(String, String)] -> [String]+       -> IO (ExitCode, String, String)+invoke ctx shared environment args = invokeDefault ctx shared environment $+  ["--network-host" | not (hasNetworkOption args) && "--dryrun" `notElem` args] ++ args++-- Exercise default fallback without the suite's usual explicit host mode.+invokeDefault :: Context -> Maybe Bool -> Maybe [(String, String)] -> [String]+              -> IO (ExitCode, String, String)+invokeDefault ctx shared environment args = capture $+  (proc (binary ctx) (flags ++ args)) {cwd = Just (project ctx), env = environment}+  where+    sharing = fromMaybe (not (privateProc ctx) && "--dryrun" `notElem` args) shared+    flags = ["--share-processes" | sharing]++hasNetworkOption :: [String] -> Bool+hasNetworkOption = any ("--network-" `isPrefixOf`) . takeWhile (/= "--")++success :: Context -> [String] -> IO String+success ctx args = successful =<< invoke ctx Nothing Nothing args++successful :: (ExitCode, String, String) -> IO String+successful (code, out, err) = do+  unless (code == ExitSuccess) $ expectationFailure $ show code ++ ": " ++ err+  pure out++failure :: Context -> [String] -> IO String+failure ctx args = do+  (code, _, err) <- invoke ctx Nothing Nothing args+  code `shouldNotBe` ExitSuccess+  pure err++shell :: Context -> String -> [String] -> IO ()+shell ctx script args = do+  _ <- success ctx $ ["--", "/bin/sh", "-c", "set -eu\n" ++ script, "check"] ++ args+  pure ()++spec :: SpecWith Context+spec = describe "workcell CLI" $ do+  it "adds directory accounts absent from local passwd and group files" $ \_ -> do+    withEntries (WorkcellIdentity.passwdEntries [directoryUser]) "root:x:0:0::/root:/bin/sh" `shouldBe`+      "root:x:0:0::/root:/bin/sh\nworkcell-nss-test:x:424242:424242:Directory User:/home/directory:/bin/bash\n"+    withEntries (WorkcellIdentity.groupEntries [directoryGroup]) "root:x:0:\n" `shouldBe`+      "root:x:0:\nworkcell-nss-test:x:424242:workcell-nss-test\n"+    withEntries (WorkcellIdentity.passwdEntries [directoryUser]) "" `shouldBe`+      "workcell-nss-test:x:424242:424242:Directory User:/home/directory:/bin/bash\n"++  it "copies directory account bytes without re-encoding them" $ \_ -> do+    -- NSS strings hold one Char per byte: these are the UTF-8 bytes of "é".+    let user = UserEntry "workcell-nss-test" "secret" 424242 424242+          "Peters\195\169n" "/home/directory" "/bin/bash"+    withEntries (WorkcellIdentity.passwdEntries [user]) "" `shouldBe`+      "workcell-nss-test:x:424242:424242:Peters\195\169n:/home/directory:/bin/bash\n"++  it "preserves existing local identities and does not duplicate snapshots" $ \_ -> do+    let passwd = "local:x:424242:12:Local User:/home/local:/bin/sh\n"+        group = "local:x:424242:local\n"+        snapshot = withEntries (WorkcellIdentity.passwdEntries [directoryUser]) ""+    WorkcellIdentity.passwdEntries [directoryUser] passwd `shouldBe` []+    WorkcellIdentity.groupEntries [directoryGroup] group `shouldBe` []+    WorkcellIdentity.passwdEntries [directoryUser] snapshot `shouldBe` []++  it "resolves snapshotted directory identities with host service paths hidden" $ \_ -> do+    executable <- getExecutablePath+    -- Replace /etc: an enclosing workcell's /etc/passwd copy cannot be mounted over.+    let flags = ["--ro-bind", "/", "/", "--dev", "/dev", "--tmpfs", "/run",+                 "--tmpfs", "/var", "--tmpfs", "/etc",+                 "--ro-bind", "/etc/nsswitch.conf", "/etc/nsswitch.conf", "--", "/bin/sh", "-ec",+                 "id -u workcell-nss-test; getent group 424242; " +++                 "! (printf changed > /etc/passwd); ! (printf changed > /etc/group)"]+    out <- successful =<< capture (proc executable ("--test-identity-files" : flags))+    out `shouldBe` "424242\nworkcell-nss-test:x:424242:workcell-nss-test\n"++  it "preserves the invoking host user and group names" $ \ctx -> do+    uid <- getEffectiveUserID+    gid <- getEffectiveGroupID+    account <- catchIOError+      (Just <$> ((,) <$> getUserEntryForID uid <*> getGroupEntryForID gid)) $ \err ->+        if isDoesNotExistError err then pure Nothing else ioError err+    case account of+      Nothing -> pendingWith "invoking account names are already unavailable outside workcell"+      Just (user, group) -> do+        success ctx ["--", "id", "-un"] `shouldReturn` userName user ++ "\n"+        success ctx ["--", "id", "-gn"] `shouldReturn` groupName group ++ "\n"++  it "enters no unknown session" $ \ctx -> do+    sessionInvoke ctx ["list"] >>= successful >>= (`shouldBe` "")+    (code1, _, emptyError) <- sessionInvoke ctx ["enter"]+    code1 `shouldNotBe` ExitSuccess+    emptyError `shouldContain` "no active sessions"+    emptyError `shouldContain` "workcell list"+    (code2, _, err) <- sessionInvoke ctx ["enter", "s123"]+    code2 `shouldNotBe` ExitSuccess+    err `shouldContain` "unknown or expired"+    err `shouldContain` "workcell list"+    doesDirectoryExist (project ctx </> "unwanted") >>= (`shouldBe` False)++  it "automatically enters the only active session, including root and dry-run modes" $ \ctx -> do+    withRunningSession ctx [] $ \ident -> do+      sessionInvoke ctx ["enter"] >>= successful >>= (`shouldBe` "")+      sessionInvoke ctx ["enter", "--root"] >>= successful >>= (`shouldBe` "")+      forM_ [[], ["--root"]] $ \flags -> do+        explicit <- successful =<< sessionInvoke ctx (["enter", ident, "--dryrun"] ++ flags)+        automatic <- successful =<< sessionInvoke ctx (["enter", "--dryrun"] ++ flags)+        automatic `shouldBe` explicit+        early <- successful =<< sessionInvoke ctx (["enter", "--dryrun", ident] ++ flags)+        early `shouldBe` explicit++  it "tracks concurrent sessions and removes records on termination" $ \ctx -> do+    withRunningSession ctx [] $ \first -> do+      withRunningSession ctx [] $ \second -> do+        first `shouldNotBe` second+        listing <- successful =<< sessionInvoke ctx ["list"]+        forM_ [[], ["--dryrun"], ["--root"]] $ \flags -> do+          (code, output, err) <- sessionInvoke ctx ("enter" : flags)+          code `shouldNotBe` ExitSuccess+          output `shouldBe` listing+          err `shouldContain` "multiple active sessions; specify a session ID"+        preview <- successful =<< sessionInvoke ctx ["enter", first, "--dryrun"]+        preview `shouldContain` "nsenter"+        output <- successful =<< sessionInvoke ctx ["list"]+        output `shouldContain` first+        output `shouldContain` second+        output `shouldContain` project ctx+        output `shouldContain` "host"+      output <- successful =<< sessionInvoke ctx ["list"]+      output `shouldContain` first+      length (lines output) `shouldBe` 2+    sessionRecordPaths ctx >>= (`shouldBe` [])+    sessionInvoke ctx ["list"] >>= successful >>= (`shouldBe` "")++  it "offers a numbered session menu and validates choices on terminal input" $ \ctx -> do+    withRunningSession ctx [] $ \_ ->+      withRunningSession ctx [] $ \_ -> do+        listing <- successful =<< sessionInvoke ctx ["list"]+        let identifiers = [ident | row <- drop 1 $ lines listing, ident:_ <- [words row]]+        length identifiers `shouldBe` 2+        forM_ (zip [1 :: Int ..] identifiers) $ \(index, ident) ->+          forM_ [[], ["--root"]] $ \flags -> do+            expected <- successful =<< sessionInvoke ctx (["enter", ident, "--dryrun"] ++ flags)+            (code, output, menu) <- menuInvoke ctx flags ("bad\n0\n3\n" ++ show index ++ "\n")+            code `shouldBe` ExitSuccess+            output `shouldBe` expected+            forM_ identifiers $ \name -> menu `shouldContain` name+            menu `shouldContain` "#"+            menu `shouldContain` "Select a workcell [1-2]"+            menu `shouldContain` "Please enter a number from 1 to 2."+        forM_ ["\n", "\4"] $ \answer -> do+          (code, output, menu) <- menuInvoke ctx [] answer+          code `shouldNotBe` ExitSuccess+          output `shouldBe` ""+          menu `shouldContain` "session selection cancelled"++  it "enters a running workcell without sudo and preserves its environment and filesystem" $ \ctx -> do+    helper <- findExecutable "nsenter"+    when (isNothing helper) $ pendingWith "nsenter unavailable"+    withRunningSession ctx ["-e", "ENTRY_VALUE=hello world"] $ \ident -> do+      preview <- successful =<< sessionInvoke ctx ["enter", ident, "--dryrun"]+      preview `shouldContain` "nsenter"+      preview `shouldContain` "--mount="+      out <- successful =<< sessionInvoke ctx ["enter", ident, "--", "/bin/sh", "-c",+        "printf '%s\\n' \"$WORKCELL_ACTIVE\" \"$ENTRY_VALUE\" \"$PWD\" \"$1\"; test -f entry-home-marker; test -f \"$HOME/entry-home-marker\"", "check", "literal argument"]+      lines out `shouldBe` ["1", "hello world", project ctx, "literal argument"]+      (code, _, _) <- sessionInvoke ctx ["enter", ident, "--", "/bin/sh", "-c", "exit 23"]+      code `shouldBe` ExitFailure 23++  it "enters as the original user or namespace root in both process modes" $ \ctx -> do+    uid <- getEffectiveUserID+    gid <- getEffectiveGroupID+    forM_ [[], ["--share-processes"]] $ \flags ->+      withRunningSession ctx flags $ \ident -> do+        paths <- sessionRecordPaths ctx+        path <- case paths of+          [found] -> pure found+          _ -> fail "expected one session record"+        record <- BS.readFile path >>= either fail pure . eitherDecodeStrict'+        pid <- case record of+          Object object | Just (Number number) <- KM.lookup "sessionPID" object -> pure (round number :: Int)+          _ -> fail "session record has no PID"+        namespace <- readSymbolicLink $ "/proc/" ++ show pid ++ "/ns/user"+        out <- successful =<< sessionInvoke ctx ["enter", ident, "--", "/bin/sh", "-c",+          "id -u; id -g; readlink /proc/self/ns/user"]+        lines out `shouldBe` [show uid, show gid, namespace]+        rooted <- successful =<< sessionInvoke ctx ["enter", ident, "--root", "--", "/bin/sh", "-c",+          "id -u; id -g; touch root-owned-marker; echo \"$WORKCELL_ACTIVE\""]+        lines rooted `shouldBe` ["0", "0", "1"]+        getFileStatus (project ctx </> "root-owned-marker") >>= (`shouldBe` uid) . fileOwner+        preview <- successful =<< sessionInvoke ctx ["enter", ident, "--root", "--dryrun"]+        preview `shouldContain` "nsenter"++  it "enters with a usable terminal and preserves input, arguments, and exit status" $ \ctx -> do+    uid <- getEffectiveUserID+    gid <- getEffectiveGroupID+    helpers <- mapM findExecutable ["systemd-pty-forward", "script"]+    when (all isNothing helpers) $ pendingWith "no terminal relay helper available"+    withRunningSession ctx [] $ \ident -> do+      environment <- sessionEnvironment ctx+      let open = do+            (master, slave) <- openPseudoTerminal+            (,) <$> Posix.fdToHandle master <*> Posix.fdToHandle slave+          close (master, slave) = hClose master >> hClose slave+      forM_ [([], show uid, show gid), (["--root"], "0", "0")] $ \(flags, expectedUID, expectedGID) ->+        bracket open close $ \(master, slave) -> do+          let invocation = (proc (binary ctx)+                (["enter", ident] ++ flags ++ ["--", "/bin/sh", "-c", unlines+                 ["set -eu", "test -t 0 && test -t 1 && test -t 2",+                  "device=$(tty); test -c \"$device\"",+                  "stty -F /dev/tty -a >/dev/null", "stty -echo", "printf 'ready\\n'",+                  "IFS= read -r answer", "test \"$answer\" = 'terminal input'",+                  "test \"$1\" = \"literal ' argument\"",+                  "test \"$(id -u)\" = \"$2\"; test \"$(id -g)\" = \"$3\"", "exit 23"],+                 "check", "literal ' argument", expectedUID, expectedGID]))+                {env = Just environment, std_in = UseHandle slave,+                 std_out = UseHandle slave, std_err = UseHandle slave}+          result <- timeout (5 * 1000000) $+            bracket (createProcess invocation)+              (\(_, _, _, handle) -> terminateProcess handle >> waitForProcess handle >> pure ()) $+              \(_, _, _, handle) -> do+                ready <- hGetLine master+                ready `shouldBe` "ready\r"+                hPutStrLn master "terminal input"+                hFlush master+                waitForProcess handle+          result `shouldBe` Just (ExitFailure 23)++  it "ignores stale, mismatched, malformed and publicly readable session records" $ \ctx -> do+    withRunningSession ctx [] $ \ident -> do+      paths <- sessionRecordPaths ctx+      path <- case paths of+        [found] -> pure found+        _ -> fail "expected one session record"+      getFileStatus path >>= (\mode -> mode .&. 0o777 `shouldBe` 0o600) . fileMode+      bytes <- BS.readFile path+      value <- either fail pure $ eitherDecodeStrict' bytes+      forM_ [("sessionStart", "invalid"), ("sessionBoot", "invalid"),+             ("sessionMountNamespace", "mnt:[0]"), ("sessionPIDNamespace", "pid:[0]")] $ \(key, text) -> do+        case value of+          Object object -> BL.writeFile path $ encode $ Object $ KM.insert key (String text) object+          _ -> expectationFailure "invalid session record"+        sessionInvoke ctx ["list"] >>= successful >>= (`shouldBe` "")+        (code, _, _) <- sessionInvoke ctx ["enter", ident]+        code `shouldNotBe` ExitSuccess+      BS.writeFile path bytes+      setFileMode path 0o644+      sessionInvoke ctx ["list"] >>= successful >>= (`shouldBe` "")+      setFileMode path 0o600+      writeFile path "invalid JSON"+      sessionInvoke ctx ["list"] >>= successful >>= (`shouldBe` "")++  it "scopes discovery to the caller's PID namespace" $ \ctx -> do+    withRunningSession ctx [] $ \_ -> do+      paths <- sessionRecordPaths ctx+      let other = root ctx </> "session-runtime/workcell/sessions/other-namespace"+      createDirectory other+      case paths of+        [path] -> copyFile path (other </> "s999")+        _ -> fail "expected one session record"+      output <- successful =<< sessionInvoke ctx ["list"]+      length (lines output) `shouldBe` 2+      output `shouldNotContain` "s999"++  it "ignores and removes records left by an uncatchable supervisor stop" $ \ctx -> do+    withRunningSessionHandle ctx [] $ \ident handle -> do+      pid <- getPid handle >>= maybe (fail "supervisor exited unexpectedly") pure+      signalProcess sigKILL pid+      _ <- waitForProcess handle+      sessionInvoke ctx ["list"] >>= successful >>= (`shouldBe` "")+      sessionRecordPaths ctx >>= (`shouldBe` [])+      (code, _, _) <- sessionInvoke ctx ["enter", ident]+      code `shouldNotBe` ExitSuccess++  it "removes records after normal exit and creates none for failed setup or dry runs" $ \ctx -> do+    environment <- sessionEnvironment ctx+    let flags = ["--share-processes" | not $ privateProc ctx]+        run args = capture $ (proc (binary ctx) (flags ++ args))+          {cwd = Just (project ctx), env = Just environment}+    _ <- successful =<< run ["--network-host", "--", "/bin/true"]+    sessionRecordPaths ctx >>= (`shouldBe` [])+    _ <- successful =<< run ["--network-host", "--dryrun"]+    sessionRecordPaths ctx >>= (`shouldBe` [])+    (code, _, _) <- run ["--network-host", "-v", "/missing-session-test"]+    code `shouldNotBe` ExitSuccess+    sessionRecordPaths ctx >>= (`shouldBe` [])++  it "uses state storage when the runtime directory is unset" $ \ctx -> do+    environment <- sessionEnvironment ctx+    let flags = ["--share-processes" | not $ privateProc ctx]+    _ <- successful =<< capture ((proc (binary ctx) (flags ++ ["--network-host", "--", "/bin/true"]))+      {cwd = Just (project ctx), env = Just $ filter ((/= "XDG_RUNTIME_DIR") . fst) environment})+    doesDirectoryExist (root ctx </> "session-state/workcell/sessions") >>= (`shouldBe` True)++  it "runs without session tracking when the state directory is unsafe" $ \ctx -> do+    let state = root ctx </> "session-state"+        records = state </> "workcell/sessions"+        target = root ctx </> "other directory"+    createDirectoryIfMissing True (takeDirectory records)+    createDirectory target+    createDirectoryLink target records+    environment <- filter ((/= "XDG_RUNTIME_DIR") . fst) <$> sessionEnvironment ctx+    (code, out, err) <- invoke ctx (Just True) (Just environment)+      ["--", "/bin/sh", "-c", "echo command-ran; exit 23"]+    unless (code == ExitFailure 23) $+      expectationFailure $ unlines+        ["expected ExitFailure 23, got " ++ show code, "Workcell executable " ++ binary ctx, err]+    out `shouldBe` "command-ran\n"+    err `shouldContain` "running without session tracking"+    err `shouldContain` ("unsafe session directory: " ++ records)+    err `shouldNotContain` "bwrap:"+    let listing = (proc (binary ctx) ["list"]) {env = Just environment}+    (listCode, _, listErr) <- capture listing+    listCode `shouldNotBe` ExitSuccess+    listErr `shouldContain` ("unsafe session directory: " ++ records)+    pathIsSymbolicLink records `shouldReturn` True+    listDirectory target `shouldReturn` []++  it "uses writable fixture storage when enclosing TMPDIR points into a read-only mount" $ \ctx -> do+    environment <- getEnvironment+    let temporary = root ctx </> "enclosing temporary directory"+        flags = ["--share-processes" | not $ privateProc ctx]+        args = ["--ro-bind", "/", "/", "--proc", "/proc",+                "--bind", project ctx, project ctx, "--", binary ctx] +++               flags ++ ["--network-host", "--", "/bin/true"]+    createDirectory temporary+    _ <- successful =<< capture ((fixtureProcess args)+      {cwd = Just (project ctx), env = Just $ setVariables [("TMPDIR", temporary)] environment})+    pure ()++  it "enters offline namespaces and respects shared process mode" $ \ctx -> do+    unless (privateNet ctx) $ pendingWith "network namespaces unavailable"+    withRunningSession ctx ["--network-none", "--share-processes"] $ \ident -> do+      preview <- successful =<< sessionInvoke ctx ["enter", ident, "--dryrun"]+      preview `shouldContain` "--net="+      preview `shouldNotContain` "--pid="+      out <- successful =<< sessionInvoke ctx ["enter", ident, "--", "/bin/sh", "-c",+        "readlink /proc/self/ns/net"]+      out `shouldContain` "net:["++  it "registers and enters the private-network supervisor with a real loopback pasta helper" $ \ctx -> do+    requireLoopbackPasta+    unless (privateProc ctx) $ pendingWith "private /proc unavailable"+    executable <- getExecutablePath+    environment <- sessionEnvironment ctx+    let waitListed = do+          output <- successful =<< sessionInvoke ctx ["list"]+          case drop 1 $ lines output of+            row:_ | ident:_ <- words row -> pure ident+            _ -> threadDelay 10000 >> waitListed+        args = ["--test-tracked-loopback-network", "--die-with-parent", "--ro-bind", "/", "/",+                "--dev", "/dev", "--unshare-net", "--unshare-pid", "--proc", "/proc",+                "--tmpfs", "/tmp", "--tmpfs", "/run", "--", "/bin/sleep", "30"]+    bracket (createProcess $ (proc executable args) {env = Just environment})+      (\(_, _, _, handle) -> terminateProcess handle >> waitForProcess handle >> pure ()) $ \_ -> do+        found <- timeout (5 * 1000000) waitListed+        ident <- maybe (fail "private session was not registered") pure found+        output <- successful =<< sessionInvoke ctx ["enter", ident, "--", "/bin/sh", "-c",+          "cat /tmp/workcell-test-resolv; readlink /proc/self/ns/net; readlink /proc/self/ns/pid"]+        output `shouldContain` "nameserver 169.254.1.1"+        outerNet <- readSymbolicLink "/proc/self/ns/net"+        outerPID <- readSymbolicLink "/proc/self/ns/pid"+        output `shouldNotContain` outerNet+        output `shouldNotContain` outerPID++  it "provides help, shell defaults, and distinct dry-run modes" $ \ctx -> do+    topHelp <- successful =<< sessionInvoke ctx ["--help"]+    forM_ ["list", "enter", "run", "--volume"] $ \name -> topHelp `shouldContain` name+    topHelp `shouldContain` "Available commands:"+    enterHelp <- successful =<< sessionInvoke ctx ["enter", "--help"]+    forM_ ["Usage: workcell enter", "--root", "--dryrun"] $ \entry -> enterHelp `shouldContain` entry+    runHelp <- successful =<< sessionInvoke ctx ["run", "--help"]+    forM_ ["Usage: workcell run", "--volume", "--dryrun"] $ \entry -> runHelp `shouldContain` entry+    forM_ [["list", "enter"], ["--root"], ["enter", "--volume", "/tmp"],+           ["list", "--dryrun"], ["list", "/bin/true"]] $ \args -> do+      (code, _, _) <- sessionInvoke ctx args+      code `shouldSatisfy` (/= ExitSuccess)+    forM_ [["--dryrun", "/bin/true"], ["--dryrun", "--", "/bin/true"],+           ["run", "--dryrun", "--", "/bin/true"]] $ \args -> do+      preview <- successful =<< sessionInvoke ctx args+      preview `shouldContain` "'--' '/bin/true'"+    out <- success ctx ["--dryrun"]+    out `shouldContain` "'--' '/bin/bash'"+    out `shouldContain` "'--unshare-pid'"+    out `shouldContain` "'--proc' '/proc'"+    out `shouldContain` "'--remount-ro' '/'"+    out `shouldNotContain` "'--ro-bind' '/' '/'"+    out `shouldContain` "'pasta' '--foreground' '--config-net' '--no-map-gw'"+    out `shouldContain` "'-t' 'none' '-u' 'none' '-T' 'none' '-U' 'none'"+    out `shouldContain` "'--ro-bind-data' '<dns-fd>'"+    offline <- success ctx ["--network-none", "--dryrun"]+    offline `shouldContain` "'--unshare-net'"+    offline `shouldNotContain` "'pasta'"+    host <- success ctx ["--network-host", "--dryrun"]+    host `shouldNotContain` "'--unshare-net'"+    host `shouldNotContain` "'pasta'"+    fallback <- success ctx ["--share-filesystem", "--dryrun"]+    fallback `shouldContain` "'--ro-bind' '/' '/'"+    shared <- successful =<< invoke ctx (Just True) Nothing ["--dryrun"]+    shared `shouldNotContain` "'--unshare-pid'"+    shared `shouldNotContain` "'--proc'"++  it "shares the enclosing network only in host mode" $ \ctx -> do+    expected <- readSymbolicLink "/proc/self/ns/net"+    forM_ [["--network-host"]] $ \flags -> do+      success ctx (flags ++ ["--", "readlink", "/proc/self/ns/net"])+        >>= (`shouldBe` expected ++ "\n")++  it "isolates offline networking independently of filesystem and process sharing" $ \ctx -> do+    unless (privateNet ctx) $ pendingWith "container blocks network namespaces"+    expected <- readSymbolicLink "/proc/self/ns/net"+    forM_ [[], ["--share-processes", "--share-filesystem"]] $ \flags -> do+      success ctx (flags ++ ["--network-none", "--", "readlink", "/proc/self/ns/net"])+        >>= (`shouldNotBe` expected ++ "\n")++  it "separates private networking while preserving identity, hostname, DNS, and exit status" $ \ctx -> do+    unless (pastaNet ctx) $ pendingWith "private pasta networking is unavailable here"+    expected <- readSymbolicLink "/proc/self/ns/net"+    forM_ [["--network-private"], []] $ \flags -> do+      out <- successful =<< invokeDefault ctx Nothing Nothing+        (flags ++ ["--", "readlink", "/proc/self/ns/net"])+      out `shouldNotBe` expected ++ "\n"+    forM_ [["id", "-u"], ["id", "-g"], ["hostname"]] $ \args -> do+      host <- success ctx $ ["--network-host", "--"] ++ args+      success ctx (["--network-private", "--"] ++ args) `shouldReturn` host+    success ctx ["--network-private", "--", "cat", "/etc/resolv.conf"]+      >>= (`shouldContain` "nameserver 169.254.1.1\n")+    (code, _, _) <- invoke ctx Nothing Nothing+      ["--network-private", "--", "/bin/sh", "-c", "exit 23"]+    code `shouldBe` ExitFailure 23++  it "blocks enclosing localhost services in offline and private modes" $ \ctx -> do+    unless (privateNet ctx) $ pendingWith "container blocks network namespaces"+    bracket (Net.socket Net.AF_INET Net.Stream Net.defaultProtocol) Net.close $ \listener -> do+      Net.bind listener $ Net.SockAddrInet 0 (Net.tupleToHostAddress (127, 0, 0, 1))+      Net.listen listener 4+      address <- Net.getSocketName listener+      port <- case address of+        Net.SockAddrInet value _ -> pure $ show value+        _ -> fail "unexpected listener address"+      let args mode = ["--network-" ++ mode, "--", "/bin/bash", "--noprofile", "--norc", "-c",+                       "touch command-ran; exec 3<>/dev/tcp/127.0.0.1/\"$1\"", "check", port]+      _ <- success ctx $ args "host"+      forM_ ("none" : ["private" | pastaNet ctx]) $ \mode -> do+        removeFile (project ctx </> "command-ran")+        (code, _, _) <- invoke ctx Nothing Nothing (args mode)+        code `shouldNotBe` ExitSuccess+        doesFileExist (project ctx </> "command-ran") `shouldReturn` True++  it "fails without side effects when private networking is unavailable" $ \ctx -> do+    when (pastaNet ctx) $ pendingWith "private pasta networking is supported"+    let supplied = root ctx </> "must not be created"+    (code, _, err) <- invoke ctx (Just True) Nothing+      ["--network-private", "-H", supplied, "--", "/bin/sh", "-c", "touch command-ran"]+    code `shouldNotBe` ExitSuccess+    err `shouldContain` "private networking is unavailable"+    err `shouldContain` "--network-host"+    doesPathExist supplied `shouldReturn` False+    doesPathExist (project ctx </> "command-ran") `shouldReturn` False++  it "requires pasta only for private networking" $ \ctx -> do+    let tools = root ctx </> "tools"+        supplied = root ctx </> "must not be created"+    createDirectory tools+    bwrap <- findExecutable "bwrap" >>= maybe (fail "bwrap disappeared") pure+    createFileLink bwrap (tools </> "bwrap")+    environment <- getEnvironment+    let envs = setVariables [("PATH", tools)] environment+    forM_ ["host", "none"] $ \mode -> do+      when (mode /= "none" || privateNet ctx) $ do+        _ <- successful =<< invoke ctx (Just True) (Just envs)+          ["--network-" ++ mode, "--", "/bin/true"]+        pure ()+    (code, _, err) <- invoke ctx (Just True) (Just envs)+      ["--network-private", "-H", supplied, "--", "/bin/true"]+    code `shouldNotBe` ExitSuccess+    err `shouldContain` "pasta is not installed or not on PATH"+    doesPathExist supplied `shouldReturn` False++  it "falls back to host networking by default before running the command once" $ \ctx -> do+    let tools = root ctx </> "tools without pasta"+        supplied = root ctx </> "auto home"+    createDirectory tools+    bwrap <- findExecutable "bwrap" >>= maybe (fail "bwrap disappeared") pure+    createFileLink bwrap (tools </> "bwrap")+    environment <- getEnvironment+    namespace <- readSymbolicLink "/proc/self/ns/net"+    let envs = setVariables [("PATH", tools)] environment+    (code, output, err) <- invokeDefault ctx Nothing (Just envs)+      ["-H", supplied, "--", "/bin/sh", "-c",+       "echo run >> command-count; readlink /proc/self/ns/net; exit 23"]+    code `shouldBe` ExitFailure 23+    output `shouldBe` namespace ++ "\n"+    err `shouldContain` "falling back to host networking"+    readFile (project ctx </> "command-count") `shouldReturn` "run\n"+    doesDirectoryExist supplied `shouldReturn` True+    (strictCode, _, strictErr) <- invokeDefault ctx Nothing (Just envs)+      ["--network-private", "--", "/bin/sh", "-c", "echo run >> command-count"]+    strictCode `shouldNotBe` ExitSuccess+    strictErr `shouldNotContain` "falling back"+    strictErr `shouldContain` "pasta is not installed or not on PATH"+    readFile (project ctx </> "command-count") `shouldReturn` "run\n"+    dry <- successful =<< invokeDefault ctx Nothing (Just envs)+      ["--dryrun", "-H", root ctx </> "dry home"]+    dry `shouldContain` "fall back to host if network setup fails"+    dry `shouldContain` "'pasta'"+    dry `shouldNotContain` "'--network-host'"+    doesPathExist (root ctx </> "dry home") `shouldReturn` False+    (invalidCode, _, invalidErr) <- invokeDefault ctx Nothing (Just envs)+      ["-v", root ctx </> "missing volume", "--", "/bin/true"]+    invalidCode `shouldNotBe` ExitSuccess+    invalidErr `shouldNotContain` "falling back"++  it "records host networking for sessions that fall back by default" $ \ctx -> do+    let tools = root ctx </> "tools without pasta"+    createDirectory tools+    bwrap <- findExecutable "bwrap" >>= maybe (fail "bwrap disappeared") pure+    createFileLink bwrap (tools </> "bwrap")+    environment <- sessionEnvironment ctx+    let args =+          ["--share-processes" | not (privateProc ctx)] +++          ["--", "/bin/sh", "-c", "touch auto-ready; exec /bin/sleep 30"]+        invocation = (proc (binary ctx) args)+          {cwd = Just (project ctx), env = Just $ setVariables [("PATH", tools)] environment,+           std_out = NoStream}+    bracket (createProcess invocation)+      (\(_, _, _, handle) -> terminateProcess handle >> waitForProcess handle >> pure ()) $ \_ -> do+        waitUntil $ doesFileExist (project ctx </> "auto-ready")+        listing <- successful =<< sessionInvoke ctx ["list"]+        length (lines listing) `shouldBe` 2+        listing `shouldContain` "host"+        listing `shouldNotContain` "private"+        preview <- successful =<< sessionInvoke ctx ["enter", "--dryrun"]+        preview `shouldNotContain` "--net="++  it "terminates private networking when its command is terminated" $ \ctx -> do+    unless (pastaNet ctx) $ pendingWith "private pasta networking is unavailable here"+    let flags = ["--share-processes" | not (privateProc ctx)]+        args = flags ++ ["--network-private", "--", "/bin/sh", "-c",+                         "touch network-ready; exec /bin/sleep 30"]+    bracket (createProcess ((proc (binary ctx) args) {cwd = Just (project ctx)}))+      (\(_, _, _, handle) -> terminateProcess handle >> waitForProcess handle >> pure ()) $+      \(_, _, _, handle) -> do+        pid <- getPid handle >>= maybe (fail "workcell exited unexpectedly") pure+        waitUntil (doesFileExist (project ctx </> "network-ready"))+        terminateProcess handle+        timeout (5 * 1000000) (waitForProcess handle)+          >>= (`shouldSatisfy` (/= Nothing))+        doesDirectoryExist ("/proc" </> show pid) `shouldReturn` False++  it "uses the real pasta launcher to restore identity, set DNS, and forward argv" $ \ctx -> do+    requireLoopbackPasta+    let value = "spaces ' dollar $ and backtick `"+    uid <- getEffectiveUserID+    gid <- getEffectiveGroupID+    namespace <- readSymbolicLink "/proc/self/ns/net"+    hostname <- takeWhile (/= '\n') <$> success ctx ["--", "hostname"]+    -- Exercise the actual helper/user-namespace/FD plumbing without a TUN+    -- device. Outbound connectivity is covered only by the TAP tests above.+    invocation <- loopbackCommand ctx ["/bin/sh", "-ec",+      unlines ["[ \"$(id -u)\" = \"$2\" ]", "[ \"$(id -g)\" = \"$3\" ]",+               "[ \"$(readlink /proc/self/ns/net)\" != \"$4\" ]", "[ \"$(hostname)\" = \"$5\" ]",+               "grep -qx 'nameserver 169.254.1.1' /tmp/workcell-test-resolv",+               "[ \"$(ls /proc/self/fd | wc -l)\" = 4 ]",+               "printf '%s' \"$1\"", "exit 23"],+      "check", value, show uid, show gid, namespace, hostname]+    (code, out, err) <- capture invocation+    unless (code == ExitFailure 23) $ expectationFailure $ show code ++ ": " ++ err+    out `shouldBe` value++  it "cleans up the real pasta launcher when terminated" $ \ctx -> do+    requireLoopbackPasta+    invocation <- loopbackCommand ctx ["/bin/sh", "-c", "touch network-ready; exec /bin/sleep 30"]+    bracket (createProcess invocation)+      (\(_, _, _, handle) -> terminateProcess handle >> waitForProcess handle >> pure ()) $+      \(_, _, _, handle) -> do+        pid <- getPid handle >>= maybe (fail "pasta exited unexpectedly") pure+        waitUntil (doesFileExist (project ctx </> "network-ready"))+        children <- words <$> readFile ("/proc" </> show pid </> "task" </> show pid </> "children")+        children `shouldSatisfy` (not . null)+        terminateProcess handle+        timeout (5 * 1000000) (waitForProcess handle)+          >>= (`shouldSatisfy` (/= Nothing))+        waitUntil $ and <$> mapM (fmap not . doesDirectoryExist . ("/proc" </>)) children++  it "keeps the requested command paused if the network helper fails" $ \ctx -> do+    let tools = root ctx </> "failing helper"+        helper = tools </> "pasta"+    createDirectory tools+    writeFile helper $ unlines $ ["#!/bin/sh", "echo earlier-diagnostic >&2"] +++      ["echo diagnostic-" ++ show n ++ " >&2" | n <- [1 :: Int .. 25]] ++ ["exit 42"]+    setFileMode helper 0o700+    environment <- getEnvironment+    invocation <- loopbackCommand ctx ["/bin/sh", "-c", "touch command-ran"]+    let envs = setVariables [("PATH", tools ++ ":/usr/bin:/bin"),+                            ("XDG_STATE_HOME", root ctx </> "state")] environment+    (code, _, err) <- capture (invocation {env = Just envs})+    code `shouldNotBe` ExitSuccess+    err `shouldContain` "pasta exited during network setup"+    err `shouldContain` "diagnostic-25"+    err `shouldNotContain` "earlier-diagnostic"+    logs <- pastaLogs ctx+    length logs `shouldBe` 1+    forM_ logs $ \path -> do+      err `shouldContain` path+      readFile path >>= (`shouldContain` "earlier-diagnostic")+      status <- getFileStatus path+      (fileMode status .&. 0o777) `shouldBe` 0o600+    doesPathExist (project ctx </> "command-ran") `shouldReturn` False++  it "keeps pasta readiness files out of a home-based TMPDIR" $ \ctx -> do+    unless (privateNet ctx) $ pendingWith "container blocks network namespaces"+    environment <- getEnvironment+    let temporary = root ctx </> "home temporary directory"+        runtime = root ctx </> "helper runtime"+        helper = unlines+          ["while [ \"$1\" != --pid ]; do shift; done",+           "printf '%s' \"$2\" > helper-pid-path", "echo $$ > \"$2\"",+           "exec /bin/sleep 30"]+    createDirectory temporary+    createDirectory runtime+    invocation <- fakeHelperCommand ctx helper ["/bin/true"]+    forM_ [Just runtime, Nothing] $ \selectedRuntime -> do+      let envs = setVariables+                 (("TMPDIR", temporary) :+                  [("XDG_RUNTIME_DIR", directory) | Just directory <- [selectedRuntime]]) $+                 filter ((/= "XDG_RUNTIME_DIR") . fst) (fromMaybe environment $ env invocation)+      _ <- successful =<< capture (invocation {env = Just envs})+      pidPath <- readFile (project ctx </> "helper-pid-path")+      pidPath `shouldSatisfy` ((fromMaybe "/tmp" selectedRuntime ++ "/workcell-session-") `isPrefixOf`)+      doesPathExist (takeDirectory pidPath) `shouldReturn` False++  it "drains large pasta diagnostics into the retained log before reporting failure" $ \ctx -> do+    unless (privateNet ctx) $ pendingWith "container blocks network namespaces"+    let helper = unlines+          ["echo first-diagnostic >&2", "n=0; while [ \"$n\" -lt 5000 ]; do",+           "echo 'diagnostic padding to exceed the pipe buffer size' >&2",+           "n=$((n + 1)); done", "echo final-diagnostic >&2", "exit 42"]+    invocation <- fakeHelperCommand ctx helper ["/bin/true"]+    (code, _, err) <- capture invocation+    code `shouldNotBe` ExitSuccess+    err `shouldContain` "final-diagnostic"+    err `shouldNotContain` "first-diagnostic"+    logs <- pastaLogs ctx+    length logs `shouldBe` 1+    forM_ logs $ \path -> do+      content <- readFile path+      content `shouldContain` "first-diagnostic"+      content `shouldContain` "final-diagnostic"+      length content `shouldSatisfy` (> 65536)++  it "logs helper warnings quietly and keeps distinct logs for concurrent runs" $ \ctx -> do+    unless (privateNet ctx) $ pendingWith "container blocks network namespaces"+    let helper = unlines+          ["echo helper-warning >&2", "while [ \"$1\" != --pid ]; do shift; done",+           "echo $$ > \"$2\"", "exec /bin/sleep 30"]+    invocation <- fakeHelperCommand ctx helper ["/bin/sh", "-c", "printf command-output; exit 23"]+    first <- newEmptyMVar+    second <- newEmptyMVar+    _ <- forkFinally (capture invocation) (putMVar first)+    _ <- forkFinally (capture invocation) (putMVar second)+    forM_ [first, second] $ \result -> do+      (code, out, err) <- takeMVar result >>= either throwIO pure+      code `shouldBe` ExitFailure 23+      out `shouldBe` "command-output"+      err `shouldBe` ""+    logs <- pastaLogs ctx+    length logs `shouldBe` 2+    forM_ logs $ \path -> readFile path `shouldReturn` "helper-warning\n"++  it "removes empty pasta logs after command exit and supervisor termination" $ \ctx -> do+    unless (privateNet ctx) $ pendingWith "container blocks network namespaces"+    let helper = unlines+          ["while [ \"$1\" != --pid ]; do shift; done", "echo $$ > \"$2\"",+           "exec /bin/sleep 30"]+    invocation <- fakeHelperCommand ctx helper+      ["/bin/sh", "-c", "touch command-ran; exit \"$EXIT_CODE\""]+    environment <- getEnvironment+    forM_ [0, 23 :: Int] $ \status -> do+      let envs = setVariables [("EXIT_CODE", show status)] $ fromMaybe environment (env invocation)+      (code, _, err) <- capture (invocation {env = Just envs})+      code `shouldBe` (if status == 0 then ExitSuccess else ExitFailure status)+      err `shouldBe` ""+      pastaLogs ctx `shouldReturn` []+    waiting <- loopbackCommand ctx+      ["/bin/sh", "-c", "touch network-ready; exec /bin/sleep 30"]+    bracket (createProcess (waiting {env = env invocation}))+      (\(_, _, _, handle) -> terminateProcess handle >> waitForProcess handle >> pure ()) $+      \(_, _, _, handle) -> do+        waitUntil (doesFileExist $ project ctx </> "network-ready")+        logs <- pastaLogs ctx+        length logs `shouldBe` 1+        terminateProcess handle+        _ <- waitForProcess handle+        pastaLogs ctx `shouldReturn` []++  it "removes empty pasta logs on setup failure without reporting a missing log" $ \ctx -> do+    unless (privateNet ctx) $ pendingWith "container blocks network namespaces"+    invocation <- fakeHelperCommand ctx "exit 42" ["/bin/true"]+    (code, _, err) <- capture invocation+    code `shouldNotBe` ExitSuccess+    err `shouldContain` "pasta exited during network setup"+    err `shouldNotContain` "Pasta log:"+    pastaLogs ctx `shouldReturn` []++  it "reports retained diagnostics when the helper exits during a command" $ \ctx -> do+    unless (privateNet ctx) $ pendingWith "container blocks network namespaces"+    let helper = unlines+          ["while [ \"$1\" != --pid ]; do shift; done", "echo $$ > \"$2\"",+           "while [ ! -f command-ran ]; do /bin/sleep 0.01; done",+           "echo runtime-failure >&2", "exit 42"]+    invocation <- fakeHelperCommand ctx helper+      ["/bin/sh", "-c", "touch command-ran; exec /bin/sleep 30"]+    (code, _, err) <- capture invocation+    code `shouldNotBe` ExitSuccess+    err `shouldContain` "pasta exited while the command was running"+    err `shouldContain` "runtime-failure"+    logs <- pastaLogs ctx+    length logs `shouldBe` 1+    forM_ logs $ \path -> err `shouldContain` path++  it "uses enclosing HOME for logs when XDG_STATE_HOME is relative" $ \ctx -> do+    unless (privateNet ctx) $ pendingWith "container blocks network namespaces"+    invocation <- fakeHelperCommand ctx "echo fallback-diagnostic >&2\nexit 42" ["/bin/true"]+    environment <- getEnvironment+    let envs = setVariables [("HOME", root ctx), ("XDG_STATE_HOME", "relative-state")]+          (fromMaybe environment $ env invocation)+    (_, _, err) <- capture (invocation {env = Just envs})+    let directory = root ctx </> ".local/state/workcell/logs"+    err `shouldContain` directory+    entries <- listDirectory directory+    length entries `shouldBe` 1++  it "fails clearly before starting a command when the log cannot be opened" $ \ctx -> do+    let blocked = root ctx </> "blocked state"+    writeFile blocked "not a directory"+    invocation <- loopbackCommand ctx ["/bin/sh", "-c", "touch command-ran"]+    environment <- getEnvironment+    let envs = setVariables [("XDG_STATE_HOME", blocked)] environment+    (code, _, err) <- capture (invocation {env = Just envs})+    code `shouldNotBe` ExitSuccess+    err `shouldContain` "cannot open pasta log"+    doesPathExist (project ctx </> "command-ran") `shouldReturn` False++  it "creates no helper logs for dry runs, host networking, or offline networking" $ \ctx -> do+    environment <- getEnvironment+    let envs = setVariables [("XDG_STATE_HOME", root ctx </> "state")] environment+    _ <- successful =<< invoke ctx Nothing (Just envs) ["--dryrun"]+    _ <- successful =<< invoke ctx Nothing (Just envs) ["--network-host", "--", "/bin/true"]+    when (privateNet ctx) $ do+      _ <- successful =<< invoke ctx Nothing (Just envs) ["--network-none", "--", "/bin/true"]+      pure ()+    doesPathExist (root ctx </> "state/workcell/logs") `shouldReturn` False++  it "keeps only nonempty logs and reports failed private setup diagnostics" $ \ctx -> do+    unless (pastaNet ctx) $ pendingWith "private pasta networking is unavailable here"+    environment <- getEnvironment+    let stateEnv = setVariables [("XDG_STATE_HOME", root ctx </> "state")] environment+    _ <- successful =<< invoke ctx Nothing (Just stateEnv) ["--network-private", "--", "/bin/true"]+    retained <- pastaLogs ctx+    forM_ retained $ getFileSize >=> (`shouldSatisfy` (> 0))+    invocation <- fakeHelperCommand ctx "echo setup-failure >&2\nexit 42" ["/bin/true"]+    (code, _, err) <- invoke ctx Nothing (env invocation)+      ["--network-private", "-H", root ctx </> "uncreated home", "--", "/bin/true"]+    code `shouldNotBe` ExitSuccess+    err `shouldContain` "setup-failure"+    err `shouldContain` "Pasta log:"+    pastaLogs ctx >>= (\logs -> length logs `shouldBe` length retained + 1)+    created <- doesPathExist (root ctx </> "uncreated home")+    when created $ expectationFailure $ "persistent home was not removed after: " ++ err++  it "removes a newly created persistent home when private setup fails" $ \ctx -> do+    unless (privateNet ctx) $ pendingWith "container blocks network namespaces"+    let tools = root ctx </> "failing tools"+        supplied = root ctx </> "new home"+        keptHome = root ctx </> "existing home"+    createDirectory tools+    createDirectory keptHome+    writeFile (tools </> "pasta") "#!/bin/sh\necho setup-failure >&2\nexit 42\n"+    setFileMode (tools </> "pasta") 0o700+    -- A placeholder TUN device lets the failing helper be reached without one.+    -- The project lies beneath HOME, so bubblewrap creates its mountpoint+    -- inside the new home before network setup fails.+    forM_ [(supplied, False), (keptHome, True)] $ \(path, kept) -> do+      let args = ["--ro-bind", "/", "/", "--dev", "/dev", "--dev-bind", "/dev/null", "/dev/net/tun",+                  "--proc", "/proc", "--bind", root ctx, root ctx,+                  "--setenv", "PATH", tools ++ ":/usr/bin:/bin",+                  "--setenv", "XDG_STATE_HOME", root ctx </> "state", "--", binary ctx] +++                 ["--share-processes" | not (privateProc ctx)] +++                 ["--network-private", "-H", path, "--", "/bin/true"]+      (code, _, err) <- capture ((fixtureProcess args) {cwd = Just (project ctx)})+      code `shouldNotBe` ExitSuccess+      err `shouldContain` "pasta exited during network setup"+      doesPathExist path `shouldReturn` kept++  it "can explicitly share the enclosing PID namespace" $ \ctx -> do+    expected <- readSymbolicLink "/proc/self/ns/pid"+    out <- successful =<< invoke ctx (Just True) Nothing ["--", "readlink", "/proc/self/ns/pid"]+    out `shouldBe` expected ++ "\n"++  it "isolates processes when private proc is available" $ \ctx -> do+    unless (privateProc ctx) $ pendingWith "container blocks private /proc"+    expected <- readSymbolicLink "/proc/self/ns/pid"+    out <- successful =<< invoke ctx (Just False) Nothing ["--", "readlink", "/proc/self/ns/pid"]+    out `shouldNotBe` expected ++ "\n"+    bracket (createProcess $ proc "/bin/sleep" ["30"])+      (\(_, _, _, handle) -> terminateProcess handle >> waitForProcess handle >> pure ()) $+      \(_, _, _, handle) -> do+        pid <- getPid handle >>= maybe (fail "sleep exited unexpectedly") pure+        shell ctx "[ ! -d \"/proc/$1\" ]" [show pid]++  it "isolates processes as UID 0 without CAP_SYS_ADMIN" $ \ctx -> do+    unshare <- findExecutable "unshare" >>= maybe (pendingWith "unshare unavailable" >> fail "unreachable") pure+    setpriv <- findExecutable "setpriv" >>= maybe (pendingWith "setpriv unavailable" >> fail "unreachable") pure+    bwrap <- findExecutable "bwrap" >>= maybe (fail "bwrap disappeared") pure+    environment <- sessionEnvironment ctx+    let run program args = capture $+          (proc unshare (["--user", "--map-root-user", "--", setpriv,+                          "--bounding-set=-sys_admin", program] ++ args))+          {cwd = Just (project ctx), env = Just environment}+    (code, _, err) <- run bwrap+      ["--unshare-user", "--die-with-parent", "--ro-bind", "/", "/", "--dev", "/dev",+       "--unshare-pid", "--proc", "/proc", "--", "/bin/true"]+    unless (code == ExitSuccess) $ pendingWith $ "nested Bubblewrap fixture unavailable: " ++ err+    dry <- successful =<< run (binary ctx) ["--network-host", "--dryrun"]+    dry `shouldContain` "'--unshare-user'"+    expected <- readSymbolicLink "/proc/self/ns/pid"+    out <- successful =<< run (binary ctx) ["--network-host", "--", "/bin/sh", "-c",+      "id -u; readlink /proc/self/ns/pid"]+    case lines out of+      ["0", namespace] -> do+        namespace `shouldSatisfy` ("pid:[" `isPrefixOf`)+        namespace `shouldNotBe` expected+      _ -> expectationFailure $ "expected UID 0 and a PID namespace, got " ++ show out++  it "reports a blocked base sandbox before suggesting namespace sharing" $ \ctx -> do+    let tools = root ctx </> "tools"+        bwrap = tools </> "bwrap"+        supplied = root ctx </> "must not be created"+        baseError = "bwrap: Creating new namespace failed: Operation not permitted"+    createDirectory tools+    writeFile bwrap $ unlines+      ["#!/bin/sh", "case \" $* \" in",+       "  *' --unshare-pid '*) echo 'private PID probe failed' >&2 ;;",+       "  *) echo '" ++ baseError ++ "' >&2 ;;", "esac", "exit 1"]+    setFileMode bwrap 0o700+    environment <- getEnvironment+    let envs = setVariables [("PATH", tools)] environment+    (code, _, err) <- invokeDefault ctx (Just False) (Just envs)+      ["-H", supplied, "--", "/bin/sh", "-c", "touch command-ran"]+    code `shouldNotBe` ExitSuccess+    err `shouldContain` "bubblewrap could not initialize the filesystem sandbox"+    err `shouldContain` baseError+    err `shouldNotContain` "--share-processes"+    err `shouldNotContain` "falling back"+    doesPathExist supplied `shouldReturn` False+    doesPathExist (project ctx </> "command-ran") `shouldReturn` False++  it "fails without side effects when private proc is unavailable" $ \ctx -> do+    when (privateProc ctx) $ pendingWith "private /proc is supported"+    let supplied = root ctx </> "must not be created"+    (code, _, err) <- invoke ctx (Just False) Nothing+      ["-H", supplied, "--", "/bin/sh", "-c", "touch command-ran"]+    code `shouldNotBe` ExitSuccess+    err `shouldContain` "private PID namespace and /proc are unavailable"+    err `shouldContain` "--share-processes"+    doesPathExist supplied `shouldReturn` False+    doesPathExist (project ctx </> "command-ran") `shouldReturn` False++  it "preserves project writes but hides home and discards temporary files" $ \ctx -> do+    let marker = root ctx </> "host-only"+    createDirectory marker+    shell ctx (unlines+      [ "[ \"$PWD\" = \"$1\" ]", "[ \"$HOME\" = \"$2\" ]", "[ ! -e \"$3\" ]"+      , "printf persistent > project-write", "printf temporary > \"$HOME/home-write\""+      , "printf temporary > /tmp/workcell-temp-write"+      , "findmnt -n -o OPTIONS -T /usr | tr ',' '\\n' | grep -qx ro"+      ]) [project ctx, home ctx, marker]+    readFile (project ctx </> "project-write") `shouldReturn` "persistent"+    shell ctx "[ ! -e \"$HOME/home-write\" ] && [ ! -e /tmp/workcell-temp-write ]" []++  it "resolves explicit project symlinks" $ \ctx -> do+    let other = root ctx </> "other project"+        link = project ctx </> "project-link"+    createDirectory other+    createDirectoryLink other link+    success ctx ["-p", link, "--", "/bin/pwd"] >>= (`shouldBe` other ++ "\n")++  it "supports persistent home and a safely quoted side-effect-free dry run" $ \ctx -> do+    let supplied = root ctx </> "new home" </> "nested"+        quoted = "spaces ' dollar $ and backtick `"+    out <- success ctx ["-H", supplied, "--dryrun", "--", "/usr/bin/printf", "%s", quoted]+    doesPathExist supplied `shouldReturn` False+    -- Let the shell parse the printed invocation; no shell expansion of argv is allowed.+    let flags = "--network-host" : ["--share-processes" | not (privateProc ctx)]+    runnable <- success ctx $ flags ++ ["--dryrun", "--", "/usr/bin/printf", "%s", quoted]+    out `shouldContain` "'--'"+    executed <- successful =<< capture ((proc "/bin/sh" ["-c", runnable]) {cwd = Just (project ctx)})+    executed `shouldBe` quoted+    shellHome ctx supplied "printf saved > \"$HOME/home-write\""+    readFile (supplied </> "home-write") `shouldReturn` "saved"+    shellHome ctx supplied "[ \"$(cat \"$HOME/home-write\")\" = saved ]"++  it "enforces read-only project access and supports explicit read/write access" $ \ctx -> do+    let link = root ctx </> "project link"+    createDirectoryLink (project ctx) link+    writeFile (project ctx </> "original") "original"+    forM_ [[], ["--share-filesystem"]] $ \flags -> do+      out <- success ctx $ flags ++ ["-p", link ++ ":ro", "--", "/bin/sh", "-ec", unlines+        [ "pwd", "[ \"$(cat original)\" = original ]"+        , "! (printf changed > original) 2>/dev/null"+        , "! rm original 2>/dev/null; ! touch new 2>/dev/null"+        , "printf writable > \"$HOME/home-write\""+        ]]+      out `shouldBe` project ctx ++ "\n"+    readFile (project ctx </> "original") `shouldReturn` "original"+    doesPathExist (project ctx </> "new") `shouldReturn` False+    void $ success ctx ["-p", link ++ ":rw", "--", "/bin/sh", "-ec",+                        "printf changed > original; touch new"]+    readFile (project ctx </> "original") `shouldReturn` "changed"+    doesPathExist (project ctx </> "new") `shouldReturn` True++  it "validates and previews project access modes before creating persistent home" $ \ctx -> do+    let supplied = root ctx </> "new home"+    forM_ [("ro", "--ro-bind"), ("rw", "--bind")] $ \(access, flag) -> do+      out <- success ctx ["--network-host", "-p", project ctx ++ ":" ++ access,+                          "-H", supplied, "--dryrun"]+      out `shouldContain` ("'" ++ flag ++ "' '" ++ project ctx ++ "' '" ++ project ctx ++ "'")+      void $ failure ctx ["-p", home ctx ++ ":" ++ access, "-H", supplied, "--dryrun"]+    forM_ [":ro", project ctx ++ ":invalid", project ctx ++ ":ro:rw"] $ \path -> do+      err <- failure ctx ["-p", path, "-H", supplied, "--dryrun"]+      err `shouldContain` "invalid project"+    doesPathExist supplied `shouldReturn` False++  it "enforces read-only file volumes and allows explicit writes" $ \ctx -> do+    let src = root ctx </> "extra file"+        dest = "/tmp/extra file"+    writeFile src "original"+    volumeShell ctx (src ++ ":" ++ dest)+      "[ \"$(cat \"$1\")\" = original ] && ! (printf changed > \"$1\")" [dest]+    readFile src `shouldReturn` "original"+    volumeShell ctx (src ++ ":" ++ dest ++ ":rw") "printf changed > \"$1\"" [dest]+    readFile src `shouldReturn` "changed"++  it "supports same-path directory volumes under home" $ \ctx -> do+    let src = root ctx </> "cache"+    createDirectory src+    writeFile (src </> "marker") "readable"+    volumeShell ctx src "[ \"$(cat \"$1/marker\")\" = readable ] && ! touch \"$1/new\"" [src]+    volumeShell ctx (src ++ ":rw") "printf writable > \"$1/new\"" [src]+    readFile (src </> "new") `shouldReturn` "writable"++  it "discards same-path and redirected directory overlay changes" $ \ctx -> do+    requireOverlay ctx+    let src = root ctx </> "overlay source"+    createDirectory src+    writeFile (src </> "original") "original"+    writeFile (src </> "deleted") "keep"+    forM_ [src, "/tmp/overlay destination"] $ \dest -> do+      let volume = src ++ (if dest == src then "" else ":" ++ dest) ++ ":O"+      volumeShell ctx volume (unlines+        [ "[ \"$(cat \"$1/original\")\" = original ]"+        , "[ -f \"$1/deleted\" ] && [ ! -e \"$1/new\" ]"+        , "printf changed > \"$1/original\""+        , "rm \"$1/deleted\"; printf created > \"$1/new\""+        , "[ \"$(cat \"$1/original\")\" = changed ]"+        , "[ ! -e \"$1/deleted\" ] && [ -f \"$1/new\" ]"+        ]) [dest]+      readFile (src </> "original") `shouldReturn` "original"+      readFile (src </> "deleted") `shouldReturn` "keep"+      doesPathExist (src </> "new") `shouldReturn` False+      volumeShell ctx volume+        "[ \"$(cat \"$1/original\")\" = original ] && [ -f \"$1/deleted\" ] && [ ! -e \"$1/new\" ]" [dest]++  it "starts in a canonical project overlay and discards edits between sessions" $ \ctx -> do+    requireOverlay ctx+    let link = root ctx </> "project link"+    createDirectoryLink (project ctx) link+    writeFile (project ctx </> "original") "original"+    writeFile (project ctx </> "deleted") "keep"+    let args = ["-p", link ++ ":O", "--", "/bin/sh", "-ec"]+    out <- success ctx $ args ++ [unlines+      [ "pwd", "[ \"$(cat original)\" = original ]"+      , "printf changed > original; rm deleted; touch new"+      , "[ \"$(cat original)\" = changed ] && [ ! -e deleted ] && [ -f new ]"+      ]]+    out `shouldBe` project ctx ++ "\n"+    readFile (project ctx </> "original") `shouldReturn` "original"+    readFile (project ctx </> "deleted") `shouldReturn` "keep"+    doesPathExist (project ctx </> "new") `shouldReturn` False+    void $ success ctx $ args +++      ["[ \"$(cat original)\" = original ] && [ -f deleted ] && [ ! -e new ]"]++  it "previews overlays without creating destinations or persistent home" $ \ctx -> do+    let src = root ctx </> "overlay source"+        dest = "/tmp/workcell overlay preview"+        supplied = root ctx </> "new home"+    createDirectory src+    out <- success ctx ["--network-host", "--dryrun", "-p", project ctx ++ ":O",+                        "-v", src ++ ":" ++ dest ++ ":O", "-H", supplied,+                        "--", "/bin/true"]+    out `shouldContain` "'--overlay-src'"+    out `shouldContain` ("'" ++ src ++ "' '--tmp-overlay' '" ++ dest ++ "'")+    out `shouldContain` ("'" ++ project ctx ++ "' '--tmp-overlay' '" ++ project ctx ++ "'")+    doesPathExist supplied `shouldReturn` False+    doesPathExist dest `shouldReturn` False++  it "rejects file overlays and conflicting overlay destinations before creating home" $ \ctx -> do+    let src = root ctx </> "overlay file"+        supplied = root ctx </> "new home"+    writeFile src "original"+    forM_ [src ++ ":O", src ++ ":/tmp/overlay:O"] $ \volume -> do+      err <- failure ctx ["-v", volume, "-H", supplied, "--dryrun"]+      err `shouldContain` "overlay source must be a directory"+    forM_ [["-p", src ++ ":O"], ["-p", home ctx ++ ":O"],+           ["-v", project ctx ++ ":O"],+           ["-v", root ctx ++ ":" ++ home ctx ++ ":O"],+           ["-v", root ctx ++ ":/tmp/duplicate:O", "-v", root ctx ++ ":/tmp/duplicate:ro"]] $ \args ->+      void $ failure ctx $ args ++ ["-H", supplied, "--dryrun"]+    (_, _, err) <- invoke ctx (Just False) Nothing+      ["-v", root ctx ++ ":/proc:O", "--dryrun"]+    err `shouldContain` "volume destination must not overlap private /proc"+    doesPathExist supplied `shouldReturn` False++  it "clears other environment variables and applies explicit overrides" $ \ctx -> do+    environment <- getEnvironment+    let supplied = setVariables [("WORKCELL_TEST_SECRET", "hidden"), ("WORKCELL_TEST_PASS", "passed"),+                                 ("WORKCELL_ACTIVE", "outside")] environment+    _ <- successful =<< invoke ctx Nothing (Just supplied)+      ["-e", "WORKCELL_TEST_PASS", "-e", "WORKCELL_TEST_VALUE=first", "-e", "WORKCELL_TEST_VALUE=last=part",+       "-e", "WORKCELL_TEST_EMPTY=", "--", "/bin/sh", "-c", unlines+       ["set -eu", "[ \"$WORKCELL_ACTIVE\" = 1 ]",+        "[ -z \"${WORKCELL_TEST_SECRET+x}\" ]", "[ \"$WORKCELL_TEST_PASS\" = passed ]",+        "[ \"$WORKCELL_TEST_VALUE\" = last=part ]", "[ \"${WORKCELL_TEST_EMPTY+x}\" = x ]",+        "[ -z \"$WORKCELL_TEST_EMPTY\" ]"]]+    pure ()++  it "exposes only the Wayland socket and permits explicit environment overrides" $ \ctx -> do+    environment <- getEnvironment+    let runtime = root ctx </> "wayland-runtime"+        socket = runtime </> "wayland-0"+        supplied display =+          setVariables+          (("XDG_RUNTIME_DIR", runtime) :+           [("WAYLAND_DISPLAY", value) | Just value <- [display]]) $+          filter ((/= "WAYLAND_DISPLAY") . fst) environment+    createDirectory runtime+    writeFile (runtime </> "private-marker") "hidden"+    bracket (Net.socket Net.AF_UNIX Net.Stream Net.defaultProtocol) Net.close $ \listener -> do+      Net.bind listener $ Net.SockAddrUnix socket+      forM_ [Nothing, Just "wayland-0", Just socket] $ \display -> do+        out <- successful =<< invoke ctx Nothing (Just $ supplied display)+          ["--wayland", "--", "/bin/sh", "-c",+           "test -S \"$1\" && test ! -e \"$XDG_RUNTIME_DIR/private-marker\" && printf '%s\\n' \"$XDG_RUNTIME_DIR\" \"$WAYLAND_DISPLAY\" \"$GDK_BACKEND\"",+           "check", socket]+        lines out `shouldBe` [runtime, fromMaybe "wayland-0" display, "wayland"]+      out <- successful =<< invoke ctx Nothing (Just $ supplied Nothing)+        ["--wayland", "-e", "GDK_BACKEND=x11", "--", "/bin/sh", "-c", "echo \"$GDK_BACKEND\""]+      out `shouldBe` "x11\n"++  it "rejects missing or invalid Wayland settings before launch" $ \ctx -> do+    environment <- filter (\(key, _) -> key `notElem` ["XDG_RUNTIME_DIR", "WAYLAND_DISPLAY"]) <$> getEnvironment+    let check settings message = do+          (code, _, err) <- invoke ctx Nothing (Just $ setVariables settings environment)+            ["--wayland", "--dryrun"]+          code `shouldNotBe` ExitSuccess+          err `shouldContain` message+    check [] "--wayland requires XDG_RUNTIME_DIR"+    check [("XDG_RUNTIME_DIR", "relative")] "absolute XDG_RUNTIME_DIR"+    check [("XDG_RUNTIME_DIR", root ctx), ("WAYLAND_DISPLAY", "")] "nonempty WAYLAND_DISPLAY"+    check [("XDG_RUNTIME_DIR", root ctx), ("WAYLAND_DISPLAY", root ctx)] "not a socket"+    check [("XDG_RUNTIME_DIR", root ctx)] "wayland-0"++  it "exposes the selected X11 socket and read-only authority with environment overrides" $ \ctx -> do+    environment <- getEnvironment+    let directory = root ctx </> "x11"+        authority = root ctx </> ".Xauthority"+        -- Exercise an inherited TMPDIR that becomes read-only in the fixture.+        supplied = setVariables [("HOME", root ctx), ("TMPDIR", root ctx)] $+          filter ((/= "XAUTHORITY") . fst) environment+        run envs args = capture $ (proc "bwrap" $+          ["--die-with-parent", "--ro-bind", "/", "/", "--dev", "/dev", "--tmpfs", "/tmp",+           "--bind", "/proc", "/proc",+           "--ro-bind", directory, "/tmp/.X11-unix",+           "--setenv", "TMPDIR", "/tmp",+           "--setenv", "XDG_RUNTIME_DIR", "/tmp/workcell-x11-runtime",+           "--", binary ctx, "--network-host"] +++          ["--share-processes" | not $ privateProc ctx] ++ args)+          {cwd = Just $ project ctx, env = Just envs}+    createDirectory directory+    writeFile authority "test-cookie"+    writeFile (directory </> "private-marker") "hidden"+    bracket (Net.socket Net.AF_UNIX Net.Stream Net.defaultProtocol) Net.close $ \listener -> do+      Net.bind listener $ Net.SockAddrUnix $ directory </> "X42"+      forM_ [":42", ":42.0", "unix:42", "unix/:42.1"] $ \display -> do+        out <- successful =<< run (setVariables [("DISPLAY", display)] supplied)+          ["--x11", "--", "/bin/sh", "-c", unlines+           ["set -eu", "test -S /tmp/.X11-unix/X42",+            "test ! -e /tmp/.X11-unix/private-marker",+            "test \"$(cat \"$XAUTHORITY\")\" = test-cookie",+            "! printf changed > \"$XAUTHORITY\"",+            "printf '%s\\n' \"$DISPLAY\" \"$XAUTHORITY\" \"$GDK_BACKEND\""]]+        lines out `shouldBe` [display, "/run/workcell-xauthority", "x11"]+      out <- successful =<< run+        (setVariables [("DISPLAY", ":42"), ("XAUTHORITY", authority)] supplied)+        ["--x11", "-e", "GDK_BACKEND=custom", "--", "/bin/sh", "-c", "echo \"$GDK_BACKEND\""]+      out `shouldBe` "custom\n"+      bracket (Net.socket Net.AF_UNIX Net.Stream Net.defaultProtocol) Net.close $ \wayland -> do+        Net.bind wayland $ Net.SockAddrUnix $ directory </> "wayland-0"+        let bothEnv = setVariables [("DISPLAY", ":42"),+              ("WAYLAND_DISPLAY", "/tmp/.X11-unix/wayland-0")] supplied+        forM_ [(["--wayland", "--x11"], "wayland,x11"),+               (["--x11", "--wayland"], "wayland,x11"),+               (["--wayland", "--x11", "-e", "GDK_BACKEND=x11,wayland"], "x11,wayland")] $ \(flags, backend) -> do+          combined <- successful =<< run bothEnv (flags +++            ["--", "/bin/sh", "-c", unlines+             ["set -eu", "test -S /tmp/.X11-unix/X42", "test -S \"$WAYLAND_DISPLAY\"",+              "test ! -e /tmp/.X11-unix/private-marker",+              "test \"$(cat \"$XAUTHORITY\")\" = test-cookie",+              "printf '%s\\n' \"$DISPLAY\" \"$WAYLAND_DISPLAY\" \"$GDK_BACKEND\""]])+          lines combined `shouldBe` [":42", "/tmp/.X11-unix/wayland-0", backend]+      (code, _, err) <- run+        (setVariables [("DISPLAY", ":42"), ("XAUTHORITY", directory)] supplied)+        ["--x11", "--dryrun"]+      code `shouldNotBe` ExitSuccess+      err `shouldContain` "X11 authority is not a regular file"+    readFile authority `shouldReturn` "test-cookie"++  it "rejects missing, remote, or malformed X11 settings before launch" $ \ctx -> do+    environment <- filter ((/= "DISPLAY") . fst) <$> getEnvironment+    let check settings args message = do+          (code, _, err) <- invoke ctx Nothing (Just $ setVariables settings environment)+            (["--x11", "--dryrun"] ++ args)+          code `shouldNotBe` ExitSuccess+          err `shouldContain` message+    check [] [] "--x11 requires DISPLAY"+    forM_ ["", "localhost:10.0", "host:0", ":", ":0.", ":0.bad", ":0.1.2", ":-1"] $ \display ->+      check [("DISPLAY", display)] [] "--x11 requires a local DISPLAY"++  it "exposes only the D-Bus session socket and accumulates desktop settings" $ \ctx -> do+    environment <- getEnvironment+    let directory = root ctx </> "bus-runtime"+        socket = directory </> "bus"+        encoded = concatMap (\c -> if c == ' ' then "%20" else [c]) socket+        address = "unix:path=" ++ encoded+        supplied value = setVariables [("DBUS_SESSION_BUS_ADDRESS", value),+          ("XDG_RUNTIME_DIR", directory), ("WAYLAND_DISPLAY", "bus")] environment+    createDirectory directory+    writeFile (directory </> "private-marker") "hidden"+    bracket (Net.socket Net.AF_UNIX Net.Stream Net.defaultProtocol) Net.close $ \listener -> do+      Net.bind listener $ Net.SockAddrUnix socket+      forM_ [address, address ++ ",guid=0123456789abcdef0123456789abcdef",+             "unix:guid=0123456789abcdef0123456789abcdef,path=" ++ encoded] $ \value -> do+        out <- successful =<< invoke ctx Nothing (Just $ supplied value)+          ["--dbus", "--", "/bin/sh", "-c", unlines+           ["set -eu", "test -S /run/workcell-session-bus",+            "test ! -e \"$1/private-marker\"", "echo \"$DBUS_SESSION_BUS_ADDRESS\""],+           "check", directory]+        out `shouldBe` "unix:path=/run/workcell-session-bus\n"+      out <- successful =<< invoke ctx Nothing (Just $ supplied address)+        ["--wayland", "--dbus", "--", "/bin/sh", "-c", unlines+         ["set -eu", "test -S /run/workcell-session-bus",+          "test -S \"$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY\"",+          "printf '%s\\n' \"$DBUS_SESSION_BUS_ADDRESS\" \"$GDK_BACKEND\""]]+      lines out `shouldBe` ["unix:path=/run/workcell-session-bus", "wayland"]+      overridden <- successful =<< invoke ctx Nothing (Just $ supplied address)+        ["--dbus", "-e", "DBUS_SESSION_BUS_ADDRESS=unix:path=/custom", "--", "/bin/sh", "-c",+         "echo \"$DBUS_SESSION_BUS_ADDRESS\""]+      overridden `shouldBe` "unix:path=/custom\n"++  it "rejects missing, unsupported, or malformed D-Bus session addresses" $ \ctx -> do+    environment <- filter ((/= "DBUS_SESSION_BUS_ADDRESS") . fst) <$> getEnvironment+    let check settings message = do+          (code, _, err) <- invoke ctx Nothing (Just $ setVariables settings environment)+            ["--dbus", "--dryrun"]+          code `shouldNotBe` ExitSuccess+          err `shouldContain` message+    check [] "--dbus requires DBUS_SESSION_BUS_ADDRESS"+    forM_ ["", "autolaunch:", "tcp:host=localhost,port=1234", "unix:abstract=bus",+           "unix:path=/tmp/bus;unix:path=/tmp/other", "unix:path=/tmp/a,path=/tmp/b",+           "unix:path=/tmp/bus,abstract=bus", "unix:path=/tmp/bus,invalid"] $ \value ->+      check [("DBUS_SESSION_BUS_ADDRESS", value)] "single unix:path="+    forM_ ["%", "%2", "%GG"] $ \escaped ->+      check [("DBUS_SESSION_BUS_ADDRESS", "unix:path=/tmp/" ++ escaped)] "invalid escape"+    check [("DBUS_SESSION_BUS_ADDRESS", "unix:path=/tmp/%00bus")] "NUL byte"+    check [("DBUS_SESSION_BUS_ADDRESS", "unix:path=relative")] "absolute Unix socket path"+    check [("DBUS_SESSION_BUS_ADDRESS", "unix:path=/tmp/unescaped space")] "unescaped character"+    check [("DBUS_SESSION_BUS_ADDRESS", "unix:path=/tmp")] "not a socket"++  it "passes environment values and arguments that look like separators" $ \ctx -> do+    out <- success ctx ["-e", "SEPARATOR=--", "--", "/bin/sh", "-c",+                        "printf '%s %s' \"$SEPARATOR\" \"$1\"", "check", "--"]+    out `shouldBe` "-- --"++  it "passes no supervisor descriptors to the command" $ \ctx -> do+    forM_ ("host" : ["none" | privateNet ctx]) $ \mode -> do+      out <- success ctx ["--network-" ++ mode, "--", "/bin/ls", "/proc/self/fd"]+      lines out `shouldBe` ["0", "1", "2", "3"]++  it "forwards arguments without interpreting options or shell syntax" $ \ctx -> do+    let args = ["run", "enter", "list", "list", "enter", "--root", "--home", "-p", "", "a b", "'", "$HOME", "`uname`", "line\nbreak"]+    success ctx (["--", "/usr/bin/printf", "%s\\0"] ++ args)+      >>= (`shouldBe` concatMap (++ "\0") args)++  it "preserves command exit status" $ \ctx -> do+    (code, _, _) <- invoke ctx Nothing Nothing ["--", "/bin/sh", "-c", "exit 23"]+    code `shouldBe` ExitFailure 23++  it "inherits locales, permits overrides, and leaves absent locales unset" $ \ctx -> do+    environment <- filter (not . localeVariable . fst) <$> getEnvironment+    let settings = [("LANG", "C.UTF-8"), ("LANGUAGE", "en:fr"), ("LC_CTYPE", "C.UTF-8"),+                    ("LC_ALL", "C.UTF-8"), ("LC_TIME", "C"), ("LC_TEST_SETTING", "preserved")]+        supplied = settings ++ environment+        run envs args = successful =<< invoke ctx Nothing (Just envs) args+    out <- run supplied ["--", "env"]+    forM_ settings $ \(key, value) -> lines out `shouldContain` [key ++ "=" ++ value]+    run supplied ["--", "locale", "charmap"] `shouldReturn` "UTF-8\n"+    run supplied ["-e", "LC_ALL=C", "--", "locale", "charmap"] >>= (`shouldNotBe` "UTF-8\n")+    absent <- run environment ["--", "env"]+    lines absent `shouldSatisfy` (not . any (localeVariable . takeWhile (/= '=')))++  it "rejects invalid options, paths, mounts, and environment names" $ \ctx -> do+    let missing = root ctx </> "missing"+        cases = [["--unknown"], ["-p", "/"], ["-p", missing], ["-v", missing],+          ["-v", root ctx ++ ":/tmp/extra:invalid"], ["-v", root ctx ++ ":/"], ["-v", project ctx],+          ["-v", root ctx ++ ":" ++ home ctx], ["-v", root ctx],+          ["-v", root ctx ++ ":/tmp/duplicate", "-v", root ctx ++ ":/tmp/duplicate"],+          ["-v", root ctx ++ ":/usr/workcell-nonexistent-destination"], ["-H", "/"],+          ["-e", "BAD-NAME=value"], ["-p", "/proc"], ["-v", "/etc:/proc"],+          ["-e", "WORKCELL_TEST_UNSET_82394"], ["--network-invalid"],+          ["--network-none", "--network-host"],+          ["--network-private", "--network-host"],+          ["--network-private", "--network-none"],+          ["--network-auto"], ["--network", "host"], ["--share-network"]]+    forM_ cases $ \args -> void (failure ctx (args ++ ["--dryrun"]))++  it "validates before creating persistent home" $ \ctx -> do+    let supplied = root ctx </> "must not be created"+    _ <- failure ctx ["-H", supplied, "-v", root ctx </> "missing", "--", "/bin/true"]+    doesPathExist supplied `shouldReturn` False++  it "rejects projects that cover the isolated home" $ \ctx -> do+    let supplied = root ctx </> "must not be created"+    forM_ [[], ["-H", supplied]] $ \homeArgs -> do+      err <- failure ctx $ ["-p", home ctx] ++ homeArgs ++ ["--dryrun"]+      err `shouldContain` "project must not cover HOME"+    doesPathExist supplied `shouldReturn` False++  it "omits implicit projects at home and its ancestors" $ \ctx -> do+    let supplied = root ctx </> "isolated home"+        flags = "--network-host" : ["--share-processes" | not (privateProc ctx)]+    createDirectory supplied+    writeFile (supplied </> "marker") "isolated"+    forM_ [home ctx, takeDirectory (home ctx), "/"] $ \directory -> do+      forM_ [[], ["-H", supplied]] $ \homeArgs -> do+        let script = "[ \"$PWD\" = \"$HOME\" ] && [ ! -e \"$1\" ]" +++              if null homeArgs then " && [ -z \"$(ls -A \"$HOME\")\" ]"+              else " && [ \"$(cat marker)\" = isolated ]"+            args = flags ++ homeArgs +++              ["--", "/bin/sh", "-ec", script, "check", root ctx]+        _ <- successful =<< capture ((proc (binary ctx) args) {cwd = Just directory})+        pure ()++  it "runs the installed GHC" $ \ctx -> do+    available <- findExecutable "ghc"+    when (isNothing available) $ pendingWith "GHC is not installed"+    success ctx ["--", "ghc", "--version"] >>= (`shouldContain` "Glorious Glasgow Haskell")++  it "preserves individual system configuration files including binary localtime" $ \ctx -> do+    forM_ ["/etc/resolv.conf", "/etc/hosts", "/etc/host.conf", "/etc/localtime"] $ \path -> do+      exists <- doesFileExist path+      when exists $ do+        let dest = project ctx </> "configuration-copy"+        shell ctx "cat \"$1\" > configuration-copy" [path]+        expected <- BS.readFile path+        BS.readFile dest `shouldReturn` expected++  it "preserves anonymous configuration mounts through nested workcells" $ \ctx -> do+    let sparseEtc = root ctx </> "sparse etc"+        fixture = root ctx </> "binary timezone"+        replacement = root ctx </> "replacement timezone"+        expected = BS.pack [0, 1, 127, 128, 255, 10]+        replaced = BS.pack [255, 128, 127, 1, 0]+        processFlags = ["--share-processes" | not (privateProc ctx)]+        script = "cat /etc/localtime > localtime-copy; " +++          "[ \"$1\" = '<system-file-0-fd>' ]; " +++          "! (printf changed > /etc/localtime); [ ! -e /run/host/etc/unrelated ]"+    createDirectory sparseEtc+    createFileLink "/run/host/etc/localtime" (sparseEtc </> "localtime")+    BS.writeFile fixture expected+    BS.writeFile replacement replaced+    forM_ ("host" : ["none" | privateNet ctx]) $ \mode ->+      forM_ [False, True] $ \override ->+      bracket (WorkcellUtil.openSimpleFd fixture Posix.ReadOnly) Posix.closeFd $ \fd -> do+        let outer = ["--ro-bind", "/", "/", "--proc", "/proc",+                     "--bind", project ctx, project ctx, "--ro-bind", sparseEtc, "/etc",+                     "--tmpfs", "/run", "--ro-bind-data", show fd, "/run/host/etc/localtime",+                     "--symlink", "/usr/bin/true", "/run/host/etc/unrelated", "--", binary ctx]+            volume = if override then ["-v", replacement ++ ":/etc/localtime"] else []+            inner = processFlags ++ ["--network-" ++ mode, "-v", binary ctx] ++ volume ++ ["--", binary ctx] +++              processFlags ++ ["--network-host", "--", "/bin/sh", "-ec", script,+                               "check", "<system-file-0-fd>"]+        _ <- successful =<< capture ((fixtureProcess (outer ++ inner))+                                      {cwd = Just (project ctx), close_fds = False})+        BS.readFile (project ctx </> "localtime-copy") `shouldReturn` (if override then replaced else expected)++  it "tracks resolver replacements through systemd and toolbox directory mounts" $ \ctx -> do+    let sparseEtc = root ctx </> "sparse etc"+        resolverDir = project ctx </> "resolver"+        overrideFile = project ctx </> "override"+        flags = ["--share-processes" | not (privateProc ctx)]+    createDirectory sparseEtc+    createDirectory resolverDir+    writeFile overrideFile "override\n"+    forM_ [False, True] $ \toolbox -> do+      let directory = if toolbox then "/run/host/run/systemd/resolve" else "/run/systemd/resolve"+          target = directory </> "stub-resolv.conf"+          link = if toolbox then "/run/host/etc/resolv.conf" else target+          outer = ["--ro-bind", "/", "/", "--proc", "/proc",+                   "--bind", project ctx, project ctx, "--ro-bind", sparseEtc, "/etc",+                   "--tmpfs", "/run", "--ro-bind", resolverDir, directory] +++                  (if toolbox then ["--symlink", target, link] else []) ++ ["--", binary ctx]+          run args = successful =<< capture ((fixtureProcess (outer ++ flags ++ args))+                                              {cwd = Just (project ctx)})+      createFileLink link (sparseEtc </> "resolv.conf")+      forM_ [False, True] $ \shared ->+        forM_ ("host" : ["none" | privateNet ctx]) $ \mode -> do+          writeFile (resolverDir </> "stub-resolv.conf") "initial\n"+          writeFile (resolverDir </> "replacement") "updated\n"+          out <- run $ ["--network-" ++ mode] ++ ["--share-filesystem" | shared] +++            ["--", "/bin/sh", "-ec", unlines+              ["cat /etc/resolv.conf",+               "mv resolver/replacement resolver/stub-resolv.conf",+               "cat /etc/resolv.conf",+               "! (printf changed > /etc/resolv.conf)",+               "[ ! -e /run/host/etc/unrelated ]"]]+          out `shouldBe` "initial\nupdated\n"+      run ["--network-host", "-v", overrideFile ++ ":/etc/resolv.conf:ro",+           "--", "cat", "/etc/resolv.conf"] `shouldReturn` "override\n"+      dry <- run ["--network-private", "--dryrun"]+      dry `shouldNotContain` ("'--ro-bind' '" ++ directory ++ "' '" ++ directory ++ "'")+      removeFile (sparseEtc </> "resolv.conf")++  it "starts when optional configuration files are absent or localtime is a dangling symlink" $ \ctx -> do+    let sparseEtc = root ctx </> "sparse etc"+        flags = "--network-host" : ["--share-processes" | not (privateProc ctx)]+        args = ["--ro-bind", "/", "/", "--proc", "/proc", "--ro-bind", sparseEtc, "/etc",+                "--", binary ctx] ++ flags +++               ["--", "/bin/sh", "-c", "[ ! -e /etc/localtime ] && printf started"]+        check = do+          out <- successful =<< capture ((fixtureProcess args) {cwd = Just (project ctx)})+          out `shouldBe` "started"+          dry <- successful =<<+                 capture+                 ((fixtureProcess+                   ["--ro-bind", "/", "/", "--proc", "/proc",+                    "--ro-bind", sparseEtc, "/etc",+                    "--", binary ctx, "--network-private", "--dryrun"])+                   {cwd = Just (project ctx)})+          dry `shouldContain` "'--ro-bind-data' '<dns-fd>' '/etc/resolv.conf'"+    createDirectory sparseEtc+    check+    createFileLink "/missing/timezone" (sparseEtc </> "localtime")+    check++  it "preserves localtime through hidden intermediate symlinks" $ \ctx -> do+    let sparseEtc = root ctx </> "sparse etc"+        flags = "--network-host" : ["--share-processes" | not (privateProc ctx)]+        outer = ["--ro-bind", "/", "/", "--proc", "/proc",+                 "--bind", project ctx, project ctx,+                 "--ro-bind", sparseEtc, "/etc", "--tmpfs", "/run",+                 "--dir", "/run/host/etc",+                 "--symlink", "/usr/bin/true", "/run/host/etc/localtime",+                 "--symlink", "/usr/bin/true", "/run/host/etc/unrelated",+                 "--", binary ctx]+    createDirectory sparseEtc+    createFileLink "/etc/timezone-link" (sparseEtc </> "localtime")+    createFileLink "../run/host/etc/localtime" (sparseEtc </> "timezone-link")+    expected <- BS.readFile "/usr/bin/true"+    forM_ [False, True] $ \shared -> do+      let args = outer ++ flags ++ ["--share-filesystem" | shared] +++            ["--", "/bin/sh", "-ec",+             "cat /etc/localtime > configuration-copy; [ ! -e /run/host/etc/unrelated ]"]+      _ <- successful =<< capture ((fixtureProcess args) {cwd = Just (project ctx)})+      BS.readFile (project ctx </> "configuration-copy") `shouldReturn` expected++  it "hides enclosing data and provides ephemeral writable var/tmp" $ \ctx -> do+    shell ctx (unlines ["[ ! -e /var/log ]", "[ ! -e /sys/class ]", "[ ! -e /run/host/etc/passwd ]",+      "[ -z \"$(ls -A /opt)\" ]", "[ -z \"$(ls -A /srv)\" ]", "! touch /root-write",+      "! touch /opt/root-write", "printf temporary > /var/tmp/workcell-test"]) []+    shell ctx "[ ! -e /var/tmp/workcell-test ]" []++  it "creates new volume destinations only inside the sandbox" $ \ctx -> do+    let src = root ctx </> "source"+        dest = "/opt/workcell tests/new directory"+    createDirectory src+    writeFile (src </> "marker") "visible"+    volumeShell ctx (src ++ ":" ++ dest)+      "[ \"$(cat \"$1/marker\")\" = visible ] && ! touch \"$1/new\"" [dest]+    volumeShell ctx (src ++ ":" ++ dest ++ ":rw") "printf saved > \"$1/new\"" [dest]+    readFile (src </> "new") `shouldReturn` "saved"+    doesPathExist dest `shouldReturn` False+    success ctx ["-v", (src </> "marker") ++ ":/srv/new/path/file", "--", "cat", "/srv/new/path/file"]+      >>= (`shouldBe` "visible")+    _ <- failure ctx ["-v", (src </> "marker") ++ ":/etc", "--dryrun"]+    pure ()++  it "restores enclosing visibility only with share-filesystem" $ \ctx -> do+    let fixture = root ctx </> "outside"+        flags = "--network-host" : ["--share-processes" | not (privateProc ctx)]+        outer = ["--ro-bind", "/", "/", "--proc", "/proc", "--tmpfs", "/opt",+                 "--ro-bind", fixture, "/opt/host-marker", "--", binary ctx]+    writeFile fixture "host data"+    forM_ [False, True] $ \shared -> do+      let args = outer ++ flags ++ ["--share-filesystem" | shared] +++            ["--", "/bin/sh", "-c", if shared then "[ -f /opt/host-marker ]" else "[ ! -e /opt/host-marker ]"]+      _ <- successful =<< capture ((fixtureProcess args) {cwd = Just (project ctx)})+      pure ()+    _ <- success ctx ["--share-filesystem", "--", "/bin/sh", "-c",+                      "[ ! -e \"$1\" ] && printf saved > shared-write", "check", fixture]+    readFile (project ctx </> "shared-write") `shouldReturn` "saved"++  it "preserves var/home on systems using that alias" $ \ctx -> do+    exists <- doesPathExist "/var/home"+    unless exists $ pendingWith "system does not use /var/home"+    symlink <- pathIsSymbolicLink "/var/home"+    resolved <- canonicalizePath "/var/home"+    unless (symlink && resolved == "/home") $ pendingWith "system does not alias /var/home to /home"+    shell ctx "[ \"$(readlink /var/home)\" = ../home ]" []++  it "runs Git in the writable project" $ \ctx -> do+    _ <- success ctx ["--", "git", "init", "--quiet"]+    _ <- success ctx ["--", "git", "status", "--short"]+    pure ()++shellHome :: Context -> FilePath -> String -> IO ()+shellHome ctx supplied script =+  void $+  success ctx+  ["-H", supplied, "--", "/bin/sh", "-c", "set -eu\n" ++ script]++-- Probe bubblewrap directly so a workcell regression cannot skip overlay tests.+requireOverlay :: Context -> IO ()+requireOverlay ctx = do+  (code, _, err) <- capture $ proc "bwrap"+    ["--die-with-parent", "--ro-bind", "/", "/",+     "--overlay-src", project ctx, "--tmp-overlay", project ctx,+     "--", "/bin/true"]+  unless (code == ExitSuccess) $ pendingWith $ "bubblewrap overlays unavailable: " ++ err++volumeShell :: Context -> String -> String -> [String] -> IO ()+volumeShell ctx volume script args =+  void $+  success ctx+  (["-v", volume, "--", "/bin/sh", "-c", "set -eu\n" ++ script, "check"] ++ args)++localeVariable :: String -> Bool+localeVariable key = key == "LANG" || key == "LANGUAGE" || "LC_" `isPrefixOf` key++setVariables :: [(String, String)] -> [(String, String)] -> [(String, String)]+setVariables values environment = values ++ filter ((`notElem` map fst values) . fst) environment++requireLoopbackPasta :: IO ()+requireLoopbackPasta = do+  available <- findExecutable "pasta"+  helper <- maybe (pendingWith "pasta is not installed" >> fail "unreachable") pure available+  (code, _, err) <- capture $ proc helper+    ["--splice-only", "--no-map-gw", "--no-pidns", "-t", "none", "-u", "none",+     "-T", "none", "-U", "none", "--", "/bin/true"]+  unless (code == ExitSuccess) $ pendingWith $ "pasta loopback launcher unavailable: " ++ err++loopbackCommand :: Context -> [String] -> IO CreateProcess+loopbackCommand ctx command = do+  executable <- getExecutablePath+  environment <- getEnvironment+  let args = ["--test-loopback-network", "--die-with-parent", "--ro-bind", "/", "/",+              "--dev", "/dev", "--unshare-net", "--tmpfs", "/tmp", "--tmpfs", "/run",+              "--bind", project ctx, project ctx, "--chdir", project ctx] +++        (if privateProc ctx then ["--unshare-pid", "--proc", "/proc"] else []) ++ ["--"] ++ command+  pure $ (proc executable args) {cwd = Just (project ctx),+    env = Just $ setVariables [("XDG_STATE_HOME", root ctx </> "state")] environment}++pastaLogs :: Context -> IO [FilePath]+pastaLogs ctx = do+  let directory = root ctx </> "state/workcell/logs"+  entries <- listDirectory directory+  pure $ map (directory </>) entries++fakeHelperCommand :: Context -> String -> [String] -> IO CreateProcess+fakeHelperCommand ctx script command = do+  let tools = root ctx </> "helper tools"+      helper = tools </> "pasta"+  createDirectory tools+  writeFile helper $ "#!/bin/sh\n" ++ script+  setFileMode helper 0o700+  invocation <- loopbackCommand ctx command+  environment <- getEnvironment+  pure invocation {env = Just $ setVariables [("PATH", tools ++ ":/usr/bin:/bin")]+                    (fromMaybe environment $ env invocation)}++waitUntil :: IO Bool -> IO ()+waitUntil condition = do+  let wait = do+        done <- condition+        unless done $ threadDelay 10000 >> wait+  timeout (10 * 1000000) wait >>= maybe (expectationFailure "condition timed out") pure+++-- Session operations must not inherit invoke's launch-only sharing flags.+sessionEnvironment :: Context -> IO [(String, String)]+sessionEnvironment ctx = do+  environment <- getEnvironment+  pure $ [("XDG_RUNTIME_DIR", root ctx </> "session-runtime"),+          ("XDG_STATE_HOME", root ctx </> "session-state")] +++    filter (\(key, _) -> key `notElem` ["XDG_RUNTIME_DIR", "XDG_STATE_HOME"]) environment++sessionInvoke :: Context -> [String] -> IO (ExitCode, String, String)+sessionInvoke ctx args = do+  environment <- sessionEnvironment ctx+  capture $ (proc (binary ctx) args) {cwd = Just (project ctx), env = Just environment}++-- Supply a real terminal for menu input, while keeping preview and menu output separate.+menuInvoke :: Context -> [String] -> String -> IO (ExitCode, String, String)+menuInvoke ctx flags answer = do+  environment <- sessionEnvironment ctx+  let open = do+        (master, slave) <- openPseudoTerminal+        (,) <$> Posix.fdToHandle master <*> Posix.fdToHandle slave+      close (master, slave) = hClose master >> hClose slave+  result <- timeout (5 * 1000000) $ bracket open close $ \(master, slave) -> do+    let invocation = (proc (binary ctx) (["enter", "--dryrun"] ++ flags))+          {cwd = Just (project ctx), env = Just environment,+           std_in = UseHandle slave, std_out = CreatePipe, std_err = CreatePipe}+    bracket (createProcess invocation)+      (\(_, _, _, handle) -> terminateProcess handle >> waitForProcess handle >> pure ()) $+      \(_, output, errors, handle) -> do+        hPutStr master answer+        hFlush master+        code <- waitForProcess handle+        out <- maybe (fail "missing stdout pipe") BS.hGetContents output+        err <- maybe (fail "missing stderr pipe") BS.hGetContents errors+        pure (code, BSC.unpack out, BSC.unpack err)+  maybe (fail "session menu timed out") pure result++sessionRecordPaths :: Context -> IO [FilePath]+sessionRecordPaths ctx = do+  let parent = root ctx </> "session-runtime/workcell/sessions"+  namespaces <- listDirectory parent+  concat <$> mapM (\ns -> do+    let dir = parent </> ns+    names <- listDirectory dir+    pure [dir </> name | name <- names, "s" `isPrefixOf` name]) namespaces++withRunningSession :: Context -> [String] -> (String -> IO a) -> IO a+withRunningSession ctx extra action =+  withRunningSessionHandle ctx extra $ \ident _ -> action ident++withRunningSessionHandle :: Context -> [String] -> (String -> ProcessHandle -> IO a) -> IO a+withRunningSessionHandle ctx extra action = do+  environment <- sessionEnvironment ctx+  existing <- lines <$> (successful =<< sessionInvoke ctx ["list"])+  let args = ["--network-host" | not (hasNetworkOption extra)] +++             ["--share-processes" | not (privateProc ctx) && "--share-processes" `notElem` extra] +++             ["-H", root ctx </> "session-home"] ++ extra +++             ["--", "/bin/sh", "-c", "touch entry-home-marker \"$HOME/entry-home-marker\"; exec sleep 30"]+  bracket (createProcess $ (proc (binary ctx) args)+    {cwd = Just (project ctx), env = Just environment, std_out = NoStream})+    (\(_, _, _, handle) -> terminateProcess handle >> waitForProcess handle >> pure ()) $ \(_, _, _, handle) -> do+      found <- timeout (5 * 1000000) $ waitForSession existing handle+      ident <- maybe (fail "session did not become ready") pure found+      action ident handle+  where+    waitForSession existing handle = do+      status <- getProcessExitCode handle+      case status of+        Just code -> fail $ "workcell exited before registration: " ++ show code+        Nothing -> pure ()+      output <- successful =<< sessionInvoke ctx ["list"]+      marker <- doesFileExist $ project ctx </> "entry-home-marker"+      -- Select the most recently added record, rather than an existing session.+      case filter (`notElem` existing) (drop 1 $ lines output) of+        row:_ | marker, ident:_ <- words row -> pure ident+        _ -> threadDelay 10000 >> waitForSession existing handle++-- Read-only enclosing fixtures need writable storage for supervision and records.+fixtureProcess :: [String] -> CreateProcess+fixtureProcess args =+  let (mounts, command) = break (== "--") args+  in proc "bwrap" $ mounts +++    ["--tmpfs", "/tmp", "--setenv", "TMPDIR", "/tmp",+     "--setenv", "XDG_RUNTIME_DIR", "/tmp/workcell-fixture-runtime"] ++ command
+ workcell.cabal view
@@ -0,0 +1,105 @@+cabal-version:       2.2+name:                workcell+version:             0.1.2+synopsis:            Linux tool and project isolation using bubblewrap+description:+        Run tools with a read-only filesystem, isolated home,+        and explicit writable project access.+license:             LGPL-2.1-or-later+license-file:        COPYING.md+author:              Jens Petersen <juhpetersen@gmail.com>+maintainer:          Jens Petersen <juhpetersen@gmail.com>+copyright:           2026  Jens Petersen <juhpetersen@gmail.com>+category:            Utility+homepage:            https://github.com/juhp/workcell+bug-reports:         https://github.com/juhp/workcell/issues+build-type:          Simple+extra-doc-files:     README.md+                     ChangeLog.md+tested-with:         GHC == 8.10.7+                      || == 9.0.2+                      || == 9.2.8+                      || == 9.4.8+                      || == 9.6.7+                      || == 9.8.4+                      || == 9.10.3+                      || == 9.12.4++source-repository head+  type:                git+  location:            https://github.com/juhp/workcell.git++executable workcell+  main-is:             Main.hs+  other-modules:       Child+                       Enter+                       Identity+                       Run+                       Sandbox+                       Session+                       Util+                       Paths_workcell+  autogen-modules:     Paths_workcell+  hs-source-dirs:      src+  build-depends:       base < 5,+                       aeson,+                       bytestring,+                       directory,+                       extra,+                       filepath,+                       process,+                       simple-cmd >= 0.2.3,+                       simple-cmd-args >= 0.1.8,+                       unix+  default-language:    Haskell2010+  ghc-options:         -Wall -threaded+  if impl(ghc >= 8.0)+    ghc-options:       -Wcompat+                       -Widentities+                       -Wincomplete-uni-patterns+                       -Wincomplete-record-updates+                       -Wredundant-constraints+  if impl(ghc >= 8.2)+    ghc-options:       -fhide-source-paths+  if impl(ghc >= 8.4)+    ghc-options:       -Wmissing-export-lists+                       -Wpartial-fields+  if impl(ghc >= 8.10)+    ghc-options:       -Wunused-packages++test-suite test+  type:                exitcode-stdio-1.0+  main-is:             Spec.hs+  hs-source-dirs:      test src+  other-modules:       Child+                       Identity+                       Sandbox+                       Session+                       Util+  build-depends:       base < 5,+                       aeson,+                       bytestring,+                       directory,+                       extra,+                       filepath,+                       hspec,+                       network,+                       process,+                       simple-cmd,+                       unix+  build-tool-depends:  workcell:workcell+  default-language:    Haskell2010+  ghc-options:         -Wall -threaded++benchmark bench+  type:                exitcode-stdio-1.0+  main-is:             Bench.hs+  hs-source-dirs:      bench+  build-depends:       base < 5,+                       process,+                       simple-cmd,+                       tasty,+                       tasty-bench >= 0.4+  build-tool-depends:  workcell:workcell+  default-language:    Haskell2010+  ghc-options:         -Wall -threaded