{-# LANGUAGE CPP #-}-- | Which store a command uses ("Nix.Daemon.StoreChoice"): what a store-- reference names, which of the three sources of one wins, what a daemon-- is sent of it and how each command's @--store@ sets the setting, which-- are pure; the choice @auto@ makes over a recording probe; and the two-- questions it asks of the machine, whether this process can keep a-- store's state directory ('probeStoreWriting') and whether anything is at-- the daemon's address ('addressPresence'), asked of real directories,-- sockets and pipes.module Test.StoreChoice ( testStoreChoice, testStoreChoiceIO, )whereimport Control.Monad.State.Strict (State, modify', runState)import DaemonLink (daemonAddress)import qualified Data.ByteString as BSimport qualified Data.Map.Strict as Mapimport qualified Data.Text as Timport qualified Data.Text.Encoding as TEimport Nix.Cli.Args (CliOpts (..), parseArgs, storeFlagOf)import Nix.Daemon.ClientStore (DaemonAddress (..), daemonStoreName)import Nix.Daemon.Dial (AddressPresence (..), addressPresence)import qualified Nix.Daemon.Listen as Listenimport Nix.Daemon.StoreChoice (StoreChoice (..), StoreFlag (..), StoreProbe (..), StoreTarget (..), chooseStore, parseStoreTarget, parseStoreTargetOn, storeOverride, storeReference)import Nix.Eval.Policy (PathRules (..))import Nix.Store.Access (StoreWriting (..), probeStoreWriting)import System.Directory (createDirectoryIfMissing, getTemporaryDirectory)import System.FilePath ((</>))import qualified System.Info as SIimport Test.Daemon (withSocketDaemon)import Test.Harness (TestResult (..), allFailures, assertEqual, forceRemoveIfExists, runTest, runTestM)import qualified Test.QuickCheck as QC#if defined(mingw32_HOST_OS)import DirDacl (processUserSid)import Nix.Store.Access (createStateDirectory)import Test.WindowsSandbox (makeDirectory)#elseimport Control.Exception (IOException, bracket_, try)import qualified Data.ByteString.Char8 as BS8import System.IO.Error (ioeGetErrorString)import System.Posix.Files (createSymbolicLink, setFileMode)import System.Posix.User (getEffectiveUserID)#endif-- ----------------------------------------------------------------------------- What a store reference names, and the choice-- ----------------------------------------------------------------------------- | A question the machine was asked, as the recording probe notes it.data Asked = AskedWriting | AskedPresence !BS.ByteString deriving (Eq, Show)-- | A probe that answers as it is told and notes each question, the latest-- first.recordingProbe :: StoreWriting -> AddressPresence -> StoreProbe (State [Asked])recordingProbe writing presence = StoreProbe { probeWriting = modify' (AskedWriting :) >> pure writing, probePresence = \address -> modify' (AskedPresence address :) >> pure presence }-- | The daemon's default address, in these tests.defaultAddress :: BS.ByteStringdefaultAddress = "/run/default-socket"-- | What 'chooseStore' answers over a recording probe, and what it asked.choose :: StoreWriting -> AddressPresence -> StoreTarget -> (StoreChoice, [Asked])choose writing presence target = runState (chooseStore (recordingProbe writing presence) defaultAddress target) []-- | The pure part: the references, their precedence and the choice.testStoreChoice :: IO [Bool]testStoreChoice = do putStrLn "daemon/store-choice" sequence [ runTest "--store, the store setting and NIX_REMOTE name auto, the daemon, a socket, the local store or a directory, as upstream reads them" $ allFailures [ assertEqual "nothing" (Right AutoStore) (posix ""), assertEqual "auto" (Right AutoStore) (posix "auto"), assertEqual "daemon" (Right (DaemonSocket Nothing)) (posix "daemon"), assertEqual "local" (Right (LocalStore Nothing)) (posix "local"), assertEqual "unix:// alone is the default socket" (Right (DaemonSocket Nothing)) (posix "unix://"), assertEqual "a socket" (Right (DaemonSocket (Just "/run/socket"))) (posix "unix:///run/socket"), assertEqual "percent-decoded" (Right (DaemonSocket (Just "/run/my socket"))) (posix "unix:///run/my%20socket"), assertEqual "a decoded slash splits" (Right (DaemonSocket (Just "/run/a/b"))) (posix "unix:///run/a%2Fb"), assertEqual "repeated separators and . fold" (Right (DaemonSocket (Just "/run/b"))) (posix "unix:///run//a/./../b"), assertEqual ".. at the root is dropped" (Right (DaemonSocket (Just "/b"))) (posix "unix:///../b"), assertEqual "a directory" (Right (LocalStore (Just "/srv/store"))) (posix "/srv/store"), assertEqual "a relative directory in the working directory" (Right (LocalStore (Just "./store"))) (posix "./store"), assertEqual "a relative directory" (Right (LocalStore (Just "srv/store"))) (posix "srv/store"), assertEqual "a path with a colon" (Right (LocalStore (Just "/srv/a:b"))) (posix "/srv/a:b") ], runTest "a word with no path separator that is none of the named forms is refused as a store that cannot be parsed" $ allFailures [ assertEqual "a word" (Left "Cannot parse Nix store 'store'") (posix "store"), assertEqual "a misspelt daemon" (Left "Cannot parse Nix store 'daemno'") (posix "daemno"), assertEqual "a scheme with nothing after it" (Left "Cannot parse Nix store 'unix'") (posix "unix"), assertEqual "the names are case sensitive" (Left "Cannot parse Nix store 'Auto'") (posix "Auto"), assertEqual "a backslash separates nothing on POSIX" (Left "Cannot parse Nix store 'C:\\nix\\store'") (posix "C:\\nix\\store"), assertEqual "a word on Windows" (Left "Cannot parse Nix store 'store'") (windows "store") ], runTest "unix: with one slash is the socket, and a literal space in an address is refused, as upstream reads them" $ allFailures [ assertEqual "one slash" (Right (DaemonSocket (Just "/run/socket"))) (posix "unix:/run/socket"), assertEqual "no path" (Right (DaemonSocket Nothing)) (posix "unix:"), assertEqual "a space in the path" (Left "Cannot parse Nix store 'unix:///run/my socket'") (posix "unix:///run/my socket"), assertEqual "a space in the authority" (Left "Cannot parse Nix store 'unix://my socket'") (posix "unix://my socket") ], runTest "a relative socket path is refused in upstream's words" $ assertEqual "relative" (Left "not an absolute path: \"run/socket\"") (posix "unix://run/socket"), runTest "a store URL's settings and any other scheme are refused" $ allFailures [ assertEqual "a query on daemon" (Left "store settings in a store's URL are not supported by nova-nix: 'daemon?trusted=1'") (posix "daemon?trusted=1"), assertEqual "a query on a socket" (Left "store settings in a store's URL are not supported by nova-nix: 'unix:///run/socket?x=y'") (posix "unix:///run/socket?x=y"), assertEqual "a query on a directory" (Left "store settings in a store's URL are not supported by nova-nix: '/srv/store?x=y'") (posix "/srv/store?x=y"), assertEqual "another scheme" (Left "store 'ssh://host' is not one nova-nix opens: it takes auto, daemon, local, unix://PATH or a store directory") (posix "ssh://host"), assertEqual "a file URL" (Left "store 'file:///srv/cache' is not one nova-nix opens: it takes auto, daemon, local, unix://PATH or a store directory") (posix "file:///srv/cache") ], runTest "on Windows a unix:// address is the pipe's path as written, and a drive path or an extended-length path is a directory" $ allFailures [ assertEqual "a pipe" (Right (DaemonSocket (Just "\\\\.\\pipe\\nova-nix-daemon"))) (windows "unix://\\\\.\\pipe\\nova-nix-daemon"), assertEqual "no address" (Right (DaemonSocket Nothing)) (windows "unix://"), assertEqual "a drive path" (Right (LocalStore (Just "C:\\nix\\store"))) (windows "C:\\nix\\store"), assertEqual "a drive path with a slash, which is no URL" (Right (LocalStore (Just "C:/nix/store"))) (windows "C:/nix/store"), assertEqual "an extended-length path, whose prefix holds a ?" (Right (LocalStore (Just "\\\\?\\C:\\nix\\store"))) (windows "\\\\?\\C:\\nix\\store"), assertEqual "an extended-length UNC path" (Right (LocalStore (Just "\\\\?\\UNC\\host\\share"))) (windows "\\\\?\\UNC\\host\\share"), assertEqual "a relative path with a backslash" (Right (LocalStore (Just "srv\\store"))) (windows "srv\\store"), assertEqual "a query on a drive path" (Left "store settings in a store's URL are not supported by nova-nix: 'C:\\nix\\store?x=y'") (windows "C:\\nix\\store?x=y"), assertEqual "daemon" (Right (DaemonSocket Nothing)) (windows "daemon"), assertEqual "an address is not percent-decoded" (Right (DaemonSocket (Just "\\\\.\\pipe\\a%20b"))) (windows "unix://\\\\.\\pipe\\a%20b") ], runTest "--store overrides the store setting, which overrides NIX_REMOTE" $ allFailures [ assertEqual "all three" "flag" (storeReference (Just "flag") (Just "setting") (Just "environment")), assertEqual "setting and environment" "setting" (storeReference Nothing (Just "setting") (Just "environment")), assertEqual "environment" "environment" (storeReference Nothing Nothing (Just "environment")), assertEqual "none" "auto" (storeReference Nothing Nothing Nothing), assertEqual "an empty setting overrides the environment" "" (storeReference Nothing (Just "") (Just "daemon")), assertEqual "an empty flag overrides both" "" (storeReference (Just "") (Just "daemon") (Just "local")), assertEqual "an empty setting reads as auto" (Right AutoStore) (parseStoreTarget (storeReference Nothing (Just "") (Just "daemon"))) ], runTest "a daemon is told the store setting when a source set it, rendered as the setting renders it" $ allFailures [ assertEqual "NIX_REMOTE only gives the setting's default" none (sent ValueFlag Nothing Nothing (Just "daemon")), assertEqual "nothing set" none (sent ValueFlag Nothing Nothing Nothing), assertEqual "an empty setting is auto" (told "auto") (sent ValueFlag Nothing (Just "") Nothing), assertEqual "auto" (told "auto") (sent ValueFlag Nothing (Just "auto") Nothing), assertEqual "daemon" (told "daemon") (sent ValueFlag Nothing (Just "daemon") Nothing), assertEqual "local" (told "local") (sent ValueFlag Nothing (Just "local") Nothing), assertEqual "the default socket" (told "unix://") (sent ValueFlag Nothing (Just "unix://") Nothing), assertEqual "a socket with one slash is rendered with three" (told "unix:///run/socket") (sent ValueFlag Nothing (Just "unix:/run/socket") Nothing), assertEqual "a socket's path is not folded" (told "unix:///run//a/../b") (sent ValueFlag Nothing (Just "unix:///run//a/../b") Nothing), assertEqual "a socket's path keeps its encoding" (told "unix:///run/my%20socket") (sent ValueFlag Nothing (Just "unix:///run/my%20socket") Nothing), assertEqual "a directory is opened directly, so nothing is sent" none (sent ValueFlag Nothing (Just "/srv/store") Nothing), assertEqual "a reference nova-nix does not open is refused, as it is where the store is chosen" (Left "store 'ssh://host' is not one nova-nix opens: it takes auto, daemon, local, unix://PATH or a store directory") (sent ValueFlag Nothing (Just "ssh://host") Nothing), assertEqual "a pipe on Windows is as written" (told "unix://\\\\.\\pipe\\x") (storeOverride WindowsPaths ValueFlag Nothing (Just "unix://\\\\.\\pipe\\x") Nothing) ], runTest "a value flag replaces the setting's value where a source set it, and a setting flag sets the setting itself" $ allFailures [ assertEqual "a value flag over a setting" (told "daemon") (sent ValueFlag (Just "daemon") (Just "local") Nothing), assertEqual "an empty value flag over a setting" (told "auto") (sent ValueFlag (Just "") (Just "local") Nothing), assertEqual "a value flag alone sends nothing" none (sent ValueFlag (Just "daemon") Nothing Nothing), assertEqual "a value flag and NIX_REMOTE send nothing" none (sent ValueFlag (Just "daemon") Nothing (Just "local")), assertEqual "a setting flag alone is sent" (told "daemon") (sent SettingFlag (Just "daemon") Nothing Nothing), assertEqual "a setting flag over NIX_REMOTE is sent" (told "unix:///run/socket") (sent SettingFlag (Just "unix:///run/socket") Nothing (Just "local")), assertEqual "an empty setting flag is auto" (told "auto") (sent SettingFlag (Just "") Nothing Nothing), assertEqual "a setting flag over a setting" (told "local") (sent SettingFlag (Just "local") (Just "daemon") Nothing), assertEqual "a setting flag naming a directory sends nothing" none (sent SettingFlag (Just "/srv/store") Nothing Nothing), assertEqual "a setting flag, no flag given, and NIX_REMOTE send nothing" none (sent SettingFlag Nothing Nothing (Just "daemon")) ], runTest "--store sets the store setting itself for the commands that model upstream's nix command, and gives it a value only for the rest" $ allFailures [ assertEqual (T.pack (unwords args)) (Right flag) (storeFlagOf . optCommand <$> parseArgs args) | (args, flag) <- [ (["develop", "--expr", "1"], SettingFlag), (["print-dev-env", "--expr", "1"], SettingFlag), (["profile", "add", "--expr", "1"], SettingFlag), (["profile", "remove", "hello"], SettingFlag), (["eval", "--expr", "1"], ValueFlag), (["build", "--expr", "1"], ValueFlag), (["profile", "list"], ValueFlag), (["store", "gc"], ValueFlag) ] ], runTest "auto opens the store when it can be written, goes through the daemon when it cannot and the socket is there, and asks nothing for a store named" $ allFailures [ assertEqual "writable" (DirectStore Nothing, [AskedWriting]) (choose StoreWritable AddressPresent AutoStore), assertEqual "not writable, a socket" (ThroughDaemon (DefaultSocket defaultAddress), [AskedPresence defaultAddress, AskedWriting]) (choose StoreNotWritable AddressPresent AutoStore), assertEqual "not writable, no socket" (DirectStore Nothing, [AskedPresence defaultAddress, AskedWriting]) (choose StoreNotWritable AddressAbsent AutoStore), assertEqual "daemon" (ThroughDaemon (DefaultSocket defaultAddress), []) (choose StoreNotWritable AddressAbsent (DaemonSocket Nothing)), assertEqual "a socket" (ThroughDaemon (NamedSocket "/run/other"), []) (choose StoreWritable AddressAbsent (DaemonSocket (Just "/run/other"))), assertEqual "a socket at the default's path is the default" (ThroughDaemon (DefaultSocket defaultAddress), []) (choose StoreWritable AddressAbsent (DaemonSocket (Just defaultAddress))), assertEqual "local" (DirectStore Nothing, []) (choose StoreNotWritable AddressPresent (LocalStore Nothing)), assertEqual "a directory" (DirectStore (Just "/srv/store"), []) (choose StoreNotWritable AddressPresent (LocalStore (Just "/srv/store"))) ], runTestM "the store setting a daemon is sent reads back as itself, so sending it again changes nothing" $ if SI.os == "mingw32" then pure Pass else do result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} (QC.forAll absolutePath renderedSettingIsStable) pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result))), runTestM "a unix:// path read back from the name a store is given is the path" $ if SI.os == "mingw32" then pure Pass else do result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} (QC.forAll absolutePath namedPathRoundTrips) pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result))) ] where posix = parseStoreTargetOn PosixPaths windows = parseStoreTargetOn WindowsPaths sent = storeOverride PosixPaths none = Right Map.empty told = Right . Map.singleton "store"-- | An absolute POSIX path of any bytes a file name may hold, its-- components none of them empty, @.@ or @..@, which a path folds.absolutePath :: QC.Gen BS.ByteStringabsolutePath = BS.cons slash . BS.intercalate (BS.singleton slash) <$> QC.listOf1 component where slash = 0x2f component = (BS.pack <$> QC.listOf1 byte) `QC.suchThat` (`notElem` [".", ".."]) byte = QC.choose (1, 255) `QC.suchThat` (/= slash)-- | The property: the store a path is named, as a message names it, reads-- back as the daemon at that path.namedPathRoundTrips :: BS.ByteString -> QC.PropertynamedPathRoundTrips path = QC.counterexample (T.unpack name) (parseStoreTargetOn PosixPaths (TE.encodeUtf8 name) QC.=== Right (DaemonSocket (Just path))) where name = daemonStoreName (NamedSocket path)-- | The property: the setting a daemon is sent for a socket, read as a-- setting again, is sent as it was.renderedSettingIsStable :: BS.ByteString -> QC.PropertyrenderedSettingIsStable path = QC.counterexample (show (first, second)) (first QC.=== second) where first = storeOverride PosixPaths ValueFlag Nothing (Just (TE.encodeUtf8 (daemonStoreName (NamedSocket path)))) Nothing second = first >>= maybe (Right Map.empty) (\rendered -> storeOverride PosixPaths ValueFlag Nothing (Just rendered) Nothing) . Map.lookup "store"-- ----------------------------------------------------------------------------- What the machine is asked-- ----------------------------------------------------------------------------- | The two questions @auto@ asks of the machine, asked of real-- directories, sockets and pipes.testStoreChoiceIO :: IO [Bool]testStoreChoiceIO = do putStrLn "daemon/store-choice-machine" temporary <- getTemporaryDirectory let root = temporary </> "nova-nix-test-store-choice" sequence $ [ runTestM "a store's state directory this process can write is writable, and one it cannot, or none, is not" $ withRoot root (writingTests root), runTestM "a socket's path is present when anything is there and absent otherwise" $ withSocketDaemon Listen.DefaultTrust id $ \_ address _ -> do listening <- addressPresence address unused <- daemonAddress (root </> "none") absent <- traverse addressPresence unused pure $ allFailures [ assertEqual "a daemon's address" AddressPresent listening, assertEqual "an address nothing listens at" (Just AddressAbsent) absent ] ] ++ presenceTests root-- | Run a test in a directory of its own, removed before and after.withRoot :: FilePath -> IO a -> IO awithRoot root action = do forceRemoveIfExists root createDirectoryIfMissing True root result <- action forceRemoveIfExists root pure result#if defined(mingw32_HOST_OS)-- | A state directory made as nova-nix makes one is writable, one that-- grants this user only read is not, and a missing one is not; and of two-- state directories this user may change, the one under a directory that-- Authenticated Users may change is not writable, since no other process-- may open a store whose way to it another account could alter, and the-- one under a directory only this user may change is.writingTests :: FilePath -> IO TestResultwritingTests root = do createStateDirectory made sid <- processUserSid >>= maybe (ioError (userError "the process's user has no SID")) pure makeDirectory readOnly ("D:P(A;;FR;;;" <> sid <> ")") makeStateDirectoryUnder sid keptByUser (fullControlFor sid) makeStateDirectoryUnder sid sharedWithUsers (fullControlFor sid <> fullControlFor "AU") writable <- probeStoreWriting made denied <- probeStoreWriting readOnly missing <- probeStoreWriting (root </> "missing") trusted <- probeStoreWriting (keptByUser </> ".nova-nix") distrusted <- probeStoreWriting (sharedWithUsers </> ".nova-nix") pure $ allFailures [ assertEqual "made by nova-nix" StoreWritable writable, assertEqual "read only" StoreNotWritable denied, assertEqual "missing" StoreNotWritable missing, assertEqual "under a directory only this user may change" StoreWritable trusted, assertEqual "under a directory Authenticated Users may change" StoreNotWritable distrusted ] where made = root </> "made" </> ".nova-nix" readOnly = root </> "read-only" keptByUser = root </> "kept-by-user" sharedWithUsers = root </> "shared-with-users" -- An entry giving the account, a SID or an SDDL alias, full control, -- passed down. fullControlFor account = "(A;OICI;FA;;;" <> account <> ")" -- A directory with the entries given and, in it, a state directory this -- user alone may use. The DACLs are protected, so nothing the test's -- own root grants is passed down. makeStateDirectoryUnder sid parent entries = do makeDirectory parent ("D:P" <> entries) makeDirectory (parent </> ".nova-nix") ("D:P" <> fullControlFor sid)-- | A path under a file or one that cannot be looked at is a POSIX-- matter: a pipe's name has neither.presenceTests :: FilePath -> [IO Bool]presenceTests _ = []#else-- | Whether this process is root, who is let through whatever the modes-- say.runsAsRoot :: IO BoolrunsAsRoot = (== 0) <$> getEffectiveUserID-- | A state directory this user owns with the usual modes is writable, one-- that has lost its write mode is not, and a missing one is not. Root is-- let through whatever the modes say, so for root the mode is not tried.writingTests :: FilePath -> IO TestResultwritingTests root = do createDirectoryIfMissing True stateDir setFileMode stateDir 0o755 writable <- probeStoreWriting stateDir missing <- probeStoreWriting (root </> "missing" </> ".nova-nix") asRoot <- runsAsRoot denied <- if asRoot then pure StoreNotWritable else bracket_ (setFileMode stateDir 0o555) (setFileMode stateDir 0o755) (probeStoreWriting stateDir) pure $ allFailures [ assertEqual "writable" StoreWritable writable, assertEqual "missing" StoreNotWritable missing, assertEqual "without the write mode" StoreNotWritable denied ] where stateDir = root </> ".nova-nix"-- | A file is present, a path under one and a missing one are absent, and-- a path that cannot be looked at, as one under a directory this user may-- not search, is a failure and not an answer.presenceTests :: FilePath -> [IO Bool]presenceTests root = [ runTestM "a file is present, and a path under a file, or nothing, is absent" $ withRoot root $ do writeFile file "" present <- addressPresence (BS8.pack file) under <- addressPresence (BS8.pack (file </> "child")) missing <- addressPresence (BS8.pack (root </> "missing")) pure $ allFailures [ assertEqual "a file" AddressPresent present, assertEqual "under a file" AddressAbsent under, assertEqual "missing" AddressAbsent missing ], runTestM "a link is present whatever it leads to, as it is looked at and not followed" $ withRoot root $ do createSymbolicLink (root </> "nowhere") link dangling <- addressPresence (BS8.pack link) pure (assertEqual "a link to nothing" AddressPresent dangling), runTestM "a path that cannot be looked at is a failure in upstream's words, not an answer" $ withRoot root $ do asRoot <- runsAsRoot if asRoot then pure Pass else do createDirectoryIfMissing True closed tried <- bracket_ (setFileMode closed 0o000) (setFileMode closed 0o755) (tryIO (addressPresence (BS8.pack (closed </> "socket")))) pure $ case tried of Left failure -> assertEqual "the failure" ("getting status of \"" <> closed </> "socket\": Permission denied") (ioeGetErrorString failure) Right answer -> Fail ("answered " <> T.pack (show answer)) ] where file = root </> "file" link = root </> "link" closed = root </> "closed" tryIO :: IO a -> IO (Either IOException a) tryIO = try#endif