packages feed

encapsule 0.6 → 0.6.1

raw patch · 19 files changed

+798/−179 lines, 19 filesdep +optparse-applicative

Dependencies added: optparse-applicative

Files

ChangeLog.md view
@@ -1,5 +1,19 @@ # encapsule releases +## 0.6.1 (2026-11-29)+- default session command is now bash --login+- add short `-c` option for `--cap`+- completion of capability names for `--cap` from the current config+- complete local image names and tags for `run` and `create`+- add `podman_opts` capability field for passing arguments directly to podman+- skip automatic SELinux relabeling for system mounts and with `label=disable`+- reject empty volume sources after environment-variable expansion+- additional capabilities added+- `backup`: just use --exclude-standard+- `enter` bugfix: pass running state to enterContainer+- `rm` now takes `--delete` option+- cleaner handling of init scriptlets+ ## 0.6 (2026-10-10) - make passwordless sudo setup opt-in with `--sudo` (replaces `--no-sudo`) - add `--root` as shorthand for `--user root`
README.md view
@@ -1,16 +1,24 @@ # encapsule -CLI tool to run developer containers, isolating your home directory and host from general effects inside the containers:-"encapsules" a project and/or temp home dir together with select "capabilities".+CLI tool to run developer containers, isolating your home directory and host+from general effects inside the containers: "encapsules" a project and/or+temp home dir together with select "capabilities".  Originally derived from [toolbox-constrained](https://github.com/swick/toolbox-constrained).  Run a ([toolbox](https://containertoolbx.org/)) container or image as an isolated podman container. Unlike with `toolbox create`, this does *not* bind-mount your home directory or integrate with the host by default.-You can explicitly choose what dir(s) or file(s) to mount or features to enable,-selecting user-configured "capabilities" that the encapsule container can access.+You can explicitly choose what dir(s) or file(s) to mount or features+to enable, selecting user-configured "capabilities" that+the encapsule container can access. +Note: for tool sandboxing I have personally since switched to using+[workcell](https://github.com/juhp/workcell) instead+(which uses Bubblewrap and also works inside a container), which avoids+the overhead of having to manage a separate container for sandboxing.+But I still use encapsule as a flexible replacement for toolbox.+ Most encapsule subcommands act on an image. - If you wish to use an existing toolbox container as a starting point you can `commit` it to an "encapsule" container image.   - Note your original toolbox container is left untouched: its system configuration and fs are just used as the base fs for the encapsule image (though its original bind mounts including $HOME will be not be included by default).@@ -33,7 +41,7 @@ `$ encapsule --version`  ```-0.6+0.6.1 ```  `$ encapsule --help`@@ -65,6 +73,13 @@ ```  There are 3 main commands: `run`, `create`, and `enter`.++Without an explicit command, all three start `bash --login`.+Login profiles may reset environment variables such as `PATH`.++`--init` snippets run in Bash as the container user before the command,+stopping if a snippet fails. Exported variables are inherited by the command.+ `run` and `create` share many options.  ### `run` command@@ -76,7 +91,7 @@ ``` Usage: encapsule run IMAGE [-v|--volume HOST:CONTAINER[:opts]]                      [-e|--env KEY[=VALUE]] [--path DIR] [-i|--init CMD]-                     [--cap NAME] [--pull] [--root | --user USER]+                     [-c|--cap NAME] [--pull] [--root | --user USER]                      [(-H|--home DIR[:opts]) [--backup-home]]                      [(-p|--project DIR[:opts]) [--backup-project]]                      [-n|--name NAME] [--readonly]@@ -92,7 +107,7 @@   --path DIR               Prepend a directory to PATH inside the container   -i,--init CMD            A bash snippet run when creating the encapsule                            container-  --cap NAME               Enable a capability from the config file+  -c,--cap NAME            Enable a config capability   --pull                   Pull newer container image   --root                   Run as root (shorthand for --user root)   --user USER              Override container user [default: host/image user@@ -126,7 +141,7 @@ `create` is similar but creates a reusable container for a project and/or temp home.  ### `enter` command-`enter` is used to join an existing (typically running) encapsule container.+`enter` is used to join an existing encapsule container. An optional command can be given, as with `run`:  ```bash@@ -148,7 +163,7 @@ Lists the encapsule images and containers:  ```-$ ncpsl list+$ encapsule list localhost/encapsule-harness:latest  6.15 GB  12 days ago  encapsule-harness-encapsule  Up 31 hours@@ -244,11 +259,33 @@ - `path` : list of directories to prepend to `$PATH` - `init` : a bash snippet to run on encapsule container creation - `security_opts` : list of `--security-opt` values passed to podman+- `podman_opts` : list of arguments passed directly to `podman run` +For example:++```toml+[capabilities.host-network]+podman_opts = ["--network=host"]+```+(equivalent to `--network-host`).++Each entry is one argument (use `["--ipc=host"]` or `["--ipc", "host"]`,+not `["--ipc host"]`). Arguments are passed literally without shell or+environment-variable expansion. Options from enabled capabilities are+concatenated in `--cap` order, followed by explicit `--podman-opt` arguments.+Podman handles repeated or conflicting options.+ `~` and envvars are expanded in volume and path specs. If the host and container paths are the same, you can use the shorthand `PATH[:opts]` instead of `PATH:PATH[:opts]`. +Automatic SELinux relabeling is skipped for system paths and when+`label=disable` is selected. Explicit `:z` or `:Z` options are preserved;+avoid requesting these for system directories. Empty mount sources,+including those produced by an unset environment variable, are rejected.++(Note _capabilities_ here does not refer to Linux `capabilities(7)`.)+ The default defined capabilities live in the bundled `data/config.toml` file. These capabilities can be overridden by XDG system config files (under `XDG_CONFIG_DIRS`): by default `/etc/xdg/encapsule/config.toml`.@@ -266,9 +303,28 @@ they need to be explicitly enabled on the commandline. The definitions just make them available to use. +## Completions++Capability names complete after `--cap` or `-c` for `run` and `create`,+using the current merged configuration.++The `IMAGE` argument completes locally stored Podman image names and tags.+Registry and repository path prefixes are removed, keeping the image name and tag+(for example, `quay.io/team/app:v1` completes as `app:v1`).+A leading `encapsule-` is also removed, matching implicit image lookup and container+naming (for example, `localhost/encapsule-dev:v1` completes as `dev:v1`).+If Podman is unavailable or fails, no image suggestions are offered.++You can enable shell completion with:+```sh+# Bash (add to ~/.bashrc)+eval "$(encapsule --bash-completion-script encapsule)"+```+The Fedora package comes with shell completion files.+ ## How it works -0. Optionally commits the named toolbox container to an encapsule image (using `podman commit`).+0. Optionally commit the named toolbox container to an encapsule image (using `podman commit`). 1. Runs `podman run` with `--userns=keep-id` so you are your own user, not root 2. Drops from root with `runuser` if present, otherwise `sudo -u`. Explicit    `--user root`/`--root` runs directly as root (`enter` uses@@ -291,7 +347,7 @@  Install `cabal-install` and `ghc`. -```bash+``` cabal install ``` @@ -338,6 +394,8 @@ - Encapsule has only been tested on Linux.  ## Related projects++I recommend using [workcell](https://github.com/juhp/workcell) now for sandboxing.  I already mentioned [toolbox-constrained](https://github.com/swick/toolbox-constrained) from which the initial code was derived. 
data/config.toml view
@@ -26,6 +26,39 @@ [capabilities.rust] path = ["~/.cargo/bin"] -[capabilities.ssh-agent]+[capabilities.unconfined]+security_opts = ["label=disable"]++[capabilities.proc-unmask]+security_opts = ["label=disable","unmask=/proc/*"]++[capabilities.ssh-agent-experimental] env = ["XDG_RUNTIME_DIR"] volumes = ["$XDG_RUNTIME_DIR/ssh-agent.sock"]++[capabilities.toolbox-experimental]+volumes = [+  "~:rw",+  "$XDG_RUNTIME_DIR",+  "/run/dbus/system_bus_socket",+  "/etc/machine-id:ro",+  "/tmp/.X11-unix",+  "/:/run/host:ro,rslave",+  "/dev:rslave",+]+env = [+  "XDG_RUNTIME_DIR",+  "WAYLAND_DISPLAY",+  "DISPLAY",+  "DBUS_SESSION_BUS_ADDRESS",+  "SSH_AUTH_SOCK",+]+podman_opts = [+  "--network=host",+  "--ipc=host",+  "--pid=host",+  "--cgroupns=host",+  "--privileged",+  "--ulimit=host",+]+security_opts = ["label=disable"]
encapsule.cabal view
@@ -1,6 +1,6 @@ cabal-version:       2.2 name:                encapsule-version:             0.6+version:             0.6.1 synopsis:            Run isolated toolbox containers with podman description:         This tool (originally based on the toolbox-constrained project)@@ -39,6 +39,7 @@   main-is:             Main.hs   other-modules:       Paths_encapsule                        Backup+                       Command                        Config                        Enter                        Error@@ -46,6 +47,7 @@                        Run                        Script                        ShellQuote+                       Volume   autogen-modules:     Paths_encapsule   hs-source-dirs:      src   build-depends:       base < 5@@ -53,6 +55,7 @@                      , extra                      , filepath                      , containers+                     , optparse-applicative                      , process                      , pretty-terminal                      , safe@@ -85,8 +88,16 @@   type:                exitcode-stdio-1.0   main-is:             Spec.hs   other-modules:       EncapsuleTest+                       Command+                       CommandSpec+                       CompletionSpec                        ConfigSpec+                       EnterSpec                        Config+                       Expand+                       Volume+                       VolumeSpec+                       ShellQuote                        Paths_encapsule   autogen-modules:     Paths_encapsule   hs-source-dirs:      test src@@ -95,6 +106,7 @@                      , directory                      , filepath                      , hspec+                     , extra                      , process                      , simple-cmd                      , text
example/config.toml view
@@ -5,6 +5,3 @@  [capabilities.agents] volumes = ["~/AGENTS.md:ro"]--[capabilities.unconfined]-security_opts = ["label=disable"]
src/Backup.hs view
@@ -48,7 +48,8 @@   if isgit     then do     withTempFile $ \ignorefile -> do-      out <- cmdLines "git" ["-C", src, "ls-files", "--cached", "--others", "--exclude-per-directory=.gitignore", "--directory", "--ignored"]+      -- FIXME? option to control --exclude-standard vs --exclude-per-directory=.gitignore+      out <- cmdLines "git" ["-C", src, "ls-files", "--cached", "--others", "--exclude-standard", "--directory", "--ignored"]       writeFile ignorefile $ unlines $ map dropTrailingPathSeparator out       checkSize yes (Just ignorefile) src       (if dryrun then cmdN else cmd_) "tar" $
+ src/Command.hs view
@@ -0,0 +1,20 @@+-- SPDX-License-Identifier: Apache-2.0++module Command (defaultCommand, withInit) where++import Data.List (intercalate)++defaultCommand :: [String] -> [String]+defaultCommand [] = ["bash", "-l"]+defaultCommand command = command++-- Run init snippets as the container user, then replace Bash with the command.+-- Pass argv separately so Bash does not reinterpret command arguments as code.+withInit :: [String] -> [String] -> [String]+withInit [] command = command+withInit snippets command =+  ["bash", "-c", intercalate " && " (map block snippets ++ ["exec \"$@\""])]+  ++ "bash" : command -- $0 + $* are args passed to the -c script+  where+    -- Permit empty snippets; keep comments from swallowing the next command.+    block snippet = "{\n:\n" ++ snippet ++ "\n}"
src/Config.hs view
@@ -1,8 +1,9 @@ -- SPDX-License-Identifier: Apache-2.0  module Config (+  Capability(..),+  listCaps,   listCapsCmd,-  loadConfig,   getCapabilities,   progname,   resolveCapabilities@@ -24,6 +25,15 @@ progname :: String progname = "encapsule" +data Capability = Capability+  { capVolumes :: [String]+  , capEnvs :: [String]+  , capPaths :: [String]+  , capInits :: [String]+  , capSecurityOpts :: [String]+  , capPodmanOpts :: [String]+  } deriving (Eq, Show) -- needed for tests+ loadConfig :: IO (Maybe Table) loadConfig = do   userPath <- getUserConfigFile progname "config.toml"@@ -56,34 +66,43 @@       Table $ mergeTables preferred fallback     mergeValue preferred _ = preferred -getCapabilities :: Maybe Table -> Table-getCapabilities Nothing = Map.empty-getCapabilities (Just table) =-  case Map.lookup (T.pack "capabilities") table of-    Just (Table t) -> t-    _ -> Map.empty+getCapabilities :: IO Table+getCapabilities =+  getCapabilities' <$> loadConfig+  where+    getCapabilities' :: Maybe Table -> Table+    getCapabilities' Nothing = Map.empty+    getCapabilities' (Just table) =+      case Map.lookup (T.pack "capabilities") table of+        Just (Table t) -> t+        _ -> Map.empty -resolveCapabilities :: Table -> [String] -> IO ([String], [String], [String], [String], [String])+resolveCapabilities :: Table -> [String] -> IO Capability resolveCapabilities caps capNames = do   results <- mapM (resolveCap caps) capNames-  let (vs, es, ps, is, ss) = unzip5 results-  return (concat vs, concat es, concat ps, concat is, concat ss)-  where-    unzip5 = foldr (\(a,b,c,d,e) (as,bs,cs,ds,es) -> (a:as,b:bs,c:cs,d:ds,e:es))-                   ([],[],[],[],[])+  return Capability+    { capVolumes = concatMap capVolumes results+    , capEnvs = concatMap capEnvs results+    , capPaths = concatMap capPaths results+    , capInits = concatMap capInits results+    , capSecurityOpts = concatMap capSecurityOpts results+    , capPodmanOpts = concatMap capPodmanOpts results+    } -resolveCap :: Table -> String -> IO ([String], [String], [String], [String], [String])+resolveCap :: Table -> String -> IO Capability resolveCap caps name =   case Map.lookup (T.pack name) caps of     Just (Table cap) ->-      return ( getStringList "volumes" cap-             , getStringList "env" cap-             , getStringList "path" cap-             , case getStringVal "init" cap of-                 Just s -> [s]-                 Nothing -> []-             , getStringList "security_opts" cap-             )+      return Capability+        { capVolumes = getStringList "volumes" cap+        , capEnvs = getStringList "env" cap+        , capPaths = getStringList "path" cap+        , capInits = case getStringVal "init" cap of+            Just s -> [s]+            Nothing -> []+        , capSecurityOpts = getStringList "security_opts" cap+        , capPodmanOpts = getStringList "podman_opts" cap+        }     _ -> do       let available = if Map.null caps                       then "(none defined)"@@ -106,12 +125,14 @@ valueToString (String t) = Just (T.unpack t) valueToString _ = Nothing +listCaps :: IO [String]+listCaps = map T.unpack . Map.keys <$> getCapabilities+ listCapsCmd :: IO () listCapsCmd = do-  config <- loadConfig-  let capabilities = getCapabilities config-  if Map.null capabilities+  caps <- listCaps+  if null caps     then putStrLn "No capabilities defined"     else do       putStrLn "Available capabilities:"-      mapM_ (putStrLn . ("  " ++) . T.unpack) $ Map.keys capabilities+      mapM_ (putStrLn . ("  " ++)) caps
src/Enter.hs view
@@ -18,6 +18,7 @@ import System.Process (rawSystem) import System.Posix.User (getEffectiveUserID, getEffectiveUserName) +import Command (defaultCommand) import ShellQuote  enterContainer :: Bool -> Bool -> Bool -> Maybe String -> String -> [String] -> IO ()@@ -28,7 +29,7 @@     cmd_ "podman" ["start", container]   (username, mPasswdHome) <- lookupContainerUser container muser   wd <- containerWorkdir container-  let userCmd = if null command then ["bash"] else command+  let userCmd = defaultCommand command       homeDir = fromMaybe hostHome mPasswdHome       -- If inspect reports "/" then --workdir was omitted at create       -- (host $HOME was not in the image), then fallback to $HOME
src/Main.hs view
@@ -2,11 +2,18 @@  module Main (main) where +import Control.Exception (IOException, try) import Control.Monad.Extra (unless, when)+import Data.List.Extra (dropPrefix, isInfixOf) import Data.Maybe (fromMaybe)+import qualified Data.Set as Set+import Options.Applicative (completer, listIOCompleter, metavar, strArgument, strOption) import SimpleCmd (cmd_, cmdBool, cmdFull, cmdLines, cmdN, warning, (+-+)) import SimpleCmdArgs import System.IO (BufferMode(NoBuffering), hSetBuffering, stdout)+import System.Exit (ExitCode(..))+import System.FilePath (takeFileName)+import System.Process (readProcessWithExitCode)  import Backup import Config@@ -23,7 +30,6 @@     ("Run a toolbox image in an isolated podman container" +-+      "https://github.com/juhp/encapsule#readme") $     subcommands-    -- FIXME add/separate: create/enter/run     [ Subcommand "list" "List encapsule images and containers" $       pure listCmd     , Subcommand "list-caps" "List available capabilities" $@@ -32,7 +38,8 @@       pullCmd <$> strArg "IMAGE"     , Subcommand "rm" "Remove an encapsule container" $       removeCmd-      <$> strArg "TOOLBOX"+      <$> switchLongWith "delete" "Do container removal"+      <*> strArg "TOOLBOX"       <*> optional projectNameOpt     , Subcommand "rmi" "Remove an encapsule image" $       removeImageCmd@@ -89,14 +96,18 @@       flagLongWith' "root" "root" "Run as root (shorthand for --user root)" <|>       strOptionLongWith "user" "USER" "Override container user [default: host/image user with host UID]" +    capOpt = strOption $+      optionMods 'c' "cap" "NAME" "Enable a config capability" <>+      completer (listIOCompleter listCaps)+     runOpts keep unique =       Run.RunOpts-      <$> strArg "IMAGE"+      <$> strArgument (metavar "IMAGE" <> completer (listIOCompleter listImages))       <*> many (strOptionWith 'v' "volume" "HOST:CONTAINER[:opts]" "Bind mount (user's files default to selinux :z)")       <*> many (strOptionWith 'e' "env" "KEY[=VALUE]" "Set or pass through an environment variable")       <*> many (strOptionLongWith "path" "DIR" "Prepend a directory to PATH inside the container")       <*> many (strOptionWith 'i' "init" "CMD" "A bash snippet run when creating the encapsule container")-      <*> many (strOptionLongWith "cap" "NAME" "Enable a capability from the config file")+      <*> many capOpt       <*> switchLongWith "pull" "Pull newer container image"       <*> optional userNameOpt       <*> optional (dirOptBackup 'H' "home" "DIR[:opts]" "Mount a directory as a writable home (created if missing; use DIR:O to overlay)")@@ -115,6 +126,20 @@       <*> dryrunOpt       <*> many (strArg "[--] CMD") +-- Completion should stay quiet when Podman is absent or its storage is unavailable.+listImages :: IO [String]+listImages = do+  result <- try (readProcessWithExitCode "podman"+                 ["images", "--format", "{{.Repository}}:{{.Tag}}"] "")+            :: IO (Either IOException (ExitCode, String, String))+  return $ case result of+    Right (ExitSuccess, out, _) ->+      Set.toAscList $ Set.fromList+        [shortName name | name <- lines out, not (null name), not ("<none>" `isInfixOf` name)]+    _ -> []+  where+    shortName = dropPrefix (progname ++ "-") . takeFileName+ listCmd :: IO () listCmd = do   needPodman@@ -126,8 +151,8 @@                  "--filter", "name=^" ++ progname +=+ "",                  "--format", "{{.Names}}  {{.Status}}"] -removeCmd :: String -> Maybe ProjectName -> IO ()-removeCmd toolbox mprojectname = do+removeCmd :: Bool -> String -> Maybe ProjectName -> IO ()+removeCmd delete toolbox mprojectname = do   containerName <- mkContainerName toolbox mprojectname   needPodman   exists <- cmdBool "podman" ["container", "exists", containerName]@@ -138,8 +163,11 @@       when (take 4 out == "true") $ do         putStr "stopping "         cmd_ "podman" ["stop", containerName]-      putStr "rm "-      cmd_ "podman" ["rm", containerName]+      if delete+        then do+        putStr "rm "+        cmd_ "podman" ["rm", containerName]+        else putStrLn "use --delete to actually remove"     else warning $ "container" +-+ containerName +-+ "not found"  -- FIXME check image exists?@@ -171,7 +199,8 @@ enterCmd dryrun debug running mbase mprojectname muser command = do   regexp <-     case mprojectname of-      Nothing -> return $ progname +=+ fromMaybe "" mbase+      Nothing -> return $ progname +=+ fromMaybe ".*" mbase+      Just (Name ('^':n)) -> return n       Just (Name n) -> return $ progname ++ '-' : n       Just (Project p) -> do         projectDir <- resolveProject p@@ -179,18 +208,17 @@   needPodman   ps <- cmdLines "podman" $ "ps" :         ["-a" | not running] ++-        ["--filter", "name=" ++ '^' : regexp,+        ["--filter", "name=" ++ '^' : regexp ++ "$",          "--format", "{{.Names}}"]   case ps of     [] ->       if running-      then do-        enterCmd dryrun debug False mbase mprojectname muser command+      then enterCmd dryrun debug False mbase mprojectname muser command       else error' "encapsule container not found"     [c] -> do-      unless running $+      when (debug && not running) $         warning "no running encapsule container found"-      enterContainer dryrun debug True muser c command+      enterContainer dryrun debug running muser c command     _ -> error' $ "multiple" +-+ (if running then  "running" else "") +-+ "containers match:\n" ++ unlines ps  -- image management@@ -206,9 +234,11 @@   containerExists <- cmdBool "podman" ["container", "exists", toolbox]   unless containerExists $     error' $ "container '" ++ toolbox ++ "' not found"-  let image = maybe (progname +=+ toolbox) encapsuleName mname-      encapsuleName ('^':n) = n-      encapsuleName n = progname +=+ n+  let image =+        -- FIXME or fallback if no encapsule container+        let encapsuleName ('^':n) = n+            encapsuleName n = progname +=+ n+        in maybe (progname +=+ toolbox) encapsuleName mname   imageExists <- cmdBool "podman" ["image", "exists", image]   unless imageExists $     putStrLn $ "creating new image:" +-+ image
src/Run.hs view
@@ -17,7 +17,7 @@ where  import Control.Monad.Extra (unless, unlessM, when, whenJust, (>=>))-import Data.List.Extra (intercalate, isPrefixOf, splitOn)+import Data.List.Extra (intercalate, isPrefixOf) import Data.Maybe (fromMaybe, isJust, isNothing) import qualified Data.Text.Lazy as TL import Safe (headMay, lastMay)@@ -30,7 +30,7 @@ import System.Environment (lookupEnv) import System.Exit (exitWith) import System.FilePath ((</>), makeRelative, takeDirectory, takeFileName)-import System.Posix.Files (fileOwner, getFileStatus, isSocket)+import System.Posix.Files (getFileStatus, isSocket) import System.Posix.Process (getProcessID) import System.Posix.Types (UserID) import System.Posix.User (getEffectiveGroupID, getEffectiveUserID,@@ -39,9 +39,11 @@   import Backup-import Config (getCapabilities, loadConfig, progname, resolveCapabilities)+import Command (defaultCommand, withInit)+import Config (Capability(..), getCapabilities, progname, resolveCapabilities) import Enter import Expand+import Volume (addSelinuxLabel, disablesSelinux, expandVolumeHost, isVolumePathStart) import Script import ShellQuote @@ -163,10 +165,9 @@                  show toolbox +-+ "image not found\n" ++                  "Create an image from a container with 'commit', or build/pull one"       debug $ "image:" +-+ image-      config <- loadConfig-      let capabilities = getCapabilities config+      capabilities <- getCapabilities -      (extraVols, extraEnvs, extraPaths, extraInits, extraSecurityOpts) <-+      Capability{..} <-         resolveCapabilities capabilities caps        -- FIXME perhaps add --no-runuser?@@ -217,7 +218,7 @@               Just p -> ensureTempHomeMountPoint containerHome temphome p p               Nothing -> return ()             mapM_ (ensureTempHomeVol hostHome containerHome temphome)-              (vols ++ extraVols)+              (vols ++ capVolumes)             return [temphome ++ ":" ++ containerHome ++ maybeOpts homeMountOpts]           Nothing -> return [] @@ -235,21 +236,23 @@       let mountsRealHome =             Just hostHome == mtemphome || Just hostHome == mprojectDir           securityOpts =-            extraSecurityOpts +++            capSecurityOpts ++             ["label=disable" | mountsRealHome,-             "label=disable" `notElem` extraSecurityOpts] +++             "label=disable" `notElem` capSecurityOpts] ++             ["label=level:s0" | isJust mtemphome && not mountsRealHome,-             "label=level:s0" `notElem` extraSecurityOpts,-             "label=disable" `notElem` extraSecurityOpts]-          volumes = homeVol ++ vols ++ extraVols ++ projectVol-          envVars = envs ++ extraEnvs-          allinits = inits ++ extraInits-      allpaths <- mapM (expandContainerPath containerHome) (paths ++ extraPaths)+             "label=level:s0" `notElem` capSecurityOpts,+             "label=disable" `notElem` capSecurityOpts]+          volumes = homeVol ++ vols ++ capVolumes ++ projectVol+          envVars = envs ++ capEnvs+          allinits = inits ++ capInits+      allpaths <- mapM (expandContainerPath containerHome) (paths ++ capPaths)       let userCmd =             let envParts =-                  (if overrideHome then (("HOME=" ++ containerHome) :) else id) $+                  (if overrideHome+                   then (("HOME=" ++ containerHome) :)+                   else id) $                   pathEnvPart allpaths-                userCmdParts = mkUserCmd command allinits+                userCmdParts = withInit allinits $ defaultCommand command             in               (if null envParts then id else (("env" +-+ unwords envParts) +-+)) $               unwords $ map shellQuote userCmdParts@@ -261,8 +264,7 @@            setupParts =             let setup = setupScript debugging mswitch haveSudo setupArgs-            in [setup | not (null setup)] ++-               [mkInitSetup allinits | not (null allinits)]+            in [setup | not (null setup)]           finalCmd =             case maybe [] (switchUserArgs username) mswitch of               []   -> "exec" +-+ userCmd@@ -276,7 +278,9 @@       when ("label=disable" `elem` securityOpts) $         warning "SELinux labeling disabled for this container (label=disable)"       unless dryrun $ debug $ "setup:" +-+ execScript-      mounts <- mapM (addSelinuxLabel hostHome containerHome) volumes+      let labelDisabled = disablesSelinux $+            concatMap (\opt -> ["--security-opt", opt]) securityOpts ++ capPodmanOpts ++ podmanopts+      mounts <- mapM (addSelinuxLabel labelDisabled hostHome containerHome) volumes       tzMounts <- hostTimezoneMount       debug $ "timezone:" +-+ show tzMounts       -- C.UTF-8 is in base images; host LANG (e.g. en_US.UTF-8) often is not.@@ -336,7 +340,7 @@                 ++ concatMap (\s -> ["--security-opt", s]) securityOpts                 ++ concatMap (\m -> ["-v", m]) (tzMounts ++ mounts)                 ++ concatMap (\e -> ["-e", e]) envVars-                ++ podmanopts+                ++ capPodmanOpts ++ podmanopts                 ++ [image, "sh", "-c", execScript]        when (dryrun || debugging) $ do@@ -403,12 +407,6 @@ maybeOpts Nothing = "" maybeOpts (Just o) = ':' : o -isVolumePathStart :: String -> Bool-isVolumePathStart ('/':_) = True-isVolumePathStart ('~':_) = True-isVolumePathStart ('$':_) = True-isVolumePathStart _       = False- -- | Combine two strings with a dash infixr 4 +=+ (+=+) :: String -> String -> String@@ -478,11 +476,11 @@ volumePaths hostHome containerHome spec =   case break (== ':') spec of     (hostPart, []) -> do-      hostExp <- expandPath hostHome hostPart+      hostExp <- expandVolumeHost hostHome hostPart       containerExp <- expandContainerPath containerHome hostPart       return (hostExp, containerExp)     (hostPart, _:rest') -> do-      hostExp <- expandPath hostHome hostPart+      hostExp <- expandVolumeHost hostHome hostPart       if isVolumePathStart rest'         then do           let containerPart = takeWhile (/= ':') rest'@@ -500,66 +498,6 @@   let prefix = intercalate ":" ps   in ["PATH=\"" ++ prefix ++ ":$PATH\""] -mkInitSetup :: [String] -> String-mkInitSetup [] = ""-mkInitSetup snippets =-  let content = intercalate "\\n" snippets-  in "printf" +-+ shellQuote content +-+ "> /tmp" </> progname ++ "-init.sh"--mkUserCmd :: [String] -> [String] -> [String]-mkUserCmd [] inits = mkUserCmd ["bash"] inits-mkUserCmd ["bash"] (_:_) =-  ["bash", "--rcfile", "/tmp" </> progname ++ "-init.sh"]-mkUserCmd com inits@(_:_) =-  let initChain = intercalate " && " inits-      cmdStr = initChain +-+ "&& exec" +-+ unwords (map shellQuote com)-  in ["sh", "-c", cmdStr]-mkUserCmd com [] = com---- SELinux labeling---- Rootless podman cannot lsetxattr on files owned by another uid (e.g. /etc/*)--- FIXME rather return Mount type or triple?-addSelinuxLabel :: FilePath -> FilePath -> String -> IO String-addSelinuxLabel hostHome containerHome spec =-  case break (== ':') spec of-    (hostPart, []) -> do-      hostExp <- expandPath hostHome hostPart-      containerExp <- expandContainerPath containerHome hostPart-      requireVolumeHost hostExp-      skipLabel <- shouldSkipLabel hostExp-      return $ hostExp ++ ":" ++ containerExp ++ if skipLabel then "" else ":z"-    (hostPart, _:rest') -> do-      hostExp <- expandPath hostHome hostPart-      requireVolumeHost hostExp-      let (containerPart, optsPart)-            | isVolumePathStart rest' =-                case break (== ':') rest' of-                  (c, [])  -> (c, Nothing)-                  (c, _:o) -> (c, Just o)-            | otherwise = (hostPart, if null rest' then Nothing else Just rest')-      containerExp <- expandContainerPath containerHome containerPart-      skipLabel <- shouldSkipLabel hostExp-      let labeled = case optsPart of-            Nothing ->-              if skipLabel-              then hostExp ++ ":" ++ containerExp-              else hostExp ++ ":" ++ containerExp ++ ":z"-            Just o ->-              let flags = splitOn "," o-              in if skipLabel || "z" `elem` flags || "Z" `elem` flags-                    || "O" `elem` flags-                 then hostExp ++ ":" ++ containerExp ++ ":" ++ o-                 else hostExp ++ ":" ++ containerExp ++ ":" ++ o ++ ",z"-      return labeled-  where-    -- Skip auto :z for sockets, real $HOME (uses label=disable), and paths we-    -- cannot relabel (rootless lsetxattr fails on files owned by another user)-    shouldSkipLabel hostExp = do-      sockFile <- isSocketFile hostExp-      selfOwned <- ownedBySelf hostExp-      return $ sockFile || hostExp == hostHome || not selfOwned- -- later possibly also support /etc/timezone hostTimezoneMount :: IO [String] hostTimezoneMount = do@@ -587,20 +525,8 @@ isUnderDir base path =   path == base || (base ++ "/") `isPrefixOf` path -requireVolumeHost :: FilePath -> IO ()-requireVolumeHost path = do-  exists <- doesPathExist path-  unless exists $-    error' $ "volume host path not found:" +-+ path- isSocketFile :: FilePath -> IO Bool isSocketFile path = isSocket <$> getFileStatus path--ownedBySelf :: FilePath -> IO Bool-ownedBySelf path = do-  uid <- getEffectiveUserID-  st <- getFileStatus path-  return $ fileOwner st == uid  needPodman :: IO () needPodman = needProgram "podman"
src/ShellQuote.hs view
@@ -2,11 +2,15 @@  module ShellQuote (shellQuote) where +import Data.Char (isAsciiLower, isAsciiUpper, isDigit)+ shellQuote :: String -> String+shellQuote "" = "''" shellQuote s   | all isSafe s = s   | otherwise = "'" ++ concatMap escSQ s ++ "'"   where-    isSafe c = c `elem` (['A'..'Z'] ++ ['a'..'z'] ++ ['0'..'9'] ++ "-_./=:@,+")+    isSafe c = isAsciiUpper c || isAsciiLower c || isDigit c ||+               c `elem` "-_./=:@,+"     escSQ '\'' = "'\\''"     escSQ c = [c]
+ src/Volume.hs view
@@ -0,0 +1,103 @@+-- SPDX-License-Identifier: Apache-2.0++module Volume (+  addSelinuxLabel,+  disablesSelinux,+  expandVolumeHost,+  isVolumePathStart+  ) where++import Control.Monad (unless, when)+import Data.List (isPrefixOf)+import Data.List.Extra (splitOn)+import SimpleCmd (error', (+-+))+import System.Directory (canonicalizePath, doesPathExist)+import System.Posix.Files (fileOwner, getFileStatus, isSocket)+import System.Posix.User (getEffectiveUserID)++import Expand (expandPath, expandContainerPath)++-- Only suppress automatic relabeling; explicitly requested :z/:Z stays intact.+disablesSelinux :: [String] -> Bool+disablesSelinux [] = False+disablesSelinux ("--security-opt":"label=disable":_) = True+disablesSelinux ("--security-opt=label=disable":_) = True+disablesSelinux (_:rest) = disablesSelinux rest++-- Canonical paths prevent aliases such as /dev/ and /tmp/../dev bypassing this.+isSystemPath :: FilePath -> Bool+isSystemPath path =+  path `elem` ["/", "/home", "/tmp", "/mnt", "/media"] ||+  any (\base -> path == base || (base ++ "/") `isPrefixOf` path)+    ["/dev", "/proc", "/sys", "/etc", "/usr", "/run", "/var",+     "/boot", "/root", "/opt", "/srv"]++isVolumePathStart :: String -> Bool+isVolumePathStart ('/':_) = True+isVolumePathStart ('~':_) = True+isVolumePathStart ('$':_) = True+isVolumePathStart _       = False++-- SELinux labeling++-- Rootless podman cannot lsetxattr on files owned by another uid (e.g. /etc/*)+-- FIXME rather return Mount type or triple?+addSelinuxLabel :: Bool -> FilePath -> FilePath -> String -> IO String+addSelinuxLabel labelDisabled hostHome containerHome spec =+  case break (== ':') spec of+    (hostPart, []) -> do+      hostExp <- expandVolumeHost hostHome hostPart+      containerExp <- expandContainerPath containerHome hostPart+      skipLabel <- shouldSkipLabel hostExp+      return $ hostExp ++ ":" ++ containerExp ++ if skipLabel then "" else ":z"+    (hostPart, _:rest') -> do+      hostExp <- expandVolumeHost hostHome hostPart+      let (containerPart, optsPart)+            | isVolumePathStart rest' =+                case break (== ':') rest' of+                  (c, [])  -> (c, Nothing)+                  (c, _:o) -> (c, Just o)+            | otherwise = (hostPart, if null rest' then Nothing else Just rest')+      containerExp <- expandContainerPath containerHome containerPart+      skipLabel <- shouldSkipLabel hostExp+      let labeled = case optsPart of+            Nothing ->+              if skipLabel+              then hostExp ++ ":" ++ containerExp+              else hostExp ++ ":" ++ containerExp ++ ":z"+            Just o ->+              let flags = splitOn "," o+              in if skipLabel || "z" `elem` flags || "Z" `elem` flags+                    || "O" `elem` flags+                 then hostExp ++ ":" ++ containerExp ++ ":" ++ o+                 else hostExp ++ ":" ++ containerExp ++ ":" ++ o ++ ",z"+      return labeled+  where+    -- Skip auto :z for sockets, real $HOME (uses label=disable), and paths we+    -- cannot relabel (rootless lsetxattr fails on files owned by another user)+    shouldSkipLabel hostExp = do+      sockFile <- isSocketFile hostExp+      selfOwned <- ownedBySelf hostExp+      canonical <- canonicalizePath hostExp+      home <- canonicalizePath hostHome+      return $ labelDisabled || isSystemPath canonical || sockFile+               || canonical == home || not selfOwned++expandVolumeHost :: FilePath -> String -> IO FilePath+expandVolumeHost home source = do+  path <- expandPath home source+  when (null path) $ error' "volume host path must not be empty"+  exists <- doesPathExist path+  unless exists $+    error' $ "volume host path not found:" +-+ path+  return path++isSocketFile :: FilePath -> IO Bool+isSocketFile path = isSocket <$> getFileStatus path++ownedBySelf :: FilePath -> IO Bool+ownedBySelf path = do+  uid <- getEffectiveUserID+  st <- getFileStatus path+  return $ fileOwner st == uid+
+ test/CommandSpec.hs view
@@ -0,0 +1,55 @@+-- SPDX-License-Identifier: Apache-2.0++module CommandSpec (spec) where++import System.Exit (ExitCode(..))+import System.Process (readProcessWithExitCode)+import Test.Hspec++import Command (defaultCommand, withInit)+import ShellQuote (shellQuote)++spec :: Spec+spec = describe "user command" $ do+  it "defaults to a login Bash shell" $+    defaultCommand [] `shouldBe` ["bash", "-l"]++  it "preserves an explicit command without adding login options" $+    mapM_ (\command -> withInit [] (defaultCommand command) `shouldBe` command)+      [["bash"], ["bash", "--noprofile"], ["printf", "%s", "hello world"]]++  it "runs Bash init snippets in order and passes their exported environment" $ do+    result <- runWithInit+      [ "values=(hello world); export ENCAPSULE_INIT_TEST=${values[0]}"+      , "export ENCAPSULE_INIT_TEST+=\" ${values[1]}\" # trailing comment"+      ]+      ["bash", "--noprofile", "--norc", "-c", "printf '%s' \"$ENCAPSULE_INIT_TEST\""]+    result `shouldBe` (ExitSuccess, "hello world", "")++  it "preserves empty arguments and shell metacharacters through init" $ do+    let args = ["", "hello world", "a'b", "\"quoted\"", "$HOME", "$(exit 99)", "; exit 99", "line\nbreak", "-l"]+    result <- runWithInit [":"] (["printf", "<%s>\n"] ++ args)+    result `shouldBe` (ExitSuccess, concatMap (\arg -> "<" ++ arg ++ ">\n") args, "")++  it "accepts empty and comment-only init snippets" $ do+    result <- runWithInit ["", "# comment"] ["printf", "ok"]+    result `shouldBe` (ExitSuccess, "ok", "")++  it "stops before later snippets and the command if init fails" $ do+    result <- runWithInit ["exit 7", "printf later"] ["printf", "command"]+    result `shouldBe` (ExitFailure 7, "", "")++  it "propagates a snippet failure without running the command" $ do+    result <- runWithInit ["false"] ["printf", "command"]+    result `shouldBe` (ExitFailure 1, "", "")++  it "preserves the command exit status after successful init" $ do+    result <- runWithInit [":"] ["bash", "-c", "exit 23"]+    result `shouldBe` (ExitFailure 23, "", "")++runWithInit :: [String] -> [String] -> IO (ExitCode, String, String)+runWithInit snippets command =+  case withInit snippets (defaultCommand command) of+    args@(_:_) -> readProcessWithExitCode "sh"+      ["-c", "exec " ++ unwords (map shellQuote args)] ""+    [] -> fail "empty user command"
+ test/CompletionSpec.hs view
@@ -0,0 +1,114 @@+-- SPDX-License-Identifier: Apache-2.0++module CompletionSpec (spec) where++import Control.Exception (bracket)+import Data.List (isPrefixOf)+import Data.Maybe (fromMaybe)+import System.Directory (canonicalizePath, findExecutable, removeDirectoryRecursive)+import System.Environment (lookupEnv, setEnv, unsetEnv)+import System.FilePath ((</>))+import System.Posix.Files (setFileMode)+import System.Posix.Temp (mkdtemp)+import Test.Hspec++import EncapsuleTest (encapsuleChecked)++spec :: Spec+spec = describe "image completion" $ do+  it "completes local names and tags once, filtering dangling images and prefixes" $+    withPodman (Just imageScript) $+      mapM_ (\subcmd -> do+        complete [subcmd, ""] `shouldReturn`+          ["alpine:latest", "dev:latest", "dev:v1"]+        complete [subcmd, "dev:"] `shouldReturn`+          ["dev:latest", "dev:v1"]+        complete [subcmd, "unknown"] `shouldReturn` []) ["run", "create"]++  it "completes the image after options and stops suggesting images for commands" $+    withPodman (Just imageScript) $+      mapM_ (\subcmd -> do+        complete [subcmd, "--user", "root", "alp"] `shouldReturn`+          ["alpine:latest"]+        complete [subcmd, "alpine:latest", "alp"] `shouldReturn` [])+        ["run", "create"]++  it "strips registries and repository paths, and deduplicates shortened names" $+    withPodman (Just $ unlines+      [ "#!/bin/sh"+      , "echo registry.example:5000/team/app:v1"+      , "echo quay.io/team/app:v1"+      , "echo quay.io/other/nested/app:v1"+      , "echo '[::1]:5000/team/app:v2'"+      , "echo team/app:v3"+      , "echo standalone:latest"+      ]) $+      mapM_ (\subcmd -> do+        complete [subcmd, ""] `shouldReturn`+          ["app:v1", "app:v2", "app:v3", "standalone:latest"]+        complete [subcmd, "app:"] `shouldReturn`+          ["app:v1", "app:v2", "app:v3"])+        ["run", "create"]++  it "returns no suggestions or diagnostics when Podman fails" $+    withPodman (Just "#!/bin/sh\necho storage-error >&2\necho partial:latest\nexit 1\n") $+      mapM_ (\subcmd -> complete [subcmd, ""] `shouldReturn` []) ["run", "create"]++  it "removes one leading encapsule prefix while preserving other occurrences and tags" $+    withPodman (Just $ unlines+      [ "#!/bin/sh"+      , "echo localhost/encapsule-fedora-toolbox:45"+      , "echo localhost/fedora-toolbox:45"+      , "echo localhost/my-encapsule-dev:latest"+      , "echo localhost/encapsule-encapsule-dev:encapsule-tag"+      ]) $+      mapM_ (\subcmd -> do+        complete [subcmd, ""] `shouldReturn`+          ["encapsule-dev:encapsule-tag", "fedora-toolbox:45", "my-encapsule-dev:latest"]+        complete [subcmd, "fedora"] `shouldReturn` ["fedora-toolbox:45"])+        ["run", "create"]++  it "returns no suggestions when Podman is missing" $+    withPodman Nothing $+      mapM_ (\subcmd -> complete [subcmd, ""] `shouldReturn` []) ["run", "create"]++imageScript :: String+imageScript = unlines+  [ "#!/bin/sh"+  , "[ \"$#\" = 3 ] && [ \"$1\" = images ] && [ \"$2\" = --format ] && [ \"$3\" = '{{.Repository}}:{{.Tag}}' ] || exit 1"+  , "echo ignored-warning >&2"+  , "echo localhost/encapsule-dev:v1"+  , "echo docker.io/library/alpine:latest"+  , "echo localhost/encapsule-dev:latest"+  , "echo localhost/encapsule-dev:v1"+  , "echo '<none>:<none>'"+  , "echo 'localhost/untagged:<none>'"+  , "echo"+  ]++complete :: [String] -> IO [String]+complete words' =+  filter (not . isPrefixOf "-") . lines <$> encapsuleChecked+    (["--bash-completion-index", show (length words')] +++     concatMap (\word -> ["--bash-completion-word", word]) ("encapsule" : words'))++-- Resolve encapsule before restricting PATH, so even the missing-Podman case+-- works on hosts where Podman is installed.+withPodman :: Maybe String -> IO a -> IO a+withPodman script action = do+  name <- fromMaybe "encapsule" <$> lookupEnv "ENCAPSULE"+  exe <- findExecutable name >>= maybe (fail "encapsule executable not found") canonicalizePath+  bracket (mkdtemp "/tmp/encapsule-completion-test-XXXXXX") removeDirectoryRecursive $ \dir -> do+    case script of+      Nothing -> return ()+      Just contents -> do+        writeFile (dir </> "podman") contents+        setFileMode (dir </> "podman") 0o700+    withEnv "ENCAPSULE" exe $ withEnv "PATH" dir action++withEnv :: String -> String -> IO a -> IO a+withEnv key value action =+  bracket (lookupEnv key) restore $ \_ -> setEnv key value >> action+  where+    restore Nothing = unsetEnv key+    restore (Just old) = setEnv key old
test/ConfigSpec.hs view
@@ -10,19 +10,64 @@ import System.Posix.Temp (mkdtemp) import Test.Hspec -import Config (getCapabilities, loadConfig, resolveCapabilities)-import EncapsuleTest (encapsule)+import Config (Capability(..), getCapabilities, listCaps, resolveCapabilities)+import EncapsuleTest (encapsule, encapsuleChecked, withGenericImage)  spec :: Spec spec = describe "config" $ do+  it "combines podman options in capability selection order and replaces overridden arrays" $+    withConfigDirs $ \user system _ -> do+      writeConfig system $ unlines+        [ "[capabilities.network]"+        , "env = ['HOST_NETWORK']"+        , "podman_opts = ['--network=none']"+        , "[capabilities.ipc]"+        , "podman_opts = ['--ipc', 'host']"+        ]+      writeConfig user "[capabilities.network]\npodman_opts = ['--network=host']\n"+      resolve ["ipc", "network"] `shouldReturn`+        emptyCapability { capEnvs = ["HOST_NETWORK"], capPodmanOpts = ["--ipc", "host", "--network=host"] }+      writeConfig user "[capabilities.network]\npodman_opts = []\n"+      resolve ["network"] `shouldReturn` emptyCapability { capEnvs = ["HOST_NETWORK"] }++  it "passes capability podman options before explicit CLI options for run and create" $+    withGenericImage $ \img ->+      withConfigDirs $ \user _ _ -> do+        writeConfig user "[capabilities.ipc]\npodman_opts = ['--ipc=host']\n"+        mapM_ (\subcmd -> do+          out <- encapsuleChecked+            [subcmd, "--dryrun", "--cap", "ipc", "--podman-opt=--ipc=private", img]+          out `shouldContain` "--ipc=host --ipc=private")+          ["run", "create"]++  it "completes bundled capability names for run and create with --cap and -c" $+    withConfigDirs $ \user _ _ -> do+      writeBundledConfig user "[capabilities.ssh]\n[capabilities.git]\n"+      mapM_ (\(subcmd, flag) -> do+        completeCap subcmd flag "" `shouldReturn` ["git", "ssh"]+        completeCap subcmd flag "s" `shouldReturn` ["ssh"]+        completeCap subcmd flag "unknown" `shouldReturn` [])+        [(subcmd, flag) | subcmd <- ["run", "create"], flag <- ["--cap", "-c"]]++  it "completes merged capabilities once and respects system config precedence" $+    withConfigDirs $ \user system _ -> do+      writeBundledConfig user "[capabilities.bundled]\n"+      writeConfig system "[capabilities.shared]\nenv = ['SYSTEM']\n[capabilities.system]\n"+      writeConfig user "[capabilities.shared]\nenv = ['USER']\n[capabilities.user]\n"+      completeCap "run" "--cap" "" `shouldReturn` ["shared", "system", "user"]++  it "returns no capability completions when no config exists" $+    withConfigDirs $ \_ _ _ ->+      completeCap "run" "--cap" "" `shouldReturn` []+   it "returns Nothing when no config files exist, including bundled defaults" $     withConfigDirs $ \_ _ _ ->-      loadConfig `shouldReturn` Nothing+      listCaps `shouldReturn` []    it "loads bundled defaults when no user or system config exists" $     withConfigDirs $ \user _ _ -> do       writeBundledConfig user "[capabilities.bundled]\nenv = ['BUNDLED']\n"-      resolve ["bundled"] `shouldReturn` ([], ["BUNDLED"], [], [], [])+      resolve ["bundled"] `shouldReturn` emptyCapability { capEnvs = ["BUNDLED"] }       out <- encapsule ["list-caps"]       out `shouldBe` "Available capabilities:\n  bundled\n" @@ -37,7 +82,7 @@         ]       writeConfig user "[capabilities.shared]\nenv = ['USER']\n"       resolve ["shared", "bundled"] `shouldReturn`-        (["bundled-volume"], ["USER"], ["/bundled/bin"], [], [])+        emptyCapability { capVolumes = ["bundled-volume"], capEnvs = ["USER"], capPaths = ["/bundled/bin"] }    it "ignores bundled defaults when a system config exists" $     withConfigDirs $ \user _ system -> do@@ -50,7 +95,7 @@     withConfigDirs $ \user system _ -> do       writeBundledConfig user "[capabilities.bundled]\nenv = ['BUNDLED']\n"       writeConfig system ""-      (getCapabilities <$> loadConfig) `shouldReturn` Map.empty+      getCapabilities `shouldReturn` Map.empty    it "reports malformed bundled defaults when no system config exists" $     withConfigDirs $ \user _ _ -> do@@ -63,17 +108,17 @@     withConfigDirs $ \user system _ -> do       writeBundledConfig user "[broken\n"       writeConfig system "[capabilities.system]\nenv = ['SYSTEM']\n"-      resolve ["system"] `shouldReturn` ([], ["SYSTEM"], [], [], [])+      resolve ["system"] `shouldReturn` emptyCapability { capEnvs = ["SYSTEM"] }    it "loads a user config without a system config" $     withConfigDirs $ \user _ _ -> do       writeConfig user "[capabilities.user]\nenv = ['USER_ONLY']\n"-      resolve ["user"] `shouldReturn` ([], ["USER_ONLY"], [], [], [])+      resolve ["user"] `shouldReturn` emptyCapability { capEnvs = ["USER_ONLY"] }    it "loads a system config without a user config" $     withConfigDirs $ \_ system _ -> do       writeConfig system "[capabilities.system]\nenv = ['SYSTEM_ONLY']\n"-      resolve ["system"] `shouldReturn` ([], ["SYSTEM_ONLY"], [], [], [])+      resolve ["system"] `shouldReturn` emptyCapability { capEnvs = ["SYSTEM_ONLY"] }    it "merges capability fields and replaces arrays and scalar values" $     withConfigDirs $ \user system _ -> do@@ -96,23 +141,23 @@         , "env = ['USER_ONLY']"         ]       resolve ["shared"] `shouldReturn`-        ([], ["USER_ENV"], ["/system/bin"], ["user-init"], ["label=disable"])+        emptyCapability { capEnvs = ["USER_ENV"], capPaths = ["/system/bin"], capInits = ["user-init"], capSecurityOpts = ["label=disable"] }       resolve ["system", "user"] `shouldReturn`-        ([], ["SYSTEM_ONLY", "USER_ONLY"], [], [], [])+        emptyCapability { capEnvs = ["SYSTEM_ONLY", "USER_ONLY"] }    it "respects system directory order and user precedence" $     withConfigDirs $ \user first second -> do       writeConfig second "[capabilities.shared]\nenv = ['SECOND']\npath = ['/second/bin']\n"       writeConfig first "[capabilities.shared]\nenv = ['FIRST']\n"-      resolve ["shared"] `shouldReturn` ([], ["FIRST"], ["/second/bin"], [], [])+      resolve ["shared"] `shouldReturn` emptyCapability { capEnvs = ["FIRST"], capPaths = ["/second/bin"] }       writeConfig user "[capabilities.shared]\nenv = ['USER']\n"-      resolve ["shared"] `shouldReturn` ([], ["USER"], ["/second/bin"], [], [])+      resolve ["shared"] `shouldReturn` emptyCapability { capEnvs = ["USER"], capPaths = ["/second/bin"] }    it "lets a user value replace a system table" $     withConfigDirs $ \user system _ -> do       writeConfig system "[capabilities.shared]\nenv = ['SYSTEM']\n"       writeConfig user "capabilities = []\n"-      (getCapabilities <$> loadConfig) `shouldReturn` Map.empty+      getCapabilities `shouldReturn` Map.empty    it "reports the path of a malformed system config even with a user config" $     withConfigDirs $ \user system _ -> do@@ -122,9 +167,26 @@       out `shouldContain` "config parse error in"       out `shouldContain` (system </> "encapsule" </> "config.toml") -resolve :: [String] -> IO ([String], [String], [String], [String], [String])+completeCap :: String -> String -> String -> IO [String]+completeCap subcmd flag prefix =+  lines <$> encapsuleChecked+    (["--bash-completion-index", "3"] +++     concatMap (\word -> ["--bash-completion-word", word])+       ["encapsule", subcmd, flag, prefix])++emptyCapability :: Capability+emptyCapability = Capability+  { capVolumes = []+  , capEnvs = []+  , capPaths = []+  , capInits = []+  , capSecurityOpts = []+  , capPodmanOpts = []+  }++resolve :: [String] -> IO Capability resolve names = do-  caps <- getCapabilities <$> loadConfig+  caps <- getCapabilities   resolveCapabilities caps names  writeConfig :: FilePath -> String -> IO ()
+ test/EnterSpec.hs view
@@ -0,0 +1,94 @@+-- SPDX-License-Identifier: Apache-2.0++module EnterSpec (spec) where++import Control.Exception (bracket)+import Data.List (isPrefixOf)+import Data.Maybe (fromMaybe)+import System.Directory (canonicalizePath, findExecutable, removeDirectoryRecursive)+import System.Environment (lookupEnv, setEnv, unsetEnv)+import System.FilePath ((</>))+import System.Posix.Files (setFileMode)+import System.Posix.Temp (mkdtemp)+import Test.Hspec++import EncapsuleTest (encapsule, encapsuleChecked)++spec :: Spec+spec = describe "enter container lifecycle" $ do+  it "starts a stopped container before looking up its user and entering it" $+    withPodman False False $ \logFile -> do+      _ <- encapsuleChecked ["enter", "--debug"]+      calls <- lines <$> readFile logFile+      take 3 calls `shouldBe`+        [ "ps --filter name=^encapsule-.*$ --format {{.Names}}"+        , "ps -a --filter name=^encapsule-.*$ --format {{.Names}}"+        , "start encapsule-test"+        ]+      take 1 (drop 3 calls) `shouldSatisfy`+        any ("exec encapsule-test /bin/sh -c " `isPrefixOf`)+      last calls `shouldBe` enterExec++  it "enters a running container without starting it again" $+    withPodman True False $ \logFile -> do+      _ <- encapsuleChecked ["enter", "--debug"]+      calls <- lines <$> readFile logFile+      calls `shouldSatisfy` notElem "start encapsule-test"+      calls `shouldSatisfy`+        notElem "ps -a --filter name=^encapsule-.*$ --format {{.Names}}"+      last calls `shouldBe` enterExec++  it "matches an explicit container name exactly and preserves its command" $+    withPodman True False $ \logFile -> do+      _ <- encapsuleChecked ["enter", "test", "--", "bash", "--noprofile"]+      calls <- lines <$> readFile logFile+      take 1 calls `shouldBe`+        ["ps --filter name=^encapsule-test$ --format {{.Names}}"]+      last calls `shouldBe`+        "exec -it --user tester -e LANG=C.UTF-8 --workdir /home/tester encapsule-test bash --noprofile"++  it "does not attempt exec if starting the container fails" $+    withPodman False True $ \logFile -> do+      out <- encapsule ["enter", "--debug"]+      out `shouldContain` "cannot start test container"+      calls <- lines <$> readFile logFile+      last calls `shouldBe` "start encapsule-test"++enterExec :: String+enterExec = "exec -it --user tester -e LANG=C.UTF-8 --workdir /home/tester encapsule-test bash -l"++withPodman :: Bool -> Bool -> (FilePath -> IO a) -> IO a+withPodman running failStart action = do+  name <- fromMaybe "encapsule" <$> lookupEnv "ENCAPSULE"+  exe <- findExecutable name >>= maybe (fail "encapsule executable not found") canonicalizePath+  bracket (mkdtemp "/tmp/encapsule-enter-test-XXXXXX") removeDirectoryRecursive $ \dir -> do+    let logFile = dir </> "calls"+        stateFile = dir </> "running"+    writeFile stateFile (if running then "true\n" else "false\n")+    writeFile (dir </> "podman") $ unlines+      [ "#!/bin/sh"+      , "printf '%s\\n' \"$*\" >> " ++ show logFile+      , "read -r running < " ++ show stateFile+      , "case \"$1\" in"+      , "  ps) [ \"$running\" = true ] || [ \"$2\" = -a ] || exit 0"+      , "      echo encapsule-test ;;"+      , "  start) " ++ if failStart+          then "echo 'cannot start test container' >&2; exit 1 ;;"+          else "echo true > " ++ show stateFile ++ "; echo encapsule-test ;;"+      , "  exec) [ \"$running\" = true ] || exit 125"+      , "        if [ \"$2\" = encapsule-test ]; then"+      , "          printf 'tester\\n/home/tester\\n'"+      , "        fi ;;"+      , "  container) echo /home/tester ;;"+      , "  *) exit 1 ;;"+      , "esac"+      ]+    setFileMode (dir </> "podman") 0o700+    withEnv "ENCAPSULE" exe $ withEnv "PATH" dir $ action logFile++withEnv :: String -> String -> IO a -> IO a+withEnv key value action =+  bracket (lookupEnv key) restore $ \_ -> setEnv key value >> action+  where+    restore Nothing = unsetEnv key+    restore (Just old) = setEnv key old
test/Spec.hs view
@@ -16,14 +16,22 @@ import Test.Hspec  import EncapsuleTest+import qualified CommandSpec+import qualified CompletionSpec import qualified ConfigSpec+import qualified EnterSpec+import qualified VolumeSpec  main :: IO () main = hspec spec  spec :: Spec spec = do+  CommandSpec.spec+  CompletionSpec.spec   ConfigSpec.spec+  EnterSpec.spec+  VolumeSpec.spec   describe "dryrun" $ do     it "shares host networking with --network-host" $       withGenericImage $ \img -> do
+ test/VolumeSpec.hs view
@@ -0,0 +1,66 @@+-- SPDX-License-Identifier: Apache-2.0++module VolumeSpec (spec) where++import Control.Exception (bracket)+import System.Directory (createDirectoryLink, removeDirectoryRecursive)+import System.Environment (lookupEnv, setEnv, unsetEnv)+import System.FilePath ((</>))+import System.Posix.Temp (mkdtemp)+import Test.Hspec++import Volume (addSelinuxLabel, disablesSelinux, expandVolumeHost)++spec :: Spec+spec = describe "volume handling" $ do+  it "keeps automatic relabeling for ordinary user-owned directories" $+    withTempDir $ \dir ->+      addSelinuxLabel False "/nonexistent-home" "/container-home" dir+        `shouldReturn` (dir ++ ":" ++ dir ++ ":z")++  it "does not automatically relabel when SELinux separation is disabled" $+    withTempDir $ \dir -> do+      addSelinuxLabel True "/nonexistent-home" "/container-home" dir+        `shouldReturn` (dir ++ ":" ++ dir)+      addSelinuxLabel True "/nonexistent-home" "/container-home" (dir ++ ":/data:ro")+        `shouldReturn` (dir ++ ":/data:ro")++  it "preserves explicitly requested labels and overlay options" $+    withTempDir $ \dir ->+      mapM_ (\opts ->+        addSelinuxLabel True "/nonexistent-home" "/container-home" (dir ++ ":/data:" ++ opts)+          `shouldReturn` (dir ++ ":/data:" ++ opts)) ["z", "Z", "O"]++  it "recognizes both forms of raw label=disable options" $ do+    disablesSelinux ["--ipc=host", "--security-opt=label=disable"] `shouldBe` True+    disablesSelinux ["--security-opt", "label=disable"] `shouldBe` True+    disablesSelinux ["--security-opt", "label=level:s0"] `shouldBe` False++  it "does not automatically relabel system mounts even when owned by the caller" $+    mapM_ (\path ->+      addSelinuxLabel False "/nonexistent-home" "/container-home" (path ++ ":rslave")+        `shouldReturn` (path ++ ":" ++ path ++ ":rslave"))+      ["/", "/dev", "/dev/", "/etc", "/usr", "/run", "/sys", "/proc", "/var", "/tmp"]++  it "recognizes system mounts through symlinks and parent traversal" $+    withTempDir $ \dir -> do+      let alias = dir </> "device-link"+      createDirectoryLink "/dev" alias+      mapM_ (\path ->+        addSelinuxLabel False "/nonexistent-home" "/container-home" path+          `shouldReturn` (path ++ ":" ++ path)) [alias, "/tmp/../dev"]++  it "rejects empty mount sources, including empty environment expansion" $+    withTempDir $ \dir -> do+      expandVolumeHost dir "" `shouldThrow` errorCall "volume host path must not be empty"+      bracket (lookupEnv "ENCAPSULE_TEST_VOLUME_SOURCE") restore $ \_ -> do+        setEnv "ENCAPSULE_TEST_VOLUME_SOURCE" ""+        expandVolumeHost dir "$ENCAPSULE_TEST_VOLUME_SOURCE" `shouldThrow` errorCall "volume host path must not be empty"+        addSelinuxLabel True dir dir "$ENCAPSULE_TEST_VOLUME_SOURCE:/data"+          `shouldThrow` errorCall "volume host path must not be empty"+  where+    restore Nothing = unsetEnv "ENCAPSULE_TEST_VOLUME_SOURCE"+    restore (Just value) = setEnv "ENCAPSULE_TEST_VOLUME_SOURCE" value++withTempDir :: (FilePath -> IO a) -> IO a+withTempDir = bracket (mkdtemp "/tmp/encapsule-volume-test-XXXXXX") removeDirectoryRecursive