diff --git a/lib/combinators.nix b/lib/combinators.nix index 4b83d55..f214924 100644 --- a/lib/combinators.nix +++ b/lib/combinators.nix @@ -1,4 +1,4 @@ -pkgs: let +pkgs: jail: let inherit (pkgs) lib; helpers = import ./helpers.nix pkgs; in rec { @@ -902,15 +902,81 @@ in rec { ; }; + dbus = { + sig = "{ own? :: [String], talk? :: [String], see? :: [String], call? :: [String], broadcast? :: [String] } -> Permission"; + doc = '' + Grants access to dbus, using + [`xdg-dbus-proxy`](https://github.com/flatpak/xdg-dbus-proxy) (inside a + jail itself) to filter messages that can be sent/received. + + All of the args in the passed attrset turn into arguments for + `xdg-dbus-proxy`. They are all optional. + + Example: + ``` + dbus { + talk = [ + "ca.desrt.dconf" + "org.a11y.Bus" + "org.freedesktop.DBus" + "org.freedesktop.portal.*" + "org.gtk.vfs" + "org.gtk.vfs.*" + ]; + } + ``` + ''; + __functor = _: + { own ? [], talk ? [], see ? [], call ? [], broadcast ? [] }: + let + proxy = jail "xdg-dbus-proxy" pkgs.xdg-dbus-proxy [ + unsafe-dbus + (readwrite (noescape "\"$PROXIED_DBUS_SOCKET_DIR\"")) + ]; + + args = [ "--filter" ] + ++ map (id: "--own=${lib.escapeShellArg id}") own + ++ map (id: "--talk=${lib.escapeShellArg id}") talk + ++ map (id: "--see=${lib.escapeShellArg id}") see + ++ map (id: "--call=${lib.escapeShellArg id}") call + ++ map (id: "--broadcast=${lib.escapeShellArg id}") broadcast; + in + compose [ + (add-runtime '' + PROXIED_DBUS_SOCKET_DIR=$(mktemp -d) + export PROXIED_DBUS_SOCKET_DIR + PROXIED_DBUS_SOCKET="$PROXIED_DBUS_SOCKET_DIR/socket" + mkfifo "$PROXIED_DBUS_SOCKET_DIR/ready" + exec {XDG_DBUS_PROXY_READY_FD}<>"$PROXIED_DBUS_SOCKET_DIR/ready" + ${lib.getExe proxy} \ + "$DBUS_SESSION_BUS_ADDRESS" \ + "$PROXIED_DBUS_SOCKET" \ + --fd="$XDG_DBUS_PROXY_READY_FD" \ + ${lib.concatStringsSep " " args} \ + & + PROXY_PID=$! + IFS= read -rn1 -u "$XDG_DBUS_PROXY_READY_FD" + '') + (add-cleanup '' + kill "$PROXY_PID" + if [ -e "''${PROXIED_DBUS_SOCKET_DIR-}" ]; then + rm -rf "$PROXIED_DBUS_SOCKET_DIR" + fi + '') + (readwrite (noescape "\"$PROXIED_DBUS_SOCKET_DIR\"")) + (set-env "DBUS_SESSION_BUS_ADDRESS" (noescape "\"unix:path=$PROXIED_DBUS_SOCKET\"")) + ] + ; + }; + unsafe-dbus = { sig = "Permission"; doc = '' Exposes D-Bus to the jailed program. - This does no message filtering so it is marked as unsafe. In the future - this library will include a combinator that uses - [xdg-dbus-proxy](https://github.com/flatpak/xdg-dbus-proxy) to specify a - set of allowed messages. + This does no message filtering so it is marked as unsafe. If you want + more control over the messages that can be sent/received, consider using + the [dbus](#dbus) combinator instead. ''; __functor = _: compose [ diff --git a/lib/jail.nix b/lib/jail.nix index f2ed8af..07031fc 100644 --- a/lib/jail.nix +++ b/lib/jail.nix @@ -5,7 +5,7 @@ }: let inherit (pkgs) lib; - builtinCombinators = import ./combinators.nix pkgs; + builtinCombinators = import ./combinators.nix pkgs jail; allCombinators = builtinCombinators // additionalCombinators builtinCombinators; @@ -16,10 +16,7 @@ if t == "null" then [] else throw "Unknown combinator type ${t}. Must be a function, list, or null"; -in { - combinators = allCombinators; - - __functor = _: name: exe: permissions: let + jail = name: exe: permissions: let initialState = { name = name; cmd = lib.getExe bubblewrapPackage; @@ -84,4 +81,8 @@ in { (jailed: if exe ? man then jailed // { inherit (exe) man; } else jailed) ] ); + +in { + combinators = allCombinators; + __functor = _: jail; } diff --git a/tests/jail-nix-tests.cabal b/tests/jail-nix-tests.cabal index 8c02b60..f1c1ead 100644 --- a/tests/jail-nix-tests.cabal +++ b/tests/jail-nix-tests.cabal @@ -13,6 +13,7 @@ test-suite spec main-is: Spec.hs other-modules: CombinatorsSpec + DBusCombinatorsSpec JailSpec TestPrelude Paths_jail_nix_tests @@ -23,7 +24,9 @@ test-suite spec FlexibleInstances GeneralizedNewtypeDeriving ImportQualifiedPost + LambdaCase NamedFieldPuns + OverloadedStrings QuasiQuotes ScopedTypeVariables TupleSections @@ -34,6 +37,7 @@ test-suite spec , base , bytestring , containers + , dbus , extra , filepath , hspec diff --git a/tests/package.yaml b/tests/package.yaml index 1418dad..8293d0f 100644 --- a/tests/package.yaml +++ b/tests/package.yaml @@ -8,6 +8,7 @@ tests: - base - bytestring - containers + - dbus - extra - filepath - hspec @@ -23,7 +24,9 @@ default-extensions: - FlexibleInstances - GeneralizedNewtypeDeriving - ImportQualifiedPost + - LambdaCase - NamedFieldPuns + - OverloadedStrings - QuasiQuotes - ScopedTypeVariables - TupleSections diff --git a/tests/spec/DBusCombinatorsSpec.hs b/tests/spec/DBusCombinatorsSpec.hs new file mode 100644 index 0000000..b8cf165 --- /dev/null +++ b/tests/spec/DBusCombinatorsSpec.hs @@ -0,0 +1,246 @@ +module DBusCombinatorsSpec (spec) where + +import Control.Concurrent (modifyMVar_, newMVar, readMVar) +import Control.Exception (bracket) +import DBus qualified +import DBus.Client qualified as DBus +import Test.Hspec +import TestPrelude + +spec :: Spec +spec = inTestM $ do + let mockBusName = "foo.bar" + let mockMethod = + MockDBusMethod + { objPath = "/foo/bar/baz", + ifaceName = "foo.bar.Iface", + methodName = "Demo" + } + + describe "unsafe-dbus" $ do + it "gives unfiltered access to DBus method calls" $ do + (sendDBusOutput, methodCalls) <- withDBusClient mockBusName $ \client -> do + withMockDBusMethodHandler client mockMethod "some return value" $ do + runNixDrv + [i| + jail "send-dbus" (#{callDBusMethodNixDrv mockBusName mockMethod "some arg"}) (c: [ + c.unsafe-dbus + ]) + |] + liftIO $ do + sendDBusOutput `shouldBe` " some return value" + methodCalls `shouldBe` ["some arg"] + + it "gives unfiltered access to DBus signals" $ do + (_, signals) <- withDBusClient mockBusName $ \client -> do + withMockDBusSignalHandler client mockMethod $ do + runNixDrv + [i| + jail "send-dbus" (#{sendDBusSignalNixDrv mockBusName mockMethod "some message"}) (c: [ + c.unsafe-dbus + ]) + |] + liftIO $ signals `shouldBe` ["some message"] + + describe "dbus" $ do + describe "sending signals from within the jail" $ do + it "filters all signals if there are no rules" $ do + (_, signals) <- withDBusClient mockBusName $ \client -> do + withMockDBusSignalHandler client mockMethod $ do + runNixDrv + [i| + jail "send-dbus" (#{sendDBusSignalNixDrv mockBusName mockMethod "some arg"}) (c: [ + (c.dbus {}) + ]) + |] + liftIO $ signals `shouldBe` [] + + describe "calling methods from within the jail" $ do + it "allows method calls that match the call filter rules" $ do + (sendDBusOutput, methodCalls) <- withDBusClient mockBusName $ \client -> do + withMockDBusMethodHandler client mockMethod "some return value" $ do + runNixDrv + [i| + jail "send-dbus" (#{callDBusMethodNixDrv mockBusName mockMethod "some arg"}) (c: [ + (c.dbus { + call = [ #{toNixString $ toProxyRule mockBusName mockMethod} ]; + }) + ]) + |] + liftIO $ do + sendDBusOutput `shouldBe` " some return value" + methodCalls `shouldBe` ["some arg"] + + it "allows method calls if the receiving bus has `own` privileges" $ do + (sendDBusOutput, methodCalls) <- withDBusClient mockBusName $ \client -> do + withMockDBusMethodHandler client mockMethod "some return value" $ do + runNixDrv + [i| + jail "send-dbus" (#{callDBusMethodNixDrv mockBusName mockMethod "some arg"}) (c: [ + (c.dbus { + own = [ #{toNixString $ DBus.formatBusName mockBusName} ]; + }) + ]) + |] + liftIO $ do + sendDBusOutput `shouldBe` " some return value" + methodCalls `shouldBe` ["some arg"] + + it "allows method calls if the receiving bus has `talk` privileges" $ do + (sendDBusOutput, methodCalls) <- withDBusClient mockBusName $ \client -> do + withMockDBusMethodHandler client mockMethod "some return value" $ do + runNixDrv + [i| + jail "send-dbus" (#{callDBusMethodNixDrv mockBusName mockMethod "some arg"}) (c: [ + (c.dbus { + talk = [ #{toNixString $ DBus.formatBusName mockBusName} ]; + }) + ]) + |] + liftIO $ do + sendDBusOutput `shouldBe` " some return value" + methodCalls `shouldBe` ["some arg"] + + it "filters method calls if the receiving bus only has `see` privileges" $ do + (sendDBusOutput, methodCalls) <- withDBusClient mockBusName $ \client -> do + withMockDBusMethodHandler client mockMethod "some return value" $ do + runNixDrv + [i| + jail "send-dbus" (#{callDBusMethodNixDrv mockBusName mockMethod "some arg"}) (c: [ + (c.dbus { + see = [ #{toNixString $ DBus.formatBusName mockBusName} ]; + }) + ]) + |] + liftIO $ do + sendDBusOutput `shouldBe` "Failed to call dbus method\n" + methodCalls `shouldBe` [] + + it "filters all method calls if there are no rules" $ do + (sendDBusOutput, methodCalls) <- withDBusClient mockBusName $ \client -> do + withMockDBusMethodHandler client mockMethod "some return value" $ do + runNixDrv + [i| + jail "send-dbus" (#{callDBusMethodNixDrv mockBusName mockMethod "some arg"}) (c: [ + (c.dbus { }) + ]) + |] + liftIO $ do + sendDBusOutput `shouldBe` "Failed to call dbus method\n" + methodCalls `shouldBe` [] + + it "filters method calls if the rules do not match" $ do + (sendDBusOutput, methodCalls) <- withDBusClient mockBusName $ \client -> do + withMockDBusMethodHandler client mockMethod "some return value" $ do + let otherMockMethod = mockMethod {objPath = "/some/unrelated/object/path"} + runNixDrv + [i| + jail "send-dbus" (#{callDBusMethodNixDrv mockBusName mockMethod "some arg"}) (c: [ + (c.dbus { + call = [ #{toNixString $ toProxyRule mockBusName otherMockMethod} ]; + }) + ]) + |] + liftIO $ do + sendDBusOutput `shouldBe` "Failed to call dbus method\n" + methodCalls `shouldBe` [] + +-- * DBus test helpers + +withDBusClient :: DBus.BusName -> (DBus.Client -> TestM a) -> TestM a +withDBusClient busName action = do + let setup = do + client <- liftIO DBus.connectSession + DBus.requestName client busName [DBus.nameDoNotQueue] >>= \case + DBus.NamePrimaryOwner -> pure client + reply -> error $ "Got unexpected requestName reply: " <> show reply + lifted (bracket setup DBus.disconnect) action + +data MockDBusMethod = MockDBusMethod + { objPath :: DBus.ObjectPath, + ifaceName :: DBus.InterfaceName, + methodName :: DBus.MemberName + } + +-- | Returns a RULE that can be passed into `--call` or `--broadcast` that +-- matches the given MockDBusMethod. See XDG-DBUS-PROXY(1). +toProxyRule :: DBus.BusName -> MockDBusMethod -> String +toProxyRule busName mockMethod = + DBus.formatBusName busName + <> "=" + <> DBus.formatInterfaceName (ifaceName mockMethod) + <> "." + <> DBus.formatMemberName (methodName mockMethod) + <> "@" + <> DBus.formatObjectPath (objPath mockMethod) + +withMockDBusMethodHandler :: DBus.Client -> MockDBusMethod -> String -> TestM a -> TestM (a, [String]) +withMockDBusMethodHandler client (MockDBusMethod {objPath, ifaceName, methodName}) returnValue action = do + recordedMethodCalls <- liftIO $ newMVar [] + let mockMethod :: String -> IO String + mockMethod arg = do + modifyMVar_ recordedMethodCalls (pure . (<> [arg])) + pure returnValue + liftIO + $ DBus.export + client + objPath + $ DBus.defaultInterface + { DBus.interfaceName = ifaceName, + DBus.interfaceMethods = [DBus.autoMethod methodName mockMethod] + } + (,) <$> action <*> liftIO (readMVar recordedMethodCalls) + +withMockDBusSignalHandler :: DBus.Client -> MockDBusMethod -> TestM a -> TestM (a, [String]) +withMockDBusSignalHandler client (MockDBusMethod {objPath}) action = do + recordedSignals <- liftIO $ newMVar [] + let onSignal sig = do + let body = case DBus.fromVariant <$> DBus.signalBody sig of + [Just s] -> s + _ -> error $ "Expected string signal body, got: " <> show (DBus.signalBody sig) + modifyMVar_ recordedSignals (pure . (<> [body])) + let matchRule = DBus.matchAny {DBus.matchPath = Just objPath} + void $ liftIO $ DBus.addMatch client matchRule onSignal + (,) <$> action <*> liftIO (readMVar recordedSignals) + +-- | Returns a nix expression that calls the specified (String -> String) DBus method +callDBusMethodNixDrv :: DBus.BusName -> MockDBusMethod -> String -> String +callDBusMethodNixDrv busName (MockDBusMethod {objPath, ifaceName, methodName}) arg = + [i| + sh '' + if ! \\ + ${pkgs.dbus}/bin/dbus-send \\ + --type=method_call \\ + --print-reply=literal \\ + --dest=#{toNixShellArg $ DBus.formatBusName busName} \\ + #{toNixShellArg $ DBus.formatObjectPath objPath} \\ + #{toNixShellArg $ DBus.formatInterfaceName ifaceName}.#{toNixShellArg $ DBus.formatMemberName methodName} \\ + string:#{toNixShellArg arg} \\ + ; then + echo "Failed to call dbus method" + fi + '' + |] + where + toNixShellArg :: String -> String + toNixShellArg s = "${lib.escapeShellArg " <> toNixString s <> "}" + +sendDBusSignalNixDrv :: DBus.BusName -> MockDBusMethod -> String -> String +sendDBusSignalNixDrv busName (MockDBusMethod {objPath, ifaceName}) msg = do + [i| + sh '' + if ! \\ + ${pkgs.dbus}/bin/dbus-send \\ + --type=signal \\ + --dest=#{toNixShellArg $ DBus.formatBusName busName} \\ + #{toNixShellArg $ DBus.formatObjectPath objPath} \\ + #{toNixShellArg $ DBus.formatInterfaceName ifaceName} \\ + string:#{toNixShellArg msg} \\ + ; then + echo "Failed to call dbus method" + fi + '' + |] + where + toNixShellArg :: String -> String + toNixShellArg s = "${lib.escapeShellArg " <> toNixString s <> "}" diff --git a/tests/spec/TestPrelude.hs b/tests/spec/TestPrelude.hs index de5e619..d490607 100644 --- a/tests/spec/TestPrelude.hs +++ b/tests/spec/TestPrelude.hs @@ -14,13 +14,14 @@ module TestPrelude toNixString, void, withEnv, + lifted, ) where import Control.Monad import Control.Monad.Extra (mapMaybeM) import Control.Monad.IO.Class (liftIO) -import Control.Monad.Reader (MonadIO, MonadReader, ReaderT, asks, local, runReaderT) +import Control.Monad.Reader (MonadIO, MonadReader, ReaderT, ask, asks, local, runReaderT) import Data.Aeson qualified as Aeson import Data.Function ((&)) import Data.List.Extra @@ -49,6 +50,11 @@ newtype TestM a = TestM {testMReaderT :: ReaderT Context IO a} MonadReader Context ) +lifted :: ((a -> IO b) -> IO c) -> (a -> TestM b) -> TestM c +lifted io action = do + ctx <- ask + liftIO $ io $ flip runReaderT ctx . testMReaderT . action + instance Example (TestM ()) where type Arg (TestM ()) = Context evaluateExample test _ hook _ = do @@ -67,7 +73,9 @@ inTestM = aroundWith $ \action () -> do (\(name, getVal) -> ((name,) <$>) <$> getVal) [ ("HOME", lookupEnv "HOME"), ("LANG", pure $ Just "en_US.UTF-8"), - ("PATH", lookupEnv "PATH") + ("PATH", lookupEnv "PATH"), + ("DBUS_SESSION_BUS_ADDRESS", lookupEnv "DBUS_SESSION_BUS_ADDRESS"), + ("XDG_RUNTIME_DIR", lookupEnv "XDG_RUNTIME_DIR") ] action $ Context diff --git a/website/flake.nix b/website/flake.nix index 424f84a..f71a57e 100644 --- a/website/flake.nix +++ b/website/flake.nix @@ -30,11 +30,10 @@ ''; combinatorDocs = let - allCombinators = import ../lib/combinators.nix { - pkgs = throw "Docs must not depend on pkgs"; - lib = throw "Docs must not depend on lib"; - helpers = throw "Docs must not depend on helpers"; - }; + allCombinators = import ../lib/combinators.nix + (throw "Docs must not depend on args") + (throw "Docs must not depend on args") + ; formatSection = filter: lib.pipe allCombinators [