From 053e2c1364fade5a7606b22ac0b1d223afafe3d0 Mon Sep 17 00:00:00 2001 From: Alex David Date: Fri, 28 Nov 2025 11:45:17 -0800 Subject: [PATCH] Add no-die-with-parent combinator --- lib/combinators.nix | 1 + lib/combinators/base.nix | 3 -- lib/combinators/no-die-with-parent.nix | 15 +++++++ lib/jail.nix | 2 + tests/jail-nix-tests.cabal | 2 + tests/package.yaml | 2 + tests/spec/CombinatorsSpec.hs | 61 +++++++++++++++++++++++++- tests/spec/JailSpec.hs | 4 +- tests/spec/TestPrelude.hs | 53 +++++++++++++++++++--- 9 files changed, 131 insertions(+), 12 deletions(-) create mode 100644 lib/combinators/no-die-with-parent.nix diff --git a/lib/combinators.nix b/lib/combinators.nix index c187804..90e1673 100644 --- a/lib/combinators.nix +++ b/lib/combinators.nix @@ -39,6 +39,7 @@ let jail-to-host-channel = ./combinators/jail-to-host-channel.nix; mount-cwd = ./combinators/mount-cwd.nix; network = ./combinators/network.nix; + no-die-with-parent = ./combinators/no-die-with-parent.nix; no-new-session = ./combinators/no-new-session.nix; noescape = ./combinators/noescape.nix; notifications = ./combinators/notifications.nix; diff --git a/lib/combinators/base.nix b/lib/combinators/base.nix index 8dd52bc..5f7d877 100644 --- a/lib/combinators/base.nix +++ b/lib/combinators/base.nix @@ -27,8 +27,6 @@ in * Sets up a fake dev at `/dev` (Using `--dev /dev` bwrap args) * Sets up a tmpfs at `/tmp` (Using `--tmpfs /tmp` bwrap args) * Sets up a tmpfs at your home (Using `--tmpfs ~` bwrap args) - * Ensures all processes in the jail are killed when the jail exits - (Using `--die-with-parent` bwrap arg) * Adds coreutils to the package deps (`add-pkg-deps [ pkgs.coreutils ]`) * Binds `/bin/sh` from `pkgs.bash` and adds `/bin` to `$PATH` (`ro-bind "''${pkgs.bash}/bin/sh" "/bin/sh"`) @@ -45,7 +43,6 @@ in (unsafe-add-raw-args "--dev /dev") (unsafe-add-raw-args "--tmpfs /tmp") (unsafe-add-raw-args "--tmpfs ~") - (unsafe-add-raw-args "--die-with-parent") (ro-bind "${pkgs.bash}/bin/sh" "/bin/sh") (add-path "/bin") (helpers.pushState "additionalRuntimeClosures" pkgs.bash) diff --git a/lib/combinators/no-die-with-parent.nix b/lib/combinators/no-die-with-parent.nix new file mode 100644 index 0000000..53e291c --- /dev/null +++ b/lib/combinators/no-die-with-parent.nix @@ -0,0 +1,15 @@ +{ ... }: +{ + sig = "Permission"; + doc = '' + Disables `--die-with-parent` + + By default, jail-nix includes the `--die-with-parent` bwrap flag which + kills all processes within this jail when the parent process dies. Use this + combinator if you don't want this behavior. + + This may be useful if the software you are jailing forks a daemon and then + exits. + ''; + impl = state: state // { dieWithParent = false; }; +} diff --git a/lib/jail.nix b/lib/jail.nix index 2dd507c..d64d708 100644 --- a/lib/jail.nix +++ b/lib/jail.nix @@ -36,6 +36,7 @@ let argv = "\"$@\""; runtime = ""; newSession = true; + dieWithParent = true; hostname = "jail"; env = { }; namespaces = { }; @@ -75,6 +76,7 @@ let ) (s: if builtins.length s.path > 0 then set-env "PATH" (lib.concatStringsSep ":" s.path) s else s) (s: if s.newSession then unsafe-add-raw-args "--new-session" s else s) + (s: if s.dieWithParent then unsafe-add-raw-args "--die-with-parent" s else s) ( s: lib.foldr ( diff --git a/tests/jail-nix-tests.cabal b/tests/jail-nix-tests.cabal index ed673cc..2d4c039 100644 --- a/tests/jail-nix-tests.cabal +++ b/tests/jail-nix-tests.cabal @@ -28,6 +28,7 @@ test-suite spec ImportQualifiedPost LambdaCase NamedFieldPuns + NumericUnderscores OverloadedStrings QuasiQuotes ScopedTypeVariables @@ -51,4 +52,5 @@ test-suite spec , string-conversions , temporary , text + , unix default-language: Haskell2010 diff --git a/tests/package.yaml b/tests/package.yaml index 3bd4867..cfa9cdd 100644 --- a/tests/package.yaml +++ b/tests/package.yaml @@ -20,6 +20,7 @@ tests: - string-conversions - temporary - text + - unix default-extensions: - DerivingStrategies @@ -28,6 +29,7 @@ default-extensions: - ImportQualifiedPost - LambdaCase - NamedFieldPuns + - NumericUnderscores - OverloadedStrings - QuasiQuotes - ScopedTypeVariables diff --git a/tests/spec/CombinatorsSpec.hs b/tests/spec/CombinatorsSpec.hs index 51c2c69..466dba1 100644 --- a/tests/spec/CombinatorsSpec.hs +++ b/tests/spec/CombinatorsSpec.hs @@ -1,8 +1,13 @@ module CombinatorsSpec (spec) where +import Control.Concurrent (threadDelay) +import Control.Monad import Data.List.Extra +import Data.Maybe (fromJust) import Data.String.Interpolate.Util -import System.Directory.Extra (createDirectoryIfMissing, doesFileExist) +import System.Directory.Extra (createDirectoryIfMissing, doesFileExist, doesPathExist) +import System.Posix (getProcessStatus, sigKILL, signalProcess) +import System.Process qualified as Process import Test.Hspec import TestPrelude @@ -111,6 +116,60 @@ spec = parallel $ inTestM $ do |] liftIO $ (read out :: Int) `shouldSatisfy` (< 100) + describe "no-die-with-parent" $ do + let waitForChildPid :: Process.Pid -> TestM Process.Pid + waitForChildPid pid = do + children <- liftIO $ readFile ("/proc" show pid "task" show pid "children") + if children /= "" + then pure $ read children + else do + liftIO $ threadDelay 20_000 + waitForChildPid pid + + let pidExists :: Process.Pid -> TestM Bool + pidExists = liftIO . doesPathExist . ("/proc" ) . show + + let killProcess :: Process.Pid -> Bool -> TestM () + killProcess pid waitForProcessToExit = liftIO $ do + signalProcess sigKILL pid + when waitForProcessToExit $ void $ getProcessStatus True False pid + + it "kills all child processes when not specifying no-die-with-parent" $ do + (_, _, _, ph) <- + spawnNixDrv + [i| + let script = sh "nohup sleep inf"; + in jail "test" script null + |] + outerBwrapPid <- liftIO $ fromJust <$> Process.getPid ph + innerBwrapPid <- waitForChildPid outerBwrapPid + bashPid <- waitForChildPid innerBwrapPid + sleepPid <- waitForChildPid bashPid + killProcess outerBwrapPid True + pidExists outerBwrapPid `shouldEventuallyReturn` False + pidExists innerBwrapPid `shouldEventuallyReturn` False + pidExists bashPid `shouldEventuallyReturn` False + pidExists sleepPid `shouldEventuallyReturn` False + + it "does not kill child processes when specifying no-die-with-parent" $ do + (_, _, _, ph) <- + spawnNixDrv + [i| + let script = sh "nohup sleep inf"; + in jail "test" script (c: [ c.no-die-with-parent ]) + |] + outerBwrapPid <- liftIO $ fromJust <$> Process.getPid ph + innerBwrapPid <- waitForChildPid outerBwrapPid + bashPid <- waitForChildPid innerBwrapPid + sleepPid <- waitForChildPid bashPid + killProcess outerBwrapPid True + pidExists outerBwrapPid `shouldEventuallyReturn` False + liftIO $ threadDelay 500_000 + pidExists innerBwrapPid `shouldReturnTestM` True + pidExists bashPid `shouldReturnTestM` True + pidExists sleepPid `shouldReturnTestM` True + killProcess sleepPid False + describe "open-urls-in-browser" $ do it "exposes a $BROWSER in the jail that calls $BROWSER outside of the jail" $ do tmpDir <- getTestDir diff --git a/tests/spec/JailSpec.hs b/tests/spec/JailSpec.hs index 6c23357..f7e9de5 100644 --- a/tests/spec/JailSpec.hs +++ b/tests/spec/JailSpec.hs @@ -31,7 +31,7 @@ spec = parallel $ inTestM $ do it "provides `sh` in the default path" $ do [i| jail "test" (sh ''sh -c "echo hello"'') [] |] - `shouldOutput` "hello\n" + `shouldOutput` "hello\n" describe "forwarding package overrides to the jailed derivation" $ do -- This is a nix expression of a package that prints out the value of an @@ -111,7 +111,7 @@ spec = parallel $ inTestM $ do in jail' "test" "some-entrypoint" [] |] - `shouldOutput` "--unshare-user --unshare-ipc --unshare-pid --unshare-net --unshare-uts --unshare-cgroup --new-session -- some-entrypoint" + `shouldOutput` "--unshare-user --unshare-ipc --unshare-pid --unshare-net --unshare-uts --unshare-cgroup --new-session --die-with-parent -- some-entrypoint" describe "sandboxed nix store" $ do let checkRuntimeDepIsExposed :: Bool -> String -> TestM () diff --git a/tests/spec/TestPrelude.hs b/tests/spec/TestPrelude.hs index cef024b..f3ec87f 100644 --- a/tests/spec/TestPrelude.hs +++ b/tests/spec/TestPrelude.hs @@ -10,14 +10,19 @@ module TestPrelude inTestM, liftIO, runNixDrv, - shouldOutput, + spawnNixDrv, toNixString, void, withEnv, lifted, + -- expectations + shouldEventuallyReturn, + shouldOutput, + shouldReturnTestM, ) where +import Control.Concurrent (threadDelay) import Control.Monad import Control.Monad.Extra (mapMaybeM) import Control.Monad.IO.Class (liftIO) @@ -29,9 +34,11 @@ import Data.Map qualified as Map import Data.Maybe (fromJust) import Data.String.Conversions import Data.String.Interpolate (i) +import GHC.IO.Handle (Handle) import System.Environment (lookupEnv) import System.FilePath (()) import System.IO.Temp (withSystemTempDirectory) +import System.Process (CreateProcess, ProcessHandle, createProcess) import System.Process qualified as Process import Test.Hspec import Test.Hspec.Core.Spec qualified @@ -55,6 +62,9 @@ lifted io action = do ctx <- ask liftIO $ io $ flip runReaderT ctx . testMReaderT . action +lifted' :: (IO x -> IO y) -> TestM x -> TestM y +lifted' fn action = lifted (fn . ($ ())) (const action) + instance Example (TestM ()) where type Arg (TestM ()) = Context evaluateExample test _ hook _ = do @@ -94,15 +104,26 @@ toNixString s = withEnv :: String -> String -> TestM () -> TestM () withEnv name value = local $ \ctx -> ctx {env = Map.insert name value (env ctx)} -runNixDrv :: String -> TestM String -runNixDrv nixDrvExpr = do +mkNixDrvProccess :: String -> TestM CreateProcess +mkNixDrvProccess nixDrvExpr = do (exe :: String, drvPath :: FilePath) <- evalNixExpr [i| let d = #{nixDrvExpr}; in [(lib.getExe d) d.drvPath] |] void $ buildNixDrvPath drvPath env <- asks env - let p = (Process.proc exe []) {Process.env = Just $ Map.toList env} - liftIO $ Process.readCreateProcess p "" + pure $ + (Process.proc exe []) + { Process.env = Just $ Map.toList env, + Process.std_in = Process.CreatePipe, + Process.std_out = Process.CreatePipe, + Process.std_err = Process.CreatePipe + } + +runNixDrv :: String -> TestM String +runNixDrv = liftIO . flip Process.readCreateProcess "" <=< mkNixDrvProccess + +spawnNixDrv :: String -> TestM (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle) +spawnNixDrv = liftIO . createProcess <=< mkNixDrvProccess buildNixDrvPath :: FilePath -> TestM FilePath buildNixDrvPath drvPath = do @@ -142,7 +163,27 @@ evalNixExpr nixExpr = do ] "" -shouldOutput :: String -> String -> TestM () +shouldOutput :: (HasCallStack) => String -> String -> TestM () shouldOutput nixDrvExpr expectedOutput = do out <- runNixDrv nixDrvExpr liftIO $ out `shouldBe` expectedOutput + +shouldReturnTestM :: (HasCallStack, Show a, Eq a) => TestM a -> a -> TestM () +shouldReturnTestM action expected = lifted' (`shouldReturn` expected) action + +shouldEventuallyReturn :: (HasCallStack, Eq a, Show a) => TestM a -> a -> TestM () +shouldEventuallyReturn action expected = go 0 + where + delay = 20_000 + maxRetries = 5_000_000 `div` delay + go :: Int -> TestM () + go retryCount = do + result <- action + if result == expected + then pure () + else do + if retryCount > maxRetries + then liftIO $ result `shouldBe` expected + else do + liftIO $ threadDelay delay + go $ retryCount + 1