{-# LANGUAGE LambdaCase #-}-- | Tests of the daemon's wire format, its protocol, its side of a-- connection, scripted byte by byte against a store in memory, who may-- connect to it, the daemon itself on a socket, or on Windows its pipe,-- over a store on disk, and what a client adds to a store on disk-- through it.module Test.Daemon ( testDaemonWire, testDaemonProtocol, testDaemonFixtures, testDaemonServer, testDaemonAuth, testDaemonSocketIO, testDaemonBuilds, testDaemonAdds, -- * A daemon on disk, for the pipe's tests withSocketDaemon, socketTestMicros, helloOver, defaultStoreDir, fooPath, )whereimport Control.Concurrent (forkFinally, killThread)import Control.Concurrent.MVar (MVar, newEmptyMVar, putMVar, takeMVar)import Control.Exception (IOException, bracket, onException, try)import Control.Monad (replicateM, void, when)import Control.Monad.State.Strict (State, gets, modify', runState, state)import DaemonLink (DaemonLink (..), connectDaemon, daemonAddress, listenerOpenToUsers)import qualified Data.Bifunctor as Bifunctorimport Data.Bits (shiftR)import qualified Data.ByteString as BSimport qualified Data.ByteString.Builder as BBimport qualified Data.ByteString.Char8 as BS8import qualified Data.ByteString.Lazy as BLimport Data.Foldable (traverse_)import Data.Functor.Identity (Identity, runIdentity)import Data.IORef (atomicModifyIORef', newIORef, readIORef)import Data.Int (Int64)import Data.List (isPrefixOf, isSuffixOf, sort)import Data.List.NonEmpty (NonEmpty (..))import qualified Data.Map.Strict as Mapimport Data.Maybe (fromMaybe, mapMaybe)import qualified Data.Set as Setimport Data.Text (Text)import qualified Data.Text as Timport qualified Data.Text.Encoding as TEimport Data.Time.Clock.POSIX (getPOSIXTime)import Data.Word (Word32, Word64, Word8)import Foreign.C.Types (CInt (..))import Nix.Builder (BuildConfig (..))import Nix.Builder.BuildUser (ProcessPrivilege (..))import Nix.Builder.Sandbox (SandboxMode (..))import Nix.Builder.Settings (MachineDefaults (..), settingsBuildConfig)import Nix.CacheDirectory (cacheInfoFileName, cacheInfoText, directoryUrl)import Nix.Config (NixConfig (..), defaultNixConfig)import qualified Nix.Daemon.Auth as Authimport qualified Nix.Daemon.Connection as Connimport qualified Nix.Daemon.Listen as Listenimport Nix.Daemon.LocalStore (ServedStore, newServedStore, serveLocal)import qualified Nix.Daemon.Ops as Opsimport qualified Nix.Daemon.Protocol as Protoimport qualified Nix.Daemon.Wire as Wireimport Nix.Derivation (Derivation (..), DerivationOutput (..), DrvFile, Platform (..), drvFileATerm, drvFileDerivation, drvFilePath, inputAddressed, toATerm)import Nix.Environment (argumentBytes)import Nix.Hash (FileIngestionMethod (..), makeFixedOutputPath, makeSourcePath, sha256Digest)import qualified Nix.Hash as Hashimport Nix.Http (FetchRetryPolicy (..), defaultDownloadAttempts)import Nix.Logger (ActivityStart (..), Logger, plainLogger)import Nix.Push (storePathBasename)import qualified Nix.Realise as Realiseimport Nix.Store (Store (..), closeStore, isValid, openStore)import Nix.Store.Access (Sid, novaNixServiceSid, serviceSid, sidFromText, sidText)import Nix.Store.DB (PathInfo (..), PathRegistration (..), RegistrationTime (..), StoreDB, Ultimate (..), closeStoreDB, openStoreDB, queryPathInfo, queryReferences, registerPath)import qualified Nix.Store.ExecBit as ExecBitimport Nix.Store.Path (StoreDir (..), StorePath, defaultStoreDir, parseStorePath, storePathHashLen, storePathToFilePath, storePathToText)import Nix.Store.Path.Internal (StorePath (..))import qualified NovaCache.Base32 as Nix32import qualified NovaCache.Base64 as B64import qualified NovaCache.Hash as CHashimport qualified NovaCache.NAR as NARimport qualified NovaCache.NarInfo as NarInfoimport qualified NovaCache.Signing as Signingimport qualified System.Directory as Dirimport System.Environment (lookupEnv)import System.FilePath ((</>))import System.IO.Error (mkIOError, resourceVanishedErrorType)import qualified System.Info as SIimport System.Timeout (timeout)import Test.Harness (TestResult (..), andThen, assertEqual, assertRight, findTestShell, forceRemoveIfExists, genContentAddress, genFixturePath, genSignatures, mkTestBuildDrv, runTest, runTestM, servedNar, sigTestKeyText, sigTestSecretKeyFile, signedTestNarInfo, symlinksAvailable)import qualified Test.QuickCheck as QC-- ----------------------------------------------------------------------------- Tests: the daemon's wire codec-- ----------------------------------------------------------------------------- | The bytes a builder writes.builtBytes :: BB.Builder -> BS.ByteStringbuiltBytes = BL.toStrict . BB.toLazyByteString-- | A value decoded from all of its input, or why not: a decode that-- leaves bytes over did not read what was written.decodeWhole :: Wire.Decoder a -> BS.ByteString -> Either Text adecodeWhole reader input = case Wire.runDecoder reader input of Left err -> Left (T.pack (show err)) Right (value, rest) | BS.null rest -> Right value | otherwise -> Left (T.pack (show (BS.length rest)) <> " bytes left over")-- | Upstream's refusal of bytes, as 'decodeWhole' reports it.wireRefusal :: Text -> Either Text awireRefusal message = Left (T.pack (show (Wire.Malformed message)))-- | A QuickCheck property as a test result.codecProperty :: (QC.Testable prop) => prop -> IO TestResultcodecProperty prop = do result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} prop pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))-- | What the store starts an activity for: a build or a check of a-- derivation, or a substitution of a path from a cache.genActivityStart :: QC.Gen ActivityStartgenActivityStart = QC.oneof [ Building <$> genFixturePath ".drv", Checking <$> genFixturePath ".drv", Substituting <$> genFixturePath "" <*> (T.pack <$> QC.arbitrary) ]-- | Upstream's framing: numbers and their ranges, strings and their-- padding, lists, and framed streams however their input arrives.testDaemonWire :: IO [Bool]testDaemonWire = do putStrLn "daemon/wire" sequence [ runTestM "a word reads back as itself" $ codecProperty $ \n -> decodeWhole Wire.getWord64 (builtBytes (Wire.putNum (n :: Word64))) QC.=== Right n, runTestM "a number reads back up to its type's largest value and is refused above it, naming the type as upstream does" $ codecProperty $ QC.forAll genWord $ \n -> let encoded = builtBytes (Wire.putNum n) bounded :: (Integral a) => Text -> Word64 -> Either Text a bounded typeCode bound | n <= bound = Right (fromIntegral n) | otherwise = wireRefusal ("serialised integer " <> T.pack (show n) <> " is too large for type '" <> typeCode <> "'") in QC.conjoin [ decodeWhole Wire.getWord8 encoded QC.=== bounded "h" 255, decodeWhole Wire.getWord32 encoded QC.=== bounded "j" 4294967295, decodeWhole Wire.getInt64 encoded QC.=== bounded "l" 9223372036854775807, decodeWhole Wire.getBool encoded QC.=== fmap (/= (0 :: Word64)) (bounded "b" 1) ], runTest "a negative number is written as its two's complement, which upstream's int64_t read refuses" $ assertEqual "read" (wireRefusal "serialised integer 18446744073709551615 is too large for type 'l'") (decodeWhole Wire.getInt64 (builtBytes (Wire.putNum (-1 :: Int64)))), runTestM "a string reads back as itself, padded with zeros to a multiple of eight" $ codecProperty $ QC.forAll genWireBytes $ \bytes -> let encoded = builtBytes (Wire.putBytes bytes) padding = BS.drop (8 + BS.length bytes) encoded in QC.conjoin [ decodeWhole Wire.getBytes encoded QC.=== Right bytes, BS.length encoded `mod` 8 QC.=== 0, QC.property (BS.length padding < 8 && BS.all (== 0) padding) ], runTestM "a string with a byte of its padding set is refused" $ codecProperty $ QC.forAll (genWireBytes `QC.suchThat` ((/= 0) . (`mod` 8) . BS.length)) $ \bytes -> let encoded = builtBytes (Wire.putBytes bytes) paddingStart = 8 + BS.length bytes in QC.forAll ((,) <$> QC.choose (paddingStart, BS.length encoded - 1) <*> QC.choose (1, 255)) $ \(at, byte) -> let corrupted = BS.take at encoded <> BS.singleton byte <> BS.drop (at + 1) encoded in decodeWhole Wire.getBytes corrupted QC.=== wireRefusal "non-zero padding", runTestM "a string cut short asks for more input, and fails when the input ends" $ codecProperty $ QC.forAll genWireBytes $ \bytes -> let encoded = builtBytes (Wire.putBytes bytes) in QC.forAll (QC.choose (0, BS.length encoded - 1)) $ \cut -> let prefix = BS.take cut encoded waiting = case Wire.feedInput (Just prefix) (Wire.startDecoding Wire.getBytes) of Wire.NeedInput _ -> True _ -> False in QC.conjoin [QC.property waiting, fmap fst (Wire.runDecoder Wire.getBytes prefix) QC.=== Left Wire.InputEnded], runTestM "a list reads back as itself" $ codecProperty $ QC.forAll (QC.listOf genWireBytes) $ \items -> decodeWhole (Wire.getList Wire.getBytes) (builtBytes (Wire.putList Wire.putBytes items)) QC.=== Right items, runTestM "a framed stream reads back as its bytes however its input is split, and stops at the chunk that ends it" $ codecProperty $ QC.forAll ((,) <$> QC.listOf genWireBytes <*> genWireBytes) $ \(chunks, after) -> let encoded = builtBytes (foldMap Wire.putFrame chunks <> Wire.putFrameEnd) <> after in QC.forAll (genSplit encoded) $ \pieces -> readFrames pieces QC.=== Right (BS.concat chunks, after), runTest "a decode that needs no input keeps all it is given as what follows" $ assertEqual "rest" (Right ((), "rest")) (Wire.runDecoder (pure ()) "rest"), runTest "a frame is its length and its bytes, unpadded, and an empty one ends the stream" $ assertEqual "frames" ("\3\0\0\0\0\0\0\0abc\0\0\0\0\0\0\0\0" :: BS.ByteString) (builtBytes (Wire.putFrame "abc" <> Wire.putFrame "" <> Wire.putFrameEnd)), runTest "a refused read leaves the input after the bytes it read, where upstream's source is left" $ case Wire.feedInput (Just (builtBytes (Wire.putNum (4294967296 :: Word64)) <> "rest")) (Wire.startDecoding Wire.getWord32) of Wire.DecodeFailed (Wire.Malformed _) rest -> assertEqual "rest" "rest" rest _ -> Fail "expected a refusal", runTest "a frame's length is read as upstream's unsigned int" $ assertEqual "read" (wireRefusal "serialised integer 4294967296 is too large for type 'j'") (decodeWhole Wire.getFrame (builtBytes (Wire.putNum (4294967296 :: Word64)))) ] where genWord = QC.oneof [QC.arbitrary, QC.choose (0, 300), QC.choose (4294967200, 4294967400), QC.choose (9223372036854775800, maxBound), QC.choose (0, 2)]-- | Bytes of any length, short ones most.genWireBytes :: QC.Gen BS.ByteStringgenWireBytes = BS.pack <$> QC.resize 40 (QC.listOf QC.arbitrary)-- | Bytes cut at random places into pieces, as reads from a socket might-- deliver them.genSplit :: BS.ByteString -> QC.Gen [BS.ByteString]genSplit bytes = do cuts <- sort <$> QC.listOf (QC.choose (0, BS.length bytes)) pure (zipWith slice (0 : cuts) (cuts ++ [BS.length bytes])) where slice from to = BS.take (to - from) (BS.drop from bytes)-- | A framed stream read a chunk at a time from input that arrives in-- pieces: the bytes it carries, and the input after its end.readFrames :: [BS.ByteString] -> Either Wire.DecodeError (BS.ByteString, BS.ByteString)readFrames = go [] (Wire.startDecoding Wire.getFrame) where go chunks decoding pieces = case decoding of Wire.NeedInput _ -> case pieces of piece : rest -> go chunks (Wire.feedInput (Just piece) decoding) rest [] -> go chunks (Wire.feedInput Nothing decoding) [] Wire.DecodeFailed err _ -> Left err Wire.Decoded Nothing rest -> Right (BS.concat (reverse chunks), BS.concat (rest : pieces)) Wire.Decoded (Just chunk) rest -> go (chunk : chunks) (Wire.feedInput (Just rest) (Wire.startDecoding Wire.getFrame)) pieces-- | Every version the codec's gates distinguish, from upstream's oldest-- tested to its newest, each with and without the feature that changes-- how realisations travel.gateVersions :: [Proto.Version]gateVersions = [ Proto.Version (Proto.VersionNumber 1 minor) features | minor <- [10 .. Proto.vnMinor Proto.latestVersionNumber], features <- [Set.empty, Set.singleton Proto.featureRealisationWithPath] ]-- | The version at a minor number, with no features.protoVersion :: Word8 -> Proto.VersionprotoVersion minor = Proto.Version (Proto.VersionNumber 1 minor) Set.empty-- | The newest version, with the feature that carries realisations.realisationVersion :: Proto.VersionrealisationVersion = Proto.Version Proto.latestVersionNumber (Set.singleton Proto.featureRealisationWithPath)-- | Whether a version's number is at least 1.@minor@.versionAtLeast :: Proto.Version -> Word8 -> BoolversionAtLeast version minor = Proto.versionNumber version >= Proto.VersionNumber 1 minor-- | Whether a version carries realisations.carriesRealisations :: Proto.Version -> BoolcarriesRealisations = Set.member Proto.featureRealisationWithPath . Proto.versionFeatures-- | The law every serialiser keeps: at every version, what is written-- reads back as what that version carries of it, and nothing is left over.-- @carried@ is this suite's own account of each gate, so a gate dropped-- from both the reader and the writer still fails it.roundTripsAtEveryVersion :: (Eq a, Show a) => (Proto.Version -> QC.Gen a) -> (Proto.Version -> a -> a) -> (Proto.Version -> Wire.Decoder a) -> (Proto.Version -> a -> BB.Builder) -> QC.PropertyroundTripsAtEveryVersion gen carried reader writer = QC.conjoin [ QC.counterexample (show version) $ QC.forAll (gen version) $ \value -> decodeWhole (reader version) (builtBytes (writer version value)) QC.=== Right (carried version value) | version <- gateVersions ]-- | The store directory the codec's properties name paths under.wireStoreDir :: StoreDirwireStoreDir = defaultStoreDir-- | A store path: a nix-base32 hash and a name, some of them derivations.genWireStorePath :: QC.Gen StorePathgenWireStorePath = do hashPart <- QC.vectorOf storePathHashLen (QC.elements "0123456789abcdfghijklmnpqrsvwxyz") first <- QC.elements ['a' .. 'z'] rest <- QC.resize 12 (QC.listOf (QC.elements (['a' .. 'z'] ++ ['A' .. 'Z'] ++ ['0' .. '9'] ++ "+-._?="))) suffix <- QC.elements ["", ".drv"] pure (StorePath (T.pack hashPart) (T.pack (first : rest) <> suffix))genOutputName :: QC.Gen Proto.OutputNamegenOutputName = Proto.OutputName . T.pack <$> ((:) <$> QC.elements ['a' .. 'z'] <*> QC.resize 6 (QC.listOf (QC.elements (['a' .. 'z'] ++ ['0' .. '9'] ++ "-_"))))genOutputsSpec :: QC.Gen Proto.OutputsSpecgenOutputsSpec = QC.oneof [pure Proto.AllOutputs, QC.suchThatMap (Set.fromList <$> QC.resize 3 (QC.listOf1 genOutputName)) Proto.namedOutputs]genDerivedPath :: QC.Gen Proto.DerivedPathgenDerivedPath = QC.oneof [Proto.DerivedOpaque <$> genWireStorePath, Proto.DerivedBuilt <$> genWireStorePath <*> genOutputsSpec]genNarHash :: QC.Gen Proto.NarHashgenNarHash = QC.suchThatMap (BS.pack <$> QC.vectorOf 32 QC.arbitrary) Proto.narHashFromDigestgenPathInfo :: QC.Gen Proto.UnkeyedValidPathInfogenPathInfo = Proto.UnkeyedValidPathInfo <$> QC.oneof [pure Nothing, Just <$> genWireStorePath] <*> genNarHash <*> (Set.fromList <$> QC.resize 3 (QC.listOf genWireStorePath)) <*> QC.choose (0, maxBound) <*> QC.arbitrary <*> QC.arbitrary <*> genSignatures <*> QC.oneof [pure Nothing, Just <$> genContentAddress]-- | What a version carries of a path's info: its trust fields from 1.16.carriedPathInfo :: Proto.Version -> Proto.UnkeyedValidPathInfo -> Proto.UnkeyedValidPathInfocarriedPathInfo version info | versionAtLeast version 16 = info | otherwise = info {Proto.upiUltimate = False, Proto.upiSignatures = Set.empty, Proto.upiContentAddress = Nothing}genUnkeyedRealisation :: QC.Gen Proto.UnkeyedRealisationgenUnkeyedRealisation = Proto.UnkeyedRealisation <$> genWireStorePath <*> genSignaturesgenBuildResult :: QC.Gen Proto.BuildResultgenBuildResult = do outcome <- QC.oneof [ Proto.Succeeded <$> (Proto.Success <$> QC.elements [minBound .. maxBound] <*> (Map.fromList <$> QC.resize 3 (QC.listOf ((,) <$> genOutputName <*> genUnkeyedRealisation)))), Proto.Failed <$> (Proto.Failure <$> QC.elements [minBound .. maxBound] <*> genWireBytes <*> QC.arbitrary) ] Proto.BuildResult outcome <$> QC.arbitrary <*> QC.choose (0, maxBound) <*> QC.choose (0, maxBound) <*> QC.oneof [pure Nothing, Just <$> QC.choose (0, maxBound)] <*> QC.oneof [pure Nothing, Just <$> QC.choose (0, maxBound)]-- | What a version carries of a build result: how often and when it built-- from 1.29, its CPU times from 1.37, and its outputs from 1.28, their-- signatures only with the realisation feature.carriedBuildResult :: Proto.Version -> Proto.BuildResult -> Proto.BuildResultcarriedBuildResult version result = withCpu (withTimes (result {Proto.brOutcome = outcome})) where withTimes r | versionAtLeast version 29 = r | otherwise = r {Proto.brTimesBuilt = 0, Proto.brStartTime = 0, Proto.brStopTime = 0} withCpu r | versionAtLeast version 37 = r | otherwise = r {Proto.brCpuUser = Nothing, Proto.brCpuSystem = Nothing} outcome = case Proto.brOutcome result of Proto.Succeeded (Proto.Success status outputs) -> Proto.Succeeded (Proto.Success status (carriedOutputs outputs)) Proto.Failed (Proto.Failure status message nonDeterministic) -> Proto.Failed (Proto.Failure status message (nonDeterministic && versionAtLeast version 29)) carriedOutputs outputs | carriesRealisations version = outputs | versionAtLeast version 28 = Map.map (\realisation -> realisation {Proto.urSignatures = Set.empty}) outputs | otherwise = Map.empty-- | Whether a store path is a derivation's.isDrvPath :: StorePath -> BoolisDrvPath path = ".drv" `T.isSuffixOf` spName path-- | What a version carries of a derived path: before 1.30 all of a path's-- outputs are spelled as the bare path, which reads back as the path-- itself unless it is a derivation's.carriedDerivedPath :: Proto.Version -> Proto.DerivedPath -> Proto.DerivedPathcarriedDerivedPath version derived = case derived of Proto.DerivedBuilt path Proto.AllOutputs | not (versionAtLeast version 30) && not (isDrvPath path) -> Proto.DerivedOpaque path _ -> derived-- | Whether a version can spell a derived path: before 1.30 a derivation-- file itself cannot be asked for.spellable :: Proto.Version -> Proto.DerivedPath -> Boolspellable version derived = case derived of Proto.DerivedOpaque path -> versionAtLeast version 30 || not (isDrvPath path) Proto.DerivedBuilt _ _ -> TruegenDaemonError :: QC.Gen Proto.DaemonErrorgenDaemonError = (Proto.DaemonError . Proto.Verbosity <$> QC.arbitrary) <*> genWireBytes <*> QC.resize 3 (QC.listOf genWireBytes) <*> QC.arbitrarygenFields :: QC.Gen [Proto.Field]genFields = QC.resize 4 (QC.listOf (QC.oneof [Proto.FieldInt <$> QC.arbitrary, Proto.FieldString <$> genWireBytes]))genStderrMessage :: QC.Gen Proto.StderrMessagegenStderrMessage = QC.oneof [ Proto.StderrNext <$> genWireBytes, Proto.StderrRead <$> QC.arbitrary, Proto.StderrWrite <$> genWireBytes, pure Proto.StderrLast, Proto.StderrError <$> genDaemonError, Proto.StderrStartActivity <$> ( (Proto.Activity . Proto.ActivityId <$> QC.arbitrary) <*> (Proto.Verbosity <$> QC.arbitrary) <*> (Proto.ActivityType <$> QC.arbitrary) <*> genWireBytes <*> genFields <*> (Proto.ActivityId <$> QC.arbitrary) ), Proto.StderrStopActivity . Proto.ActivityId <$> QC.arbitrary, (Proto.StderrResult . Proto.ActivityId <$> QC.arbitrary) <*> (Proto.ResultType <$> QC.arbitrary) <*> genFields ]-- | What a version carries of a message: from 1.26 an error goes as a-- record without its exit status, which reads back as 1; before, as its-- message and exit status, which read back at the error level with no-- traces.carriedStderrMessage :: Proto.Version -> Proto.StderrMessage -> Proto.StderrMessagecarriedStderrMessage version message = case message of Proto.StderrError err | versionAtLeast version 26 -> Proto.StderrError err {Proto.errExitStatus = 1} | otherwise -> Proto.StderrError err {Proto.errLevel = Proto.errorVerbosity, Proto.errTraces = []} _ -> message-- | Every version a request's form changes at, with each combination of-- the two features that change what one carries.requestVersions :: [Proto.Version]requestVersions = [ Proto.Version (Proto.VersionNumber 1 minor) (Set.fromList features) | minor <- [10 .. Proto.vnMinor Proto.latestVersionNumber], features <- [[], [Proto.featureRealisationWithPath], [Proto.featureDeleteDeadSpecificReferrers], [Proto.featureRealisationWithPath, Proto.featureDeleteDeadSpecificReferrers]] ]-- | A request a client may send at a version, its derived paths ones-- the version can spell.genRequest :: Proto.Version -> QC.Gen Ops.RequestgenRequest version = QC.oneof [ Ops.SetOptions <$> genClientSettings, Ops.IsValidPath <$> genWireStorePath, Ops.QueryValidPaths <$> genPathSet <*> QC.elements [Ops.NoSubstitute, Ops.Substitute], Ops.QuerySubstitutablePaths <$> genPathSet, Ops.QueryReferrers <$> genWireStorePath, Ops.QueryValidDerivers <$> genWireStorePath, Ops.QueryDerivationOutputMap <$> genWireStorePath, pure Ops.QueryAllValidPaths, Ops.QueryPathInfo <$> genWireStorePath, Ops.QueryMissing <$> targets, Ops.AddToStore <$> (Ops.AddToStoreRequest <$> genWireBytes <*> genWireBytes <*> genPathSet <*> repair), Ops.AddToStoreNar <$> (Proto.ValidPathInfo <$> genWireStorePath <*> genPathInfo) <*> repair <*> QC.elements [Ops.CheckSigs, Ops.NoCheckSigs], Ops.AddMultipleToStore <$> repair <*> QC.elements [Ops.CheckSigs, Ops.NoCheckSigs], Ops.BuildPaths <$> targets <*> mode, Ops.BuildPathsWithResults <$> targets <*> mode, Ops.EnsurePath <$> genWireStorePath, Ops.AddTempRoot <$> genWireStorePath, Ops.AddIndirectRoot . canonicalLink <$> QC.resize 3 (QC.listOf1 (BS8.pack <$> QC.listOf1 (QC.elements (['a' .. 'z'] ++ "-_")))), pure Ops.FindRoots, Ops.CollectGarbage <$> ( Ops.GCRequest <$> QC.elements [Proto.ReturnLive, Proto.ReturnDead, Proto.DeleteDead, Proto.DeleteSpecific] <*> QC.oneof [pure Proto.WholeStore, Proto.SpecificPaths <$> genPathSet <*> QC.arbitrary] <*> QC.arbitrary ) <*> QC.elements [Ops.KeepLiveness, Ops.IgnoreLiveness], pure Ops.OptimiseStore, Ops.VerifyStore <$> QC.elements [Ops.SkipContents, Ops.CheckContents] <*> repair, Ops.AddSignatures <$> genWireStorePath <*> genSignatures, Ops.NarFromPath <$> genWireStorePath ] where targets = QC.resize 3 (QC.listOf (genDerivedPath `QC.suchThat` spellable version)) repair = QC.elements [Ops.NoRepair, Ops.Repair] mode = QC.elements [Proto.BuildNormal, Proto.BuildRepair, Proto.BuildCheck]genPathSet :: QC.Gen (Set.Set StorePath)genPathSet = Set.fromList <$> QC.resize 3 (QC.listOf genWireStorePath)-- | The absolute link in canonical form, as the host spells it, whose-- components are given: one that a daemon reads back as it was sent.canonicalLink :: [BS.ByteString] -> BS.ByteStringcanonicalLink components | SI.os == "mingw32" = "C:\\" <> BS8.intercalate "\\" components | otherwise = "/" <> BS8.intercalate "/" components-- | What a version carries of a request: below 1.27 no substitute flag,-- derived paths as the version spells them, and without the-- delete-specific feature a collection's paths as a bare set, so the-- whole store for a specific deletion reads back as no paths.carriedRequest :: Proto.Version -> Ops.Request -> Ops.RequestcarriedRequest version = \case Ops.QueryValidPaths paths _ | not (versionAtLeast version 27) -> Ops.QueryValidPaths paths Ops.NoSubstitute Ops.QueryMissing targets -> Ops.QueryMissing (map (carriedDerivedPath version) targets) Ops.BuildPaths targets mode -> Ops.BuildPaths (map (carriedDerivedPath version) targets) mode Ops.BuildPathsWithResults targets mode -> Ops.BuildPathsWithResults (map (carriedDerivedPath version) targets) mode Ops.CollectGarbage (Ops.GCRequest action paths maxFreed) liveness | not (Set.member Proto.featureDeleteDeadSpecificReferrers (Proto.versionFeatures version)) -> let bare = case paths of Proto.WholeStore | action == Proto.DeleteSpecific -> Proto.SpecificPaths Set.empty False _ -> paths in Ops.CollectGarbage (Ops.GCRequest action bare maxFreed) liveness request -> request-- | Upstream's refusal of a request a version cannot carry, or 'Nothing'-- where it can carry it.refusalFor :: Proto.Version -> Ops.Request -> Maybe TextrefusalFor version = \case Ops.AddToStore _ | not (versionAtLeast version 25) -> Just "AddToStore before protocol 1.25 is not supported by this daemon" Ops.AddToStoreNar {} | not (versionAtLeast version 23) -> Just "AddToStoreNar before protocol 1.23 is not supported by this daemon" Ops.CollectGarbage (Ops.GCRequest action (Proto.SpecificPaths _ referrers) _) _ | not (Set.member Proto.featureDeleteDeadSpecificReferrers (Proto.versionFeatures version)) -> if action /= Proto.DeleteSpecific then Just "Your daemon version is too old to support garbage collecting a specific set of paths" else if referrers then Just "Your daemon version is too old to support deleting referrers." else Nothing _ -> Nothing-- | A request as a daemon reads one: its code, then what that names.requestReader :: Proto.Version -> Wire.Decoder Ops.RequestrequestReader version = Wire.getWord32 >>= \code -> fromMaybe (Wire.malformed ("no request has code " <> T.pack (show code))) (Ops.getRequest wireStoreDir version code)-- | A client's settings: its verbosity at most upstream's loudest, as a-- daemon reads it.genClientSettings :: QC.Gen Ops.ClientSettingsgenClientSettings = Ops.ClientSettings <$> QC.arbitrary <*> QC.arbitrary <*> QC.arbitrary <*> (Proto.Verbosity <$> QC.choose (0, 7)) <*> QC.arbitrary <*> QC.arbitrary <*> QC.arbitrary <*> QC.arbitrary <*> QC.arbitrary <*> (Map.fromList <$> QC.resize 3 (QC.listOf ((,) <$> genWireBytes <*> genWireBytes)))genMissing :: QC.Gen Proto.MissinggenMissing = Proto.Missing <$> genPathSet <*> genPathSet <*> genPathSet <*> QC.arbitrary <*> QC.arbitrarygenGCResult :: QC.Gen Proto.GCResultgenGCResult = Proto.GCResult . Set.fromList <$> QC.resize 3 (QC.listOf genWireBytes) <*> QC.arbitrarygenOutputMap :: QC.Gen (Map.Map Proto.OutputName (Maybe StorePath))genOutputMap = Map.fromList <$> QC.resize 3 (QC.listOf ((,) <$> genOutputName <*> QC.oneof [pure Nothing, Just <$> genWireStorePath]))-- | Roots, each kept by at least one link, as a listing gives them.genRoots :: QC.Gen (Map.Map StorePath (Set.Set BS.ByteString))genRoots = Map.fromList <$> QC.resize 3 (QC.listOf ((,) <$> genWireStorePath <*> (Set.fromList <$> QC.resize 2 (QC.listOf1 genWireBytes))))-- | Every value the protocol carries, written and read back at every-- version gate, and the refusals upstream makes of bytes it does not-- accept.testDaemonProtocol :: IO [Bool]testDaemonProtocol = do putStrLn "daemon/protocol" sequence [ runTestM "a version number reads back as itself" $ codecProperty $ \major minor -> let number = Proto.VersionNumber major minor in decodeWhole Proto.getVersionNumber (builtBytes (Proto.putVersionNumber number)) QC.=== Right number, runTest "a version number is the major number in the second byte and the minor in the first" $ assertEqual "1.38" ("\x26\x01\0\0\0\0\0\0" :: BS.ByteString) (builtBytes (Proto.putVersionNumber Proto.latestVersionNumber)), runTestM "a feature list reads back as its set" $ codecProperty $ QC.forAll (QC.listOf genWireBytes) $ \names -> let features = Set.fromList (map Proto.Feature names) in decodeWhole Proto.getFeatures (builtBytes (Wire.putList Wire.putBytes names)) QC.=== Right features QC..&&. decodeWhole Proto.getFeatures (builtBytes (Proto.putFeatures features)) QC.=== Right features, runTestM "what a daemon tells its client after the handshake reads back as far as each version carries it" $ codecProperty $ roundTripsAtEveryVersion (const ((Proto.HandshakeInfo . Just <$> genWireBytes) <*> QC.elements [Nothing, Just Proto.Trusted, Just Proto.NotTrusted])) ( \version (Proto.HandshakeInfo daemonVersion trust) -> Proto.HandshakeInfo (if versionAtLeast version 33 then daemonVersion else Nothing) (if versionAtLeast version 35 then trust else Nothing) ) Proto.getHandshakeInfo (\version (Proto.HandshakeInfo daemonVersion trust) -> Proto.putHandshakeInfo version (fromMaybe BS.empty daemonVersion) trust), runTestM "a client's obsolete fields are read whole at every version" $ codecProperty $ QC.conjoin [decodeWhole (Proto.getClientObsoleteFields version) (builtBytes (Proto.putClientObsoleteFields version)) QC.=== Right () | version <- gateVersions], runTest "a client's CPU affinity, when set, is followed by a number" $ assertEqual "read" (Right ()) (decodeWhole (Proto.getClientObsoleteFields (protoVersion 14)) (builtBytes (Wire.putNum (1 :: Word64) <> Wire.putNum (7 :: Word64) <> Wire.putBool False))), runTest "a handshake that opens with another word is refused" $ assertEqual "client" (wireRefusal "protocol mismatch") (decodeWhole Proto.getClientMagic (builtBytes Proto.putServerMagic)) `andThen` assertEqual "server" (wireRefusal "nix-daemon protocol mismatch from") (decodeWhole Proto.getServerMagic (builtBytes Proto.putClientMagic)), runTestM "a store path, a store path or none, and a set of them read back as themselves" $ codecProperty $ QC.forAll ((,,) <$> genWireStorePath <*> QC.oneof [pure Nothing, Just <$> genWireStorePath] <*> (Set.fromList <$> QC.listOf genWireStorePath)) $ \(path, optional, paths) -> QC.conjoin [ decodeWhole (Proto.getStorePath wireStoreDir) (builtBytes (Proto.putStorePath wireStoreDir path)) QC.=== Right path, decodeWhole (Proto.getStorePath (StoreDir "/tmp/nova-store")) (builtBytes (Proto.putStorePath (StoreDir "/tmp/nova-store") path)) QC.=== Right path, decodeWhole (Proto.getOptionalStorePath wireStoreDir) (builtBytes (Proto.putOptionalStorePath wireStoreDir optional)) QC.=== Right optional, decodeWhole (Proto.getStorePathSet wireStoreDir) (builtBytes (Proto.putStorePathSet wireStoreDir paths)) QC.=== Right paths ], runTestM "a store path spelled with empty, . and .. components reads as the path it names, as upstream's canonPath makes it" $ codecProperty $ QC.forAll ((,) <$> genWireStorePath <*> QC.elements ["/nix/store//", "/nix/./store/", "/nix/x/../store/", "//nix/store/", "/../nix/store/"]) $ \(path, prefix) -> readStorePath (prefix <> storePathBasename path <> "/") QC.=== Right path, runTest "a store path is refused in upstream's words" $ assertEqual "empty" (wireRefusal "empty path is not a valid store path") (readStorePath "") `andThen` assertEqual "relative" (wireRefusal "not an absolute path: \"nix/store/x\"") (readStorePath "nix/store/x") `andThen` assertEqual "the store itself" (wireRefusal "path \"/nix/store\" is not in the Nix store") (readStorePath "/nix/store/.") `andThen` assertEqual "elsewhere" (wireRefusal "path \"/tmp/g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-foo\" is not in the Nix store") (readStorePath "/tmp/g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-foo") `andThen` assertEqual "beneath one" (wireRefusal "path \"/nix/store/g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-foo/bin\" is not in the Nix store") (readStorePath "/nix/store/g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-foo/bin") `andThen` assertEqual "short" (wireRefusal "'g1w7-foo' is too short to be a valid store path") (readStorePath "/nix/store/g1w7-foo") `andThen` assertEqual "no dash" (wireRefusal "'g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q_foo' can't name a store path because the hash part is not followed by a '-'") (readStorePath "/nix/store/g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q_foo") `andThen` assertEqual "hash" (wireRefusal "store path 'e1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-foo' contains illegal base-32 character 'e'") (readStorePath "/nix/store/e1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-foo") `andThen` assertEqual "name" (wireRefusal "path 'g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-f$o' is not a valid store path: name 'f$o' contains illegal character '$'") (readStorePath "/nix/store/g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-f$o"), runTestM "a signature set, a NAR hash and a content address read back as themselves" $ codecProperty $ QC.forAll ((,,) <$> genSignatures <*> genNarHash <*> QC.oneof [pure Nothing, Just <$> genContentAddress]) $ \(sigs, narHash, ca) -> QC.conjoin [ decodeWhole Proto.getSignatureSet (builtBytes (Proto.putSignatureSet sigs)) QC.=== Right sigs, decodeWhole Proto.getNarHash (builtBytes (Proto.putNarHash narHash)) QC.=== Right narHash, decodeWhole Proto.getOptionalContentAddress (builtBytes (Proto.putOptionalContentAddress ca)) QC.=== Right ca ], runTest "a NAR hash reads in any spelling of a SHA-256 hash" $ let digest = sha256Digest "nar" in assertEqual "nix32" (Proto.narHashFromDigest digest) (either (const Nothing) Just (decodeWhole Proto.getNarHash (builtBytes (Wire.putBytes (TE.encodeUtf8 ("sha256:" <> Nix32.encode digest)))))) `andThen` assertEqual "other algorithm" (wireRefusal "hash 'sha1:0000000000000000000000000000000000000000' should have type 'sha256'") (decodeWhole Proto.getNarHash (builtBytes (Wire.putBytes "sha1:0000000000000000000000000000000000000000"))), runTest "a signature is refused in upstream's words" $ let readSignatures spelled = decodeWhole Proto.getSignatureSet (builtBytes (Wire.putList Wire.putBytes [spelled])) in assertEqual "no colon" (wireRefusal "signature is corrupt") (readSignatures "key") `andThen` assertEqual "no name" (wireRefusal "signature is corrupt") (readSignatures ":AAAA") `andThen` assertEqual "no bytes" (wireRefusal "signature is corrupt") (readSignatures "key:") `andThen` assertEqual "not base64" (wireRefusal "invalid character in Base64 string: '@'") (readSignatures "key:AA@A"), runTest "a content address is refused in upstream's words" $ let readCa spelled = decodeWhole Proto.getContentAddress (builtBytes (Wire.putBytes spelled)) in assertEqual "no prefix" (wireRefusal "not a content address because it is not in the form '<prefix>:<rest>': sha256") (readCa "sha256") `andThen` assertEqual "prefix" (wireRefusal "content address prefix 'flat' is unrecognized. Recogonized prefixes are 'text' or 'fixed'") (readCa "flat:sha256:x") `andThen` assertEqual "no hash" (wireRefusal "content address hash must be in form '<algo>:<hash>', but found: text:sha256") (readCa "text:sha256") `andThen` assertEqual "git" (wireRefusal "experimental Nix feature 'git-hashing' is disabled; add '--extra-experimental-features git-hashing' to enable it") (readCa "fixed:git:sha1:x") `andThen` assertEqual "algorithm" (wireRefusal "unknown hash algorithm 'sha3', expect 'md5', 'sha1', 'sha256', or 'sha512'") (readCa "fixed:r:sha3:x"), runTest "an upload's method and algorithm are read as upstream reads them, a refusal quoting the colon they are read with" $ assertEqual "text" (Right (Proto.TextMethod, "sha256")) (Proto.parseContentAddressMethod "text:sha256") `andThen` assertEqual "recursive" (Right (Proto.FixedMethod NarIngestion, "sha256")) (Proto.parseContentAddressMethod "fixed:r:sha256") `andThen` assertEqual "flat, what follows ignored" (Right (Proto.FixedMethod FlatIngestion, "md5")) (Proto.parseContentAddressMethod "fixed:md5:ignored") `andThen` assertEqual "git" (Left "experimental Nix feature 'git-hashing' is disabled; add '--extra-experimental-features git-hashing' to enable it") (Proto.parseContentAddressMethod "fixed:git:sha1") `andThen` assertEqual "no algorithm" (Left "content address hash must be in form '<algo>:<hash>', but found: text:") (Proto.parseContentAddressMethod "text") `andThen` assertEqual "algorithm" (Left "unknown hash algorithm 'sha3', expect 'md5', 'sha1', 'sha256', or 'sha512'") (Proto.parseContentAddressMethod "text:sha3") `andThen` assertEqual "prefix" (Left "content address prefix 'bogus' is unrecognized. Recogonized prefixes are 'text' or 'fixed'") (Proto.parseContentAddressMethod "bogus:sha256"), runTest "a content address's base64 digest ends at its padding, whatever bytes follow it, as upstream reads it" $ assertEqual "read" (maybe (Left "no expected value") Right (Proto.contentAddressFromParts (Proto.FixedMethod FlatIngestion) "md5" (BS.replicate 16 0))) (decodeWhole Proto.getContentAddress (builtBytes (Wire.putBytes ("fixed:md5:" <> BS8.replicate 22 'A' <> "=\xff")))), runTestM "a path's info reads back as far as each version carries it" $ codecProperty $ roundTripsAtEveryVersion (const genPathInfo) carriedPathInfo (Proto.getUnkeyedValidPathInfo wireStoreDir) (Proto.putUnkeyedValidPathInfo wireStoreDir), runTestM "a path and its info read back as far as each version carries it" $ codecProperty $ roundTripsAtEveryVersion (const (Proto.ValidPathInfo <$> genWireStorePath <*> genPathInfo)) (\version (Proto.ValidPathInfo path info) -> Proto.ValidPathInfo path (carriedPathInfo version info)) (Proto.getValidPathInfo wireStoreDir) (Proto.putValidPathInfo wireStoreDir), runTestM "a derived path reads back as far as each version spells it, and one it cannot spell is refused" $ codecProperty $ QC.conjoin [ QC.counterexample (show version) $ QC.forAll genDerivedPath $ \derived -> case Proto.putDerivedPath wireStoreDir version derived of Right builder -> QC.counterexample "written" (QC.property (spellable version derived)) QC..&&. decodeWhole (Proto.getDerivedPath wireStoreDir version) (builtBytes builder) QC.=== Right (carriedDerivedPath version derived) Left _ -> QC.counterexample "refused" (QC.property (not (spellable version derived))) | version <- gateVersions ], runTest "a derivation file is refused before 1.30 in upstream's words" $ assertEqual "refusal" (Left "trying to request '/nix/store/g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-bar.drv', but daemon protocol 1.29 is too old (< 1.29) to request a derivation file") (builtBytes <$> Proto.putDerivedPath wireStoreDir (protoVersion 29) (Proto.DerivedOpaque (g1w7 "bar.drv"))), runTest "a derived path is refused in upstream's words" $ let readDerived minor spelled = decodeWhole (Proto.getDerivedPath wireStoreDir (protoVersion minor)) (builtBytes (Wire.putBytes spelled)) bar = "/nix/store/g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-bar.drv" in assertEqual "dynamic" (wireRefusal "experimental Nix feature 'dynamic-derivations' is disabled (building output 'out' of 'g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-bar.drv'); add '--extra-experimental-features dynamic-derivations' to enable it") (readDerived 30 (bar <> "!out!lib")) `andThen` assertEqual "no names" (wireRefusal "name must not be empty") (readDerived 30 (bar <> "!")) `andThen` assertEqual "empty name" (wireRefusal "name must not be empty") (readDerived 30 (bar <> "!out,,lib")) `andThen` assertEqual "bad name" (wireRefusal "name 'a$' contains illegal character '$'") (readDerived 30 (bar <> "!z$,a$")) `andThen` assertEqual "unchecked before 1.30" (Right (Proto.DerivedBuilt (g1w7 "bar.drv") (fromMaybe Proto.AllOutputs (Proto.namedOutputs (Set.fromList [Proto.OutputName "a$", Proto.OutputName "out!x"]))))) (readDerived 29 (bar <> "!a$,,out!x")) `andThen` assertEqual "a bare derivation before 1.30" (Right (Proto.DerivedBuilt (g1w7 "bar.drv") Proto.AllOutputs)) (readDerived 29 (bar <> "!,")), runTestM "realisations read back with the feature that carries them, and are refused without it" $ codecProperty $ QC.conjoin [ QC.counterexample (show version) $ QC.forAll ((,,) <$> genUnkeyedRealisation <*> (Proto.DrvOutput <$> genWireStorePath <*> genOutputName) <*> QC.oneof [pure Nothing, Just <$> genUnkeyedRealisation]) $ \(unkeyed, output, optional) -> let readBack reader = fmap (decodeWhole (reader wireStoreDir version) . builtBytes) buildTrace = "the daemon is missing the 'realisation-with-path-not-hash' protocol feature, needed to understand build trace" contentAddressing = "the daemon is missing the 'realisation-with-path-not-hash' protocol feature, needed to support content-addressing derivations" pathBytes path = Wire.putBytes (TE.encodeUtf8 (storePathToText wireStoreDir path)) in if carriesRealisations version then QC.conjoin [ readBack Proto.getUnkeyedRealisation (Proto.putUnkeyedRealisation wireStoreDir version unkeyed) QC.=== Right (Right unkeyed), readBack Proto.getDrvOutput (Proto.putDrvOutput wireStoreDir version output) QC.=== Right (Right output), readBack Proto.getRealisation (Proto.putRealisation wireStoreDir version (Proto.Realisation output unkeyed)) QC.=== Right (Right (Proto.Realisation output unkeyed)), readBack Proto.getOptionalUnkeyedRealisation (Proto.putOptionalUnkeyedRealisation wireStoreDir version optional) QC.=== Right (Right optional) ] else QC.conjoin [ fmap builtBytes (Proto.putUnkeyedRealisation wireStoreDir version unkeyed) QC.=== Left buildTrace, fmap builtBytes (Proto.putDrvOutput wireStoreDir version output) QC.=== Left contentAddressing, fmap builtBytes (Proto.putRealisation wireStoreDir version (Proto.Realisation output unkeyed)) QC.=== Left contentAddressing, fmap builtBytes (Proto.putOptionalUnkeyedRealisation wireStoreDir version (Just unkeyed)) QC.=== Left buildTrace, decodeWhole (Proto.getUnkeyedRealisation wireStoreDir version) (builtBytes (pathBytes (Proto.urOutPath unkeyed) <> Wire.putList Wire.putBytes [])) QC.=== wireRefusal buildTrace, decodeWhole (Proto.getDrvOutput wireStoreDir version) (builtBytes (pathBytes (Proto.doDrvPath output) <> Proto.putOutputName (Proto.doOutputName output))) QC.=== wireRefusal contentAddressing, readBack Proto.getOptionalUnkeyedRealisation (Proto.putOptionalUnkeyedRealisation wireStoreDir version Nothing) QC.=== Right (Right Nothing) ] | version <- gateVersions ], runTestM "a build result reads back as far as each version carries it" $ codecProperty $ roundTripsAtEveryVersion (const genBuildResult) carriedBuildResult (Proto.getBuildResult wireStoreDir) (Proto.putBuildResult wireStoreDir), runTestM "a keyed build result reads back as far as each version carries it" $ codecProperty $ QC.conjoin [ QC.counterexample (show version) $ QC.forAll ((,) <$> (genDerivedPath `QC.suchThat` spellable version) <*> genBuildResult) $ \(derived, result) -> fmap (decodeWhole (Proto.getKeyedBuildResult wireStoreDir version) . builtBytes) (Proto.putKeyedBuildResult wireStoreDir version (Proto.KeyedBuildResult derived result)) QC.=== Right (Right (Proto.KeyedBuildResult (carriedDerivedPath version derived) (carriedBuildResult version result))) | version <- gateVersions ], runTest "a build's outputs in the older JSON form are refused in upstream's words" $ let readOutputs pairs = decodeWhole (Proto.getBuildResult wireStoreDir (protoVersion 28)) (builtBytes (Wire.putNum (0 :: Word64) <> Wire.putBytes "" <> Wire.putList (\(k, v) -> Wire.putBytes k <> Wire.putBytes v) pairs)) in assertEqual "id" (wireRefusal "Invalid derivation output id out") (readOutputs [("out", "{}")]) `andThen` assertEqual "object" (wireRefusal "Expected JSON value to be of type 'object' but it is of type 'array': []") (readOutputs [("x!out", "[]")]) `andThen` assertEqual "key" (wireRefusal "Expected JSON object to contain key 'outPath' but it doesn't: {\"id\":\"x\"}") (readOutputs [("x!out", "{\"id\":\"x\"}")]) `andThen` assertEqual "string" (wireRefusal "Expected JSON value to be of type 'string' but it is of type 'number': 5") (readOutputs [("x!out", "{\"outPath\":5}")]), runTest "a build mode, a status, a trust flag, a collection's action and paths, and a tag are each refused out of range" $ let readByte reader byte = decodeWhole reader (builtBytes (Wire.putNum (byte :: Word64))) in assertEqual "mode" (wireRefusal "Invalid build mode") (readByte Proto.getBuildMode 3) `andThen` assertEqual "status" (wireRefusal "Invalid BuildResult status 15 from remote") (void (decodeWhole (Proto.getBuildResult wireStoreDir (protoVersion 27)) (builtBytes (Wire.putNum (15 :: Word64) <> Wire.putBytes "")))) `andThen` assertEqual "trust" (wireRefusal "Invalid trusted status from remote") (readByte Proto.getTrust 3) `andThen` assertEqual "action" (wireRefusal "Invalid GC action") (readByte Proto.getGCAction 4) `andThen` assertEqual "paths" (wireRefusal "Invalid whole store indicator from remote") (readByte (Proto.getGCPaths wireStoreDir) 2) `andThen` assertEqual "realisation" (wireRefusal "Invalid optional build trace from remote") (readByte (Proto.getOptionalUnkeyedRealisation wireStoreDir realisationVersion) 2) `andThen` assertEqual "duration" (wireRefusal "Invalid optional tag from remote") (void (decodeWhole (Proto.getBuildResult wireStoreDir (protoVersion 37)) (builtBytes (Wire.putNum (0 :: Word64) <> Wire.putBytes "" <> foldMap Wire.putNum [0, 0, 0, 0 :: Word64] <> Wire.putNum (2 :: Word64))))), runTestM "a build mode, a trust flag, a collection's action and its paths read back as themselves" $ codecProperty $ QC.forAll ( (,,,) <$> QC.elements [Proto.BuildNormal, Proto.BuildRepair, Proto.BuildCheck] <*> QC.elements [Nothing, Just Proto.Trusted, Just Proto.NotTrusted] <*> QC.elements [Proto.ReturnLive, Proto.ReturnDead, Proto.DeleteDead, Proto.DeleteSpecific] <*> QC.oneof [pure Proto.WholeStore, (Proto.SpecificPaths . Set.fromList <$> QC.listOf genWireStorePath) <*> QC.arbitrary] ) $ \(mode, trust, action, paths) -> QC.conjoin [ decodeWhole Proto.getBuildMode (builtBytes (Proto.putBuildMode mode)) QC.=== Right mode, decodeWhole Proto.getTrust (builtBytes (Proto.putTrust trust)) QC.=== Right trust, decodeWhole Proto.getGCAction (builtBytes (Proto.putGCAction action)) QC.=== Right action, decodeWhole (Proto.getGCPaths wireStoreDir) (builtBytes (Proto.putGCPaths wireStoreDir paths)) QC.=== Right paths ], runTestM "a request reads back, at every version and with every feature, as what the version carries of it, and one it cannot carry is refused in upstream's words" $ codecProperty $ QC.forAll (QC.elements requestVersions) $ \version -> QC.forAll (genRequest version) $ \request -> QC.counterexample (show version) $ case Ops.putRequest wireStoreDir version request of Right bytes -> decodeWhole (requestReader version) (builtBytes bytes) QC.=== Right (carriedRequest version request) Left refusal -> refusalFor version request QC.=== Just refusal, -- Only a Windows host spells a path the Windows way, so the rule is -- held there alone. runTestM "on Windows an indirect root's link is kept when absolute, collapsed over the host's separators and roots, and refused when no drive or share makes it absolute" $ if SI.os /= "mingw32" then Pass <$ putStrLn " SKIP a Windows link is read by a Windows host alone" else let rootedLink link = decodeWhole (requestReader (protoVersion 38)) (builtBytes (Wire.putNum (12 :: Word64) <> Wire.putBytes link)) recorded = Right . Ops.AddIndirectRoot refused link = wireRefusal ("the link '" <> TE.decodeUtf8Lenient link <> "' is not an absolute Windows path: it needs a drive and a backslash, as in C:\\result, or a UNC share") in pure $ assertEqual "absolute and canonical" (recorded "C:\\home\\user\\result") (rootedLink "C:\\home\\user\\result") `andThen` assertEqual "dots" (recorded "C:\\home\\user\\result2") (rootedLink "C:\\home\\user\\..\\user\\.\\result2\\") `andThen` assertEqual "a drive's root" (recorded "C:\\result") (rootedLink "C:\\home\\..\\..\\result") `andThen` assertEqual "a share" (recorded "\\\\server\\share\\result") (rootedLink "\\\\server\\share\\dir\\..\\result") `andThen` assertEqual "relative" (refused "home\\user\\result") (rootedLink "home\\user\\result") `andThen` assertEqual "a drive's relative directory" (refused "C:result") (rootedLink "C:result") `andThen` assertEqual "rooted without a drive" (refused "\\home\\user\\result") (rootedLink "\\home\\user\\result") `andThen` assertEqual "POSIX" (refused "/home/user/result") (rootedLink "/home/user/result") `andThen` assertEqual "no UTF-8 reading" (refused "C:\\\xff") (rootedLink "C:\\\xff"), runTestM "a client's settings read back as themselves" $ codecProperty $ QC.forAll genClientSettings $ \settings -> decodeWhole Ops.getClientSettings (builtBytes (Ops.putClientSettings settings)) QC.=== Right settings, runTestM "what realising paths would take, a collection's result, a derivation's outputs and the roots read back as themselves" $ codecProperty $ QC.forAll ((,,,) <$> genMissing <*> genGCResult <*> genOutputMap <*> genRoots) $ \(missing, collected, outputs, roots) -> QC.conjoin [ decodeWhole (Proto.getMissing wireStoreDir) (builtBytes (Proto.putMissing wireStoreDir missing)) QC.=== Right missing, decodeWhole Proto.getGCResult (builtBytes (Proto.putGCResult collected)) QC.=== Right collected, decodeWhole (Proto.getOutputMap wireStoreDir) (builtBytes (Proto.putOutputMap wireStoreDir outputs)) QC.=== Right outputs, decodeWhole (Proto.getRoots wireStoreDir) (builtBytes (Proto.putRoots wireStoreDir roots)) QC.=== Right roots ], runTestM "build results with the paths they answer read back as far as each version carries them" $ codecProperty $ QC.conjoin [ QC.counterexample (show version) $ QC.forAll (QC.resize 3 (QC.listOf (Proto.KeyedBuildResult <$> (genDerivedPath `QC.suchThat` spellable version) <*> genBuildResult))) $ \results -> let (bytes, refusal) = Proto.putKeyedBuildResults wireStoreDir version results in refusal QC.=== Nothing QC..&&. decodeWhole (Proto.getKeyedBuildResults wireStoreDir version) (builtBytes bytes) QC.=== Right [Proto.KeyedBuildResult (carriedDerivedPath version path) (carriedBuildResult version result) | Proto.KeyedBuildResult path result <- results] | version <- gateVersions ], runTestM "a daemon's message to its client reads back as far as each version carries it" $ codecProperty $ roundTripsAtEveryVersion (const genStderrMessage) carriedStderrMessage Proto.getStderrMessage Proto.putStderrMessage, runTest "a daemon's messages, its errors and a collection's paths are laid out as upstream writes them" $ let word = Wire.putNum :: Word64 -> BB.Builder failure = Proto.DaemonError (Proto.Verbosity 3) "msg" ["outer", "inner"] 7 activity = Proto.Activity (Proto.ActivityId 5) (Proto.Verbosity 4) (Proto.ActivityType 105) "text" [Proto.FieldInt 9, Proto.FieldString "s"] (Proto.ActivityId 2) written version message = builtBytes (Proto.putStderrMessage (protoVersion version) message) in assertEqual "error record" (builtBytes (word 0x63787470 <> Wire.putBytes "Error" <> word 3 <> Wire.putBytes "Error" <> Wire.putBytes "msg" <> word 0 <> word 2 <> word 0 <> Wire.putBytes "outer" <> word 0 <> Wire.putBytes "inner")) (written 26 (Proto.StderrError failure)) `andThen` assertEqual "error before 1.26" (builtBytes (word 0x63787470 <> Wire.putBytes "msg" <> word 7)) (written 25 (Proto.StderrError failure)) `andThen` assertEqual "activity" (builtBytes (word 0x53545254 <> word 5 <> word 4 <> word 105 <> Wire.putBytes "text" <> word 2 <> word 0 <> word 9 <> word 1 <> Wire.putBytes "s" <> word 2)) (written 38 (Proto.StderrStartActivity activity)) `andThen` assertEqual "result" (builtBytes (word 0x52534c54 <> word 5 <> word 101 <> word 1 <> word 1 <> Wire.putBytes "s")) (written 38 (Proto.StderrResult (Proto.ActivityId 5) (Proto.ResultType 101) [Proto.FieldString "s"])) `andThen` assertEqual "stop" (builtBytes (word 0x53544f50 <> word 5)) (written 38 (Proto.StderrStopActivity (Proto.ActivityId 5))) `andThen` assertEqual "read" (builtBytes (word 0x64617461 <> word 4096)) (written 38 (Proto.StderrRead 4096)) `andThen` assertEqual "action" (builtBytes (word 3)) (builtBytes (Proto.putGCAction Proto.DeleteSpecific)) `andThen` assertEqual "specific paths" (builtBytes (word 0 <> word 1 <> Wire.putBytes "/nix/store/g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-foo" <> word 1)) (builtBytes (Proto.putGCPaths wireStoreDir (Proto.SpecificPaths (Set.singleton (g1w7 "foo")) True))) `andThen` assertEqual "whole store" (builtBytes (word 1)) (builtBytes (Proto.putGCPaths wireStoreDir Proto.WholeStore)) `andThen` assertEqual "features" (builtBytes (word 2 <> Wire.putBytes "a" <> Wire.putBytes "b")) (builtBytes (Proto.putFeatures (Set.fromList [Proto.Feature "b", Proto.Feature "a"]))), runTest "a daemon's message is refused in upstream's words" $ let version = protoVersion 38 readMessage builder = decodeWhole (Proto.getStderrMessage version) (builtBytes builder) in assertEqual "message" (wireRefusal "got unknown message type 1234 from Nix daemon") (readMessage (Wire.putNum (0x1234 :: Word64))) `andThen` assertEqual "error type" (wireRefusal "unexpected error type 'Oops'") (readMessage (Wire.putNum (0x63787470 :: Word64) <> Wire.putBytes "Oops")) `andThen` assertEqual "position" (wireRefusal "deserializing error positions is not supported") (readMessage (Wire.putNum (0x63787470 :: Word64) <> Wire.putBytes "Error" <> Wire.putNum (0 :: Word64) <> Wire.putBytes "Error" <> Wire.putBytes "msg" <> Wire.putNum (1 :: Word64))) `andThen` assertEqual "field" (wireRefusal "got unsupported field type 2 from Nix daemon") (readMessage (Wire.putNum (0x52534c54 :: Word64) <> Wire.putNum (1 :: Word64) <> Wire.putNum (0 :: Word64) <> Wire.putNum (1 :: Word64) <> Wire.putNum (2 :: Word64))) ] where readStorePath spelled = decodeWhole (Proto.getStorePath wireStoreDir) (builtBytes (Wire.putBytes (TE.encodeUtf8 spelled)))-- | A store path under upstream's fixtures' hash.g1w7 :: Text -> StorePathg1w7 = StorePath "g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q"-- | The environment variable naming a directory holding upstream's-- worker-protocol fixtures (@src/libstore-tests/data/worker-protocol@ at-- the tag CI fetches). Unset, the group skips; set, every fixture must be-- there.workerProtocolDirVar :: StringworkerProtocolDirVar = "NOVA_NIX_TEST_WORKER_PROTOCOL_DIR"-- | One of upstream's fixtures and what reading it must give: the value-- its own test gives at the version it reads at, and, where upstream-- writes the value back too, the same bytes from writing what was read.wireFixture :: (Eq a, Show a) => FilePath -> Wire.Decoder a -> Maybe a -> Maybe (a -> Either Text BB.Builder) -> (FilePath, BS.ByteString -> TestResult)wireFixture stem reader expected writer = (stem <> ".bin", check) where check bytes = case (decodeWhole reader bytes, expected) of (Left err, _) -> Fail ("read: " <> err) (Right _, Nothing) -> Fail "the expected value does not build" (Right value, Just wanted) -> assertEqual "read" wanted value `andThen` case writer of Nothing -> Pass Just write -> assertRight "write" (write value) (assertEqual "written" bytes . builtBytes)-- | A writer that cannot refuse.totalWriter :: (a -> BB.Builder) -> Maybe (a -> Either Text BB.Builder)totalWriter writer = Just (Right . writer)-- | Upstream 2.35.4's worker-protocol fixtures, each as its-- @worker-protocol.cc@ reads it. @build-result-1.28@, @-1.29@ and @-1.37@-- hold outputs in the older JSON form with a real derivation hash, which-- upstream reads but writes back with 'dummy' hashes, so it reads them only-- (@build-result-1.29-compat@ is the form it writes).upstreamWireFixtures :: [(FilePath, BS.ByteString -> TestResult)]upstreamWireFixtures = [ -- Upstream's last string is the C literal "oh no \0\0\0 what was that!", -- which becomes a std::string at its first NUL. wireFixture "string" (replicateM 5 Wire.getBytes) (Just ["", "hi", "white rabbit", BS.pack [0xe5, 0xa4, 0xa7, 0xe7, 0x99, 0xbd, 0xe5, 0x85, 0x94], "oh no "]) (totalWriter (foldMap Wire.putBytes)), wireFixture "store-path" (replicateM 2 (Proto.getStorePath defaultStoreDir)) (Just [g1w7 "foo", g1w7 "foo-bar"]) (totalWriter (foldMap (Proto.putStorePath defaultStoreDir))), wireFixture "content-address" (replicateM 3 Proto.getContentAddress) (sequence [textDerive, flatBlob, narParens]) (totalWriter (foldMap Proto.putContentAddress)), wireFixture "derived-path-1.29" (derivedPaths 29 3) (Just [Proto.DerivedOpaque (g1w7 "foo"), Proto.DerivedBuilt (g1w7 "bar.drv") Proto.AllOutputs, builtXY]) (derivedWriter 29), wireFixture "derived-path-1.30" (derivedPaths 30 4) (Just [Proto.DerivedOpaque (g1w7 "foo"), Proto.DerivedOpaque (g1w7 "foo.drv"), Proto.DerivedBuilt (g1w7 "bar.drv") Proto.AllOutputs, builtXY]) (derivedWriter 30), wireFixture "drv-output-realisation-with-path-not-hash" (replicateM 2 (Proto.getDrvOutput defaultStoreDir realisationVersion)) (Just [Proto.DrvOutput (g1w7 "foo.drv") (Proto.OutputName "baz"), Proto.DrvOutput (g1w7 "foo.drv") (Proto.OutputName "quux")]) (Just (fmap mconcat . traverse (Proto.putDrvOutput defaultStoreDir realisationVersion))), wireFixture "unkeyed-realisation-realisation-with-path-not-hash" (Proto.getUnkeyedRealisation defaultStoreDir realisationVersion) (Proto.UnkeyedRealisation (g1w7 "foo") <$> zeroSignatures ["asdf", "qwer"]) (Just (Proto.putUnkeyedRealisation defaultStoreDir realisationVersion)), wireFixture "realisation-realisation-with-path-not-hash" (Proto.getRealisation defaultStoreDir realisationVersion) (Proto.Realisation (Proto.DrvOutput (g1w7 "foo.drv") (Proto.OutputName "baz")) . Proto.UnkeyedRealisation (g1w7 "foo") <$> zeroSignatures ["asdf", "qwer"]) (Just (Proto.putRealisation defaultStoreDir realisationVersion)), wireFixture "build-result-1.27" (buildResults (protoVersion 27)) (Just [rejected, notDeterministic False 0, built Map.empty 0 Nothing]) (buildWriter (protoVersion 27)), wireFixture "build-result-1.28" (buildResults (protoVersion 28)) (Just [rejected, notDeterministic False 0, built fooBar 0 Nothing]) Nothing, wireFixture "build-result-1.29" (buildResults (protoVersion 29)) (Just [rejected, notDeterministic True 3, built fooBar 1 Nothing]) Nothing, wireFixture "build-result-1.29-compat" (buildResults (protoVersion 29)) (Just [rejected, notDeterministic True 3, built fooBar 1 Nothing]) (buildWriter (protoVersion 29)), wireFixture "build-result-1.37" (buildResults (protoVersion 37)) (Just [rejected, notDeterministic True 3, built fooBar 1 cpuTimes]) Nothing, wireFixture "build-result-realisation-with-path-not-hash" (buildResults realisationVersion) (Just [rejected, notDeterministic True 3, built fooBar 1 cpuTimes]) (buildWriter realisationVersion), wireFixture "keyed-build-result-1.29" (replicateM 2 (Proto.getKeyedBuildResult defaultStoreDir (protoVersion 29))) ( Just [ Proto.KeyedBuildResult (Proto.DerivedOpaque (g1w7 "xxx")) rejected, Proto.KeyedBuildResult (Proto.DerivedBuilt (g1w7 "bar.drv") (fromMaybe Proto.AllOutputs (Proto.namedOutputs (Set.singleton (Proto.OutputName "out"))))) (notDeterministic True 3) ] ) (Just (fmap mconcat . traverse (Proto.putKeyedBuildResult defaultStoreDir (protoVersion 29)))), wireFixture "unkeyed-valid-path-info-1.15" (replicateM 2 (Proto.getUnkeyedValidPathInfo defaultStoreDir (protoVersion 15))) (sequence [pathInfo Nothing [], pathInfo (Just (g1w7 "bar.drv")) [StorePath "g1w7hyyyy1w7hy3qg1w7hy3qgqqqqy3q" "foo.drv"]]) (totalWriter (foldMap (Proto.putUnkeyedValidPathInfo defaultStoreDir (protoVersion 15)))), wireFixture "valid-path-info-1.15" (replicateM 2 (Proto.getValidPathInfo defaultStoreDir (protoVersion 15))) (sequence [Proto.ValidPathInfo (g1w7 "bar") <$> pathInfo Nothing [], Proto.ValidPathInfo (g1w7 "bar") <$> pathInfo (Just (g1w7 "bar.drv")) [yyyyFoo, g1w7 "bar"]]) (totalWriter (foldMap (Proto.putValidPathInfo defaultStoreDir (protoVersion 15)))), wireFixture "valid-path-info-1.16" (replicateM 3 (Proto.getValidPathInfo defaultStoreDir (protoVersion 16))) ( sequence [ Proto.ValidPathInfo (g1w7 "bar") . (\info -> info {Proto.upiUltimate = True}) <$> pathInfo Nothing [], Proto.ValidPathInfo (g1w7 "bar") <$> ((\info sigs -> info {Proto.upiSignatures = sigs}) <$> pathInfo (Just (g1w7 "bar.drv")) [yyyyFoo, g1w7 "bar"] <*> zeroSignatures ["fake-sig-1", "fake-sig-2"]), fixedFoo >>= \path -> Proto.ValidPathInfo path <$> ((\info ca -> info {Proto.upiContentAddress = Just ca}) <$> pathInfo Nothing [g1w7 "bar", path] <*> narParens) ] ) (totalWriter (foldMap (Proto.putValidPathInfo defaultStoreDir (protoVersion 16)))), wireFixture "build-mode" (replicateM 3 Proto.getBuildMode) (Just [Proto.BuildNormal, Proto.BuildRepair, Proto.BuildCheck]) (totalWriter (foldMap Proto.putBuildMode)), wireFixture "optional-trusted-flag" (replicateM 3 Proto.getTrust) (Just [Nothing, Just Proto.Trusted, Just Proto.NotTrusted]) (totalWriter (foldMap Proto.putTrust)), wireFixture "vector" ((,) <$> replicateM 3 (Wire.getList Wire.getBytes) <*> Wire.getList (Wire.getList Wire.getBytes)) (Just ([[], [""], ["", "foo", "bar"]], [[], [""], ["", "1", "2"]])) (totalWriter (\(vectors, nested) -> foldMap (Wire.putList Wire.putBytes) vectors <> Wire.putList (Wire.putList Wire.putBytes) nested)), wireFixture "set" ((,) <$> replicateM 3 stringSet <*> (Set.fromList <$> Wire.getList stringSet)) (Just ([Set.empty, Set.singleton "", Set.fromList ["", "foo", "bar"]], Set.fromList [Set.empty, Set.singleton "", Set.fromList ["", "1", "2"]])) (totalWriter (\(sets, nested) -> foldMap putStringSet sets <> Wire.putList putStringSet (Set.toAscList nested))), wireFixture "optional-store-path" (replicateM 2 (Proto.getOptionalStorePath defaultStoreDir)) (Just [Nothing, Just (g1w7 "foo-bar")]) (totalWriter (foldMap (Proto.putOptionalStorePath defaultStoreDir))), wireFixture "optional-content-address" (replicateM 2 Proto.getOptionalContentAddress) (sequence [Just Nothing, Just <$> flatBlob]) (totalWriter (foldMap Proto.putOptionalContentAddress)), wireFixture "client-handshake-info_1_30" (replicateM 1 (Proto.getHandshakeInfo (protoVersion 30))) (Just [Proto.HandshakeInfo Nothing Nothing]) (handshakeWriter 30), wireFixture "client-handshake-info_1_33" (replicateM 2 (Proto.getHandshakeInfo (protoVersion 33))) (Just [Proto.HandshakeInfo (Just "foo") Nothing, Proto.HandshakeInfo (Just "bar") Nothing]) (handshakeWriter 33), wireFixture "client-handshake-info_1_35" (replicateM 2 (Proto.getHandshakeInfo (protoVersion 35))) (Just [Proto.HandshakeInfo (Just "foo") (Just Proto.NotTrusted), Proto.HandshakeInfo (Just "bar") (Just Proto.Trusted)]) (handshakeWriter 35), alsoWrittenByTheDaemon (wireFixture "handshake-to-client" (Proto.getServerMagic *> Proto.getVersionNumber) (Just (Proto.VersionNumber 1 10)) (totalWriter (\number -> Proto.putServerMagic <> Proto.putVersionNumber number))) ] where derivedPaths minor count = replicateM count (Proto.getDerivedPath defaultStoreDir (protoVersion minor)) derivedWriter minor = Just (fmap mconcat . traverse (Proto.putDerivedPath defaultStoreDir (protoVersion minor))) builtXY = Proto.DerivedBuilt (g1w7 "bar.drv") (fromMaybe Proto.AllOutputs (Proto.namedOutputs (Set.fromList [Proto.OutputName "x", Proto.OutputName "y"]))) buildResults version = replicateM 3 (Proto.getBuildResult defaultStoreDir version) buildWriter version = totalWriter (foldMap (Proto.putBuildResult defaultStoreDir version)) result outcome timesBuilt cpu = Proto.BuildResult outcome timesBuilt (if timesBuilt == 0 then 0 else 30) (if timesBuilt == 0 then 0 else 50) (fst <$> cpu) (snd <$> cpu) rejected = result (Proto.Failed (Proto.Failure Proto.OutputRejected "no idea why" False)) 0 Nothing notDeterministic nonDeterministic timesBuilt = result (Proto.Failed (Proto.Failure Proto.NotDeterministic "no idea why" nonDeterministic)) timesBuilt Nothing built outputs = result (Proto.Succeeded (Proto.Success Proto.Built outputs)) fooBar = Map.fromList [(Proto.OutputName name, Proto.UnkeyedRealisation (g1w7 name) Set.empty) | name <- ["foo", "bar"]] cpuTimes = Just (500000000, 604000000) zeroSignatures names = Set.fromList <$> traverse (\name -> Proto.signatureFromParts name (BS.replicate 64 0)) names contentAddress method algo input = Hash.rawHashWithAlgo algo input >>= Proto.contentAddressFromParts method algo textDerive = contentAddress Proto.TextMethod "sha256" "Derive(...)" flatBlob = contentAddress (Proto.FixedMethod FlatIngestion) "sha1" "blob blob..." narParens = contentAddress (Proto.FixedMethod NarIngestion) "sha256" "(...)" narHash = Hash.base64ToBytes "FePFYIlMuycIXPZbWi7LGEiMmZSX9FMbaQenWBzm1Sc=" >>= Proto.narHashFromDigest pathInfo deriver references = (\hash -> Proto.UnkeyedValidPathInfo deriver hash (Set.fromList references) 23423 34878 False Set.empty Nothing) <$> narHash yyyyFoo = StorePath "g1w7hyyyy1w7hy3qg1w7hy3qgqqqqy3q" "foo" -- The path upstream's makeFromCA gives "foo" with that content -- address, referring to bar and to itself. fixedFoo = either (const Nothing) Just (Hash.makeStorePath defaultStoreDir "source:/nix/store/g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-bar:self" (sha256Digest "(...)") "foo") stringSet = Set.fromList <$> Wire.getList Wire.getBytes putStringSet strings = Wire.putList Wire.putBytes (Set.toAscList strings) handshakeWriter minor = totalWriter (foldMap (\(Proto.HandshakeInfo daemonVersion trust) -> Proto.putHandshakeInfo (protoVersion minor) (fromMaybe BS.empty daemonVersion) trust))-- | Fixtures upstream 2.35.4 keeps that no test of its reads: realisations-- keyed by a derivation's hash, the form 2.35.4 stopped speaking. Read as-- 2.35.4 reads a realisation, each is refused.orphanedWireFixtures :: [(FilePath, BS.ByteString -> TestResult)]orphanedWireFixtures = [ ("drv-output.bin", refused (Proto.getDrvOutput defaultStoreDir realisationVersion)), ("realisation.bin", refused (Proto.getRealisation defaultStoreDir realisationVersion)), ("realisation-with-deps.bin", refused (Proto.getRealisation defaultStoreDir realisationVersion)) ] where refused reader bytes = case Wire.runDecoder reader bytes of Left (Wire.Malformed _) -> Pass other -> Fail ("expected a refusal, got " <> T.pack (show (fmap snd other)))-- | Upstream's worker-protocol fixtures read, and written back where-- upstream writes them, byte for byte. Every @.bin@ in the directory-- must have a case, so a fixture a newer tag adds fails here until it is-- read.testDaemonFixtures :: IO [Bool]testDaemonFixtures = do putStrLn "daemon/fixtures" named <- lookupEnv workerProtocolDirVar case named of Nothing -> do putStrLn (" SKIP needs " ++ workerProtocolDirVar) pure [] Just dir -> do present <- Dir.doesDirectoryExist dir if not present then (: []) <$> runTest (T.pack workerProtocolDirVar <> " names a directory") (Fail (T.pack dir)) else do let cases = upstreamWireFixtures ++ orphanedWireFixtures listed <- filter (".bin" `isSuffixOf`) <$> Dir.listDirectory dir let unread = filter (`notElem` map fst cases) listed checked <- mapM (readFixture dir) cases complete <- runTest "every fixture has a case" (assertEqual "fixtures with no case" [] (sort unread)) pure (checked ++ [complete]) where readFixture dir (file, check) = runTestM (T.pack file) $ do exists <- Dir.doesFileExist (dir </> file) if exists then check <$> BS.readFile (dir </> file) else pure (Fail "missing")-- ----------------------------------------------------------------------------- Tests: the daemon's side of a connection-- ----------------------------------------------------------------------------- Wire bytes spelled out by hand, apart from the codec, so a script holds-- what the connection writes to upstream's layout rather than to the-- codec's own idea of it.-- | A number as upstream writes every one: eight bytes, little-endian.le64 :: Word64 -> BS.ByteStringle64 n = BS.pack [fromIntegral (n `shiftR` (8 * i)) | i <- [0 .. 7]]-- | A string: its length, its bytes, and zeros to a multiple of eight.wstr :: BS.ByteString -> BS.ByteStringwstr bytes = le64 (fromIntegral (BS.length bytes)) <> bytes <> BS.replicate ((8 - BS.length bytes `mod` 8) `mod` 8) 0-- | A list of strings.wstrs :: [BS.ByteString] -> BS.ByteStringwstrs items = le64 (fromIntegral (length items)) <> BS.concat (map wstr items)-- | A chunk of a framed stream, and the empty one that ends it.wframe :: BS.ByteString -> BS.ByteStringwframe chunk = le64 (fromIntegral (BS.length chunk)) <> chunkframeEnd :: BS.ByteStringframeEnd = le64 0-- | The words that open the daemon's messages, and its handshake's.nextWord, lastWord, errorWord, startWord, stopWord, resultWord, clientMagicWord, serverMagicWord :: Word64nextWord = 0x6f6c6d67lastWord = 0x616c7473errorWord = 0x63787470startWord = 0x53545254stopWord = 0x53544f50resultWord = 0x52534c54clientMagicWord = 0x6e697863serverMagicWord = 0x6478696f-- | A line, the end of an operation's work, and an error as a record-- (from 1.26) and as its message and exit status (before).msgNext :: BS.ByteString -> BS.ByteStringmsgNext line = le64 nextWord <> wstr linemsgLast :: BS.ByteStringmsgLast = le64 lastWordmsgError :: BS.ByteString -> BS.ByteStringmsgError message = le64 errorWord <> wstr "Error" <> le64 0 <> wstr "Error" <> wstr message <> le64 0 <> le64 0msgErrorBefore126 :: BS.ByteString -> BS.ByteStringmsgErrorBefore126 message = le64 errorWord <> wstr message <> le64 1-- | A path as the wire names it.pathOnWire :: StorePath -> BS.ByteStringpathOnWire = TE.encodeUtf8 . storePathToText defaultStoreDir-- | A set of paths, in order.wpaths :: [StorePath] -> BS.ByteStringwpaths = wstrs . map pathOnWire . Set.toAscList . Set.fromList-- | A signature as the wire spells it.sigBytes :: Proto.Signature -> BS.ByteStringsigBytes sig = Proto.sigKeyName sig <> ":" <> TE.encodeUtf8 (B64.encode (Proto.sigBytes sig))-- | A path's info as a version from 1.16 writes it.winfo :: Proto.UnkeyedValidPathInfo -> BS.ByteStringwinfo info = wstr (maybe "" pathOnWire (Proto.upiDeriver info)) <> wstr (TE.encodeUtf8 (Hash.bytesToHexText (Proto.narHashDigest (Proto.upiNarHash info)))) <> wpaths (Set.toList (Proto.upiReferences info)) <> le64 (fromIntegral (Proto.upiRegistrationTime info)) <> le64 (Proto.upiNarSize info) <> le64 (if Proto.upiUltimate info then 1 else 0) <> wstrs (map sigBytes (Set.toAscList (Proto.upiSignatures info))) <> wstr ""-- | The features the scripts' daemon offers, as it lists them.serverFeatures :: [BS.ByteString]serverFeatures = ["delete-dead-specific-referrers", "realisation-with-path-not-hash"]-- | The Nix version the scripts' daemon names itself by.serverNixVersion :: BS.ByteStringserverNixVersion = "nova-nix (test)"-- | The substituter the scripts' daemon uses, and the one it trusts for-- its clients.daemonSubstituter, trustedSubstituter :: TextdaemonSubstituter = "https://cache.example.org/"trustedSubstituter = "https://trusted.example.org/"serverConfigAt :: Proto.Version -> Conn.ServerConfigserverConfigAt version = Conn.ServerConfig { Conn.scStoreDir = defaultStoreDir, Conn.scVersion = version, Conn.scNixVersion = serverNixVersion, Conn.scVerbosity = Proto.Verbosity 3, Conn.scConfig = defaultNixConfig {ncSubstituters = [daemonSubstituter], ncTrustedSubstituters = [trustedSubstituter]} }serverConfig :: Conn.ServerConfigserverConfig = serverConfigAt (Proto.Version Proto.latestVersionNumber (Set.fromList (map Proto.Feature serverFeatures)))-- | What a client at a minor version opens a connection with: the magic-- word, its version, its features from 1.38 (one the daemon does not-- offer among them), and its obsolete fields.clientHello :: Word8 -> BS.ByteStringclientHello minor = le64 clientMagicWord <> le64 (0x100 + fromIntegral minor) <> (if minor >= 38 then wstrs ["realisation-with-path-not-hash", "some-other-feature", "delete-dead-specific-referrers"] else "") <> (if minor >= 14 then le64 0 else "") <> (if minor >= 11 then le64 0 else "")-- | What the daemon answers a client's opening with: its magic word and-- version, its features from 1.38, its Nix version from 1.33, its trust-- from 1.35, and the end of its startup work.serverHello :: Word8 -> Proto.Trust -> BS.ByteStringserverHello minor trust = le64 serverMagicWord <> le64 0x126 <> (if minor >= 38 then wstrs serverFeatures else "") <> (if minor >= 33 then wstr serverNixVersion else "") <> (if minor >= 35 then le64 (if trust == Proto.Trusted then 1 else 2) else "") <> msgLast-- | Paths the scripts name: valid ones, one that refers to another, a-- derivation, one a substituter offers, one nothing knows, one whose-- query reports as it works, two uploads, and a dump's.fooPath, barPath, drvPath, offeredPath, missingPath, noisyPath, newPath, refusedPath, dumpPath :: StorePathfooPath = StorePath "00000000000000000000000000000001" "foo"barPath = StorePath "00000000000000000000000000000002" "bar"drvPath = StorePath "00000000000000000000000000000003" "foo.drv"offeredPath = StorePath "00000000000000000000000000000004" "offered"missingPath = StorePath "00000000000000000000000000000005" "missing"noisyPath = StorePath "00000000000000000000000000000006" "noisy"newPath = StorePath "00000000000000000000000000000007" "new"refusedPath = StorePath "00000000000000000000000000000008" "refused"dumpPath = StorePath "00000000000000000000000000000009" "dump"-- | A path's NAR in the scripts.narOf :: StorePath -> BS.ByteStringnarOf path = "nar of " <> TE.encodeUtf8 (spName path)-- | A path's info whose NAR is 'narOf' the path.infoFor :: StorePath -> [StorePath] -> Maybe StorePath -> Maybe Proto.UnkeyedValidPathInfoinfoFor path references deriver = withNar <$> Proto.narHashFromDigest (sha256Digest (narOf path)) where withNar narHash = Proto.UnkeyedValidPathInfo { Proto.upiDeriver = deriver, Proto.upiNarHash = narHash, Proto.upiReferences = Set.fromList references, Proto.upiRegistrationTime = 1700000000, Proto.upiNarSize = fromIntegral (BS.length (narOf path)), Proto.upiUltimate = False, Proto.upiSignatures = Set.empty, Proto.upiContentAddress = Nothing }-- | The infos the scripts' store and uploads hold.data Fixtures = Fixtures { fooInfo :: !Proto.UnkeyedValidPathInfo, barInfo :: !Proto.UnkeyedValidPathInfo, drvInfo :: !Proto.UnkeyedValidPathInfo, noisyInfo :: !Proto.UnkeyedValidPathInfo, newInfo :: !Proto.UnkeyedValidPathInfo, refusedInfo :: !Proto.UnkeyedValidPathInfo }fixtures :: Maybe Fixturesfixtures = Fixtures <$> infoFor fooPath [] (Just drvPath) <*> infoFor barPath [fooPath] Nothing <*> infoFor drvPath [] Nothing <*> infoFor noisyPath [] Nothing <*> infoFor newPath [fooPath] Nothing <*> infoFor refusedPath [] Nothing-- | A script's test, given the fixtures.scriptTest :: Text -> (Fixtures -> TestResult) -> IO BoolscriptTest name check = runTest name (maybe (Fail "the fixtures do not build") check fixtures)-- | The scripts' store: the valid paths and their infos, what it was-- asked in order, latest first, the NARs it imported, and the settings-- its latest call ran under.data Fake = Fake { fakeValid :: !(Map.Map StorePath Proto.UnkeyedValidPathInfo), fakeCalls :: ![Text], fakeImports :: ![(StorePath, BS.ByteString)], fakeSettings :: !(Maybe Ops.ConnectionSettings) }-- | The store every script starts with.startingStore :: Fixtures -> FakestartingStore fx = Fake (Map.fromList [(fooPath, fooInfo fx), (barPath, barInfo fx), (drvPath, drvInfo fx), (noisyPath, noisyInfo fx)]) [] [] Nothing-- | What a script runs over: the client's input still to come, what the-- daemon has written, latest first, and the store.data World = World { worldInput :: ![BS.ByteString], worldOutput :: ![BS.ByteString], worldFake :: !Fake }type Scripted = State WorldscriptTransport :: Conn.Transport ScriptedscriptTransport = Conn.Transport { Conn.transportReceive = state $ \world -> case worldInput world of [] -> (Nothing, world) chunk : rest -> (Just chunk, world {worldInput = rest}), Conn.transportSend = \bytes -> modify' (\world -> world {worldOutput = builtBytes bytes : worldOutput world}) }onFake :: (Fake -> Fake) -> Scripted ()onFake change = modify' (\world -> world {worldFake = change (worldFake world)})validPaths :: Scripted (Map.Map StorePath Proto.UnkeyedValidPathInfo)validPaths = gets (fakeValid . worldFake)-- | Record a call, and the settings it ran under.asked :: Ops.Work Scripted -> Text -> Scripted ()asked w call = onFake (\fake -> fake {fakeCalls = call : fakeCalls fake, fakeSettings = Just (Ops.workSettings w)})-- | An intake that keeps what it is fed and acts on all of it at its end,-- recording an upload that broke off.collecting :: BS.ByteString -> (BS.ByteString -> Scripted (Either Proto.DaemonError a)) -> Ops.Intake Scripted acollecting held atEnd = Ops.Taking (\chunk -> pure (collecting (held <> chunk) atEnd)) (atEnd held) (onFake (\fake -> fake {fakeCalls = "broken off" : fakeCalls fake}))-- | What a build reports: its activity's start (a build's, type 105), a-- line its builder wrote (a result of type 101), and its stop.buildEvents :: [Ops.LogEvent]buildEvents = [ Ops.ActivityStarted (Proto.Activity (Proto.ActivityId 7) (Proto.Verbosity 3) (Proto.ActivityType 105) "building noisy" [Proto.FieldString "noisy.drv", Proto.FieldInt 1] (Proto.ActivityId 0)), Ops.ActivityResult (Proto.ActivityId 7) (Proto.ResultType 101) [Proto.FieldString "a build line"], Ops.ActivityStopped (Proto.ActivityId 7) ]-- | Those reports as upstream's daemon sends them from 1.20.buildBytes :: BS.ByteStringbuildBytes = (le64 startWord <> le64 7 <> le64 3 <> le64 105 <> wstr "building noisy" <> le64 2 <> le64 1 <> wstr "noisy.drv" <> le64 0 <> le64 1 <> le64 0) <> (le64 resultWord <> le64 7 <> le64 101 <> le64 1 <> le64 1 <> wstr "a build line") <> (le64 stopWord <> le64 7)-- | What querying 'noisyPath' reports as it works: a line at the info-- level, one at a level above it, and a build.noisyEvents :: [Ops.LogEvent]noisyEvents = Ops.LogLine (Proto.Verbosity 3) "checking noisy" : Ops.LogLine (Proto.Verbosity 5) "too quiet to hear" : buildEvents-- | A build's result in the scripts: built once, its output at 'fooPath'.builtResult :: Proto.BuildResultbuiltResult = Proto.BuildResult (Proto.Succeeded (Proto.Success Proto.Built (Map.singleton (Proto.OutputName "out") (Proto.UnkeyedRealisation fooPath Set.empty)))) 1 10 20 Nothing Nothing-- | The roots the scripts' store holds, as a client is shown them.rootsShown :: Ops.RootCensoring -> Map.Map StorePath (Set.Set BS.ByteString)rootsShown censoring = Map.singleton fooPath (Set.singleton link) where link = case censoring of Ops.ShowRoots -> "/home/user/result" Ops.CensorRoots -> "{censored}"-- | Two links a scripted client asks the daemon to root, each as the client-- spells it and as the daemon makes it absolute. A POSIX daemon takes a-- relative link from @/@ and collapses the path; a Windows daemon takes an-- absolute link alone, so there both links are absolute.firstLink, secondLink :: (BS.ByteString, BS.ByteString)firstLink | SI.os == "mingw32" = ("C:\\home\\user\\result", "C:\\home\\user\\result") | otherwise = ("home/user/./result", "/home/user/result")secondLink | SI.os == "mingw32" = ("C:\\home\\user\\..\\user\\.\\result2\\", "C:\\home\\user\\result2") | otherwise = ("/home/user/../user//result2/", "/home/user/result2")-- | What the fake store notes of a link it is asked to root.askedRoot :: BS.ByteString -> TextaskedRoot link = "AddIndirectRoot " <> TE.decodeLatin1 link-- | Upstream's refusal of a path that is not valid.notValid :: StorePath -> Proto.DaemonErrornotValid path = Ops.daemonError ("path '" <> storePathToText defaultStoreDir path <> "' is not valid")fakeStore :: Ops.DaemonStore ScriptedfakeStore = Ops.DaemonStore { Ops.dsIsValidPath = \w path -> do asked w ("IsValidPath " <> spName path) when (path == noisyPath) (traverse_ (Ops.workReport w) noisyEvents) Right . Map.member path <$> validPaths, Ops.dsQueryValidPaths = \w substitute paths -> do asked w ("QueryValidPaths " <> T.pack (show substitute)) Right . (\known -> Set.filter (`Map.member` known) paths) <$> validPaths, Ops.dsQuerySubstitutablePaths = \w paths -> Right (Set.filter (== offeredPath) paths) <$ asked w "QuerySubstitutablePaths", Ops.dsQueryReferrers = \w path -> do asked w "QueryReferrers" Right . Map.keysSet . Map.filter (Set.member path . Proto.upiReferences) <$> validPaths, Ops.dsQueryValidDerivers = \w path -> do asked w "QueryValidDerivers" Right . maybe Set.empty (maybe Set.empty Set.singleton . Proto.upiDeriver) . Map.lookup path <$> validPaths, Ops.dsQueryDerivationOutputMap = \w _ -> Right (Map.fromList [(Proto.OutputName "out", Just fooPath), (Proto.OutputName "dev", Nothing)]) <$ asked w "QueryDerivationOutputMap", Ops.dsQueryAllValidPaths = \w -> asked w "QueryAllValidPaths" >> (Right . Map.keysSet <$> validPaths), Ops.dsQueryPathInfo = \w path -> asked w "QueryPathInfo" >> (Right . Map.lookup path <$> validPaths), Ops.dsQueryMissing = \w _ -> Right (Proto.Missing (Set.singleton drvPath) (Set.singleton offeredPath) Set.empty 10 20) <$ asked w "QueryMissing", Ops.dsAddToStore = \w upload -> do asked w ("AddToStore " <> TE.decodeLatin1 (Ops.duName upload) <> " " <> T.pack (show (Ops.duMethod upload)) <> " " <> Ops.duAlgo upload) pure . collecting BS.empty $ \dump -> do onFake (\fake -> fake {fakeImports = (dumpPath, dump) : fakeImports fake}) pure $ case Proto.narHashFromDigest (sha256Digest dump) of Nothing -> Left (Ops.daemonError "no hash") Just narHash -> Right (Proto.ValidPathInfo dumpPath (Proto.UnkeyedValidPathInfo Nothing narHash (Ops.duReferences upload) 1700000000 (fromIntegral (BS.length dump)) True Set.empty Nothing)), Ops.dsAddToStoreNar = \w (Proto.ValidPathInfo path info) repair checkSigs -> do asked w ("AddToStoreNar " <> spName path <> " " <> T.pack (show repair) <> " " <> T.pack (show checkSigs) <> " ultimate " <> T.pack (show (Proto.upiUltimate info))) importing path info repair <$> validPaths, Ops.dsBuildPaths = \w _ mode -> do asked w ("BuildPaths " <> T.pack (show mode)) Right () <$ traverse_ (Ops.workReport w) buildEvents, Ops.dsBuildPathsWithResults = \w targets mode -> Right [Proto.KeyedBuildResult target builtResult | target <- targets] <$ asked w ("BuildPathsWithResults " <> T.pack (show mode)), Ops.dsEnsurePath = \w path -> do asked w ("EnsurePath " <> spName path) (\known -> if Map.member path known then Right () else Left (notValid path)) <$> validPaths, Ops.dsAddTempRoot = \w path -> Right () <$ asked w ("AddTempRoot " <> spName path), Ops.dsAddIndirectRoot = \w link -> Right () <$ asked w ("AddIndirectRoot " <> TE.decodeLatin1 link), Ops.dsFindRoots = \w censoring -> Right (rootsShown censoring) <$ asked w ("FindRoots " <> T.pack (show censoring)), Ops.dsCollectGarbage = \w request -> Right (Proto.GCResult (Set.singleton (pathOnWire (StorePath "0000000000000000000000000000000a" "dead"))) 4096) <$ asked w ("CollectGarbage " <> T.pack (show request)), Ops.dsOptimiseStore = \w -> Right () <$ asked w "OptimiseStore", Ops.dsVerifyStore = \w contents repair -> Right False <$ asked w ("VerifyStore " <> T.pack (show contents) <> " " <> T.pack (show repair)), Ops.dsAddSignatures = \w path sigs -> Right () <$ asked w ("AddSignatures " <> spName path <> " " <> T.pack (show (Set.size sigs))), Ops.dsNarFromPath = \path sink -> do onFake (\fake -> fake {fakeCalls = ("NarFromPath " <> spName path) : fakeCalls fake}) known <- validPaths if Map.member path known then Right () <$ traverse_ sink [BS.take 4 (narOf path), BS.drop 4 (narOf path)] else Left (notValid path) <$ sink "partial" }-- | How the scripts' store imports a NAR: 'refusedPath' is refused before-- a byte is read, as upstream refuses an unsigned path; a valid path is-- left as it is without its NAR being read, unless it is repaired; any-- other is held to its info's hash and size.importing :: StorePath -> Proto.UnkeyedValidPathInfo -> Ops.Repair -> Map.Map StorePath Proto.UnkeyedValidPathInfo -> Ops.Intake Scripted ()importing path info repair known | path == refusedPath = Ops.Taken (Left (Ops.daemonError ("cannot add path '" <> storePathToText defaultStoreDir path <> "' because it lacks a signature by a trusted key"))) | Map.member path known && repair == Ops.NoRepair = Ops.Taken (Right ()) | otherwise = collecting BS.empty imported where imported nar | Proto.narHashFromDigest (sha256Digest nar) == Just (Proto.upiNarHash info) && fromIntegral (BS.length nar) == Proto.upiNarSize info = Right () <$ onFake (\fake -> fake {fakeValid = Map.insert path info (fakeValid fake), fakeImports = (path, nar) : fakeImports fake}) | otherwise = pure (Left (Ops.daemonError ("hash mismatch importing path '" <> storePathToText defaultStoreDir path <> "'")))-- | Run a client's bytes against the scripts' store: how the connection-- ended, every byte the daemon wrote, and the store after.runScript :: Conn.ServerConfig -> Proto.Trust -> Fake -> [BS.ByteString] -> (Conn.ConnectionEnd, BS.ByteString, Fake)runScript config trust fake input = (ended, BS.concat (reverse (worldOutput world)), worldFake world) where (ended, world) = runState (Conn.serveConnection config trust fakeStore scriptTransport) (World (filter (not . BS.null) input) [] fake)-- | A session at a minor version: what the daemon writes after its-- handshake, how the connection ends, and a check of the store after.assertSession :: Proto.Trust -> Word8 -> Fake -> [BS.ByteString] -> BS.ByteString -> Conn.ConnectionEnd -> (Fake -> TestResult) -> TestResultassertSession trust minor fake ops expected end check = let (ended, written, after) = runScript serverConfig trust fake (clientHello minor : ops) in assertEqual "written" (serverHello minor trust <> expected) written `andThen` assertEqual "end" end ended `andThen` check after-- | The store was asked exactly these, in order.askedOnly :: [Text] -> Fake -> TestResultaskedOnly calls fake = assertEqual "calls" calls (reverse (fakeCalls fake))-- | A request naming one path.reqPath :: Word64 -> StorePath -> BS.ByteStringreqPath code path = le64 code <> wstr (pathOnWire path)-- | Settings as upstream's client sends them, at a verbosity, with the-- other settings given.setOptionsAt :: Word64 -> [(BS.ByteString, BS.ByteString)] -> BS.ByteStringsetOptionsAt verbosity overrides = le64 19 <> foldMap le64 [1, 0, 1, verbosity, 1, 0, 1, 7, 0, 0, 4, 1] <> le64 (fromIntegral (length overrides)) <> foldMap (\(name, value) -> wstr name <> wstr value) overrides-- | A path's info as an upload sends it.uploadInfo :: StorePath -> Proto.UnkeyedValidPathInfo -> BS.ByteStringuploadInfo path info = wstr (pathOnWire path) <> winfo info-- | A path derived from 'drvPath', its output @out@.drvOut :: BS.ByteStringdrvOut = pathOnWire drvPath <> "!out"-- | The scripted connections: a client's bytes against a fake store, and-- every byte the daemon writes back, spelled out by hand.testDaemonServer :: IO [Bool]testDaemonServer = do putStrLn "daemon/server" sequence [ scriptTest "a trusted client's queries are each answered after the end of their work, as upstream's daemon answers them" $ \fx -> assertSession Proto.Trusted 38 (startingStore fx) [ setOptionsAt 3 [], reqPath 1 fooPath, reqPath 1 missingPath, reqPath 26 fooPath, reqPath 26 missingPath, le64 31 <> wpaths [fooPath, missingPath] <> le64 1, le64 32 <> wpaths [offeredPath, missingPath], reqPath 6 fooPath, reqPath 33 fooPath, reqPath 41 drvPath, le64 23, le64 40 <> wstrs [drvOut], reqPath 10 fooPath, reqPath 11 fooPath, le64 12 <> wstr (fst firstLink), le64 12 <> wstr (fst secondLink), le64 14, le64 20 <> le64 2 <> le64 1 <> le64 0 <> le64 100 <> le64 0 <> le64 0 <> le64 0, le64 34, le64 35 <> le64 1 <> le64 0, le64 37 <> wstr (pathOnWire fooPath) <> wstrs ["key:" <> TE.encodeUtf8 (B64.encode (BS.replicate 64 0))], reqPath 38 fooPath ] ( msgLast <> (msgLast <> le64 1) <> (msgLast <> le64 0) <> (msgLast <> le64 1 <> winfo (fooInfo fx)) <> (msgLast <> le64 0) <> (msgLast <> wpaths [fooPath]) <> (msgLast <> wpaths [offeredPath]) <> (msgLast <> wpaths [barPath]) <> (msgLast <> wpaths [drvPath]) <> (msgLast <> le64 2 <> wstr "dev" <> wstr "" <> wstr "out" <> wstr (pathOnWire fooPath)) <> (msgLast <> wpaths [fooPath, barPath, drvPath, noisyPath]) <> (msgLast <> wpaths [drvPath] <> wpaths [offeredPath] <> wpaths [] <> le64 10 <> le64 20) <> (msgLast <> le64 1) <> (msgLast <> le64 1) <> (msgLast <> le64 1) <> (msgLast <> le64 1) <> (msgLast <> le64 1 <> wstr "/home/user/result" <> wstr (pathOnWire fooPath)) <> (msgLast <> wstrs ["/nix/store/0000000000000000000000000000000a-dead"] <> le64 4096 <> le64 0) <> (msgLast <> le64 1) <> (msgLast <> le64 0) <> (msgLast <> le64 1) <> (msgLast <> narOf fooPath) ) Conn.ClientClosed ( askedOnly [ "IsValidPath foo", "IsValidPath missing", "QueryPathInfo", "QueryPathInfo", "QueryValidPaths Substitute", "QuerySubstitutablePaths", "QueryReferrers", "QueryValidDerivers", "QueryDerivationOutputMap", "QueryAllValidPaths", "QueryMissing", "EnsurePath foo", "AddTempRoot foo", askedRoot (snd firstLink), askedRoot (snd secondLink), "FindRoots ShowRoots", "CollectGarbage " <> T.pack (show (Ops.GCRequest Proto.DeleteDead Proto.WholeStore 100)), "OptimiseStore", "VerifyStore CheckContents NoRepair", "AddSignatures foo 1", "NarFromPath foo" ] ), scriptTest "a build's activity and its log line reach the client as it runs, and its results are keyed by the paths asked for" $ \fx -> assertSession Proto.Trusted 38 (startingStore fx) [le64 9 <> wstrs [drvOut] <> le64 0, le64 46 <> wstrs [drvOut] <> le64 2] ( buildBytes <> (msgLast <> le64 1) <> msgLast <> le64 1 <> wstr drvOut <> (le64 0 <> wstr "" <> le64 1 <> le64 0 <> le64 10 <> le64 20 <> le64 0 <> le64 0) <> (le64 1 <> wstr "out" <> wstr (pathOnWire fooPath) <> le64 0) ) Conn.ClientClosed (askedOnly ["BuildPaths BuildNormal", "BuildPathsWithResults BuildCheck"]), scriptTest "a message and an activity the store reports mid-operation reach the client as upstream's daemon forwards them" $ \fx -> assertSession Proto.Trusted 38 (startingStore fx) [reqPath 1 noisyPath] (msgNext "checking noisy\n" <> buildBytes <> msgLast <> le64 1) Conn.ClientClosed (const Pass), scriptTest "before 1.20 an activity's start reaches the client as a line, and the rest of what it reports does not" $ \fx -> assertSession Proto.Trusted 19 (startingStore fx) [reqPath 1 noisyPath] (msgNext "checking noisy\n" <> msgNext "building noisy...\n" <> msgLast <> le64 1) Conn.ClientClosed (const Pass), scriptTest "a client's verbosity decides which of the store's lines reach it" $ \fx -> assertSession Proto.Trusted 38 (startingStore fx) [setOptionsAt 5 [], reqPath 1 noisyPath, setOptionsAt 0 [], reqPath 1 noisyPath] ( msgLast <> msgNext "checking noisy\n" <> msgNext "too quiet to hear\n" <> buildBytes <> (msgLast <> le64 1) <> msgLast <> buildBytes <> (msgLast <> le64 1) ) Conn.ClientClosed (const Pass), scriptTest "an operation that fails in its work is sent upstream's error record, and the connection goes on" $ \fx -> assertSession Proto.Trusted 38 (startingStore fx) [reqPath 10 missingPath, reqPath 1 fooPath] (msgError "path '/nix/store/00000000000000000000000000000005-missing' is not valid" <> msgLast <> le64 1) Conn.ClientClosed (const Pass), scriptTest "before 1.26 a failure is sent as its message and exit status" $ \fx -> assertSession Proto.Trusted 25 (startingStore fx) [reqPath 10 missingPath, reqPath 1 fooPath] (msgErrorBefore126 "path '/nix/store/00000000000000000000000000000005-missing' is not valid" <> msgLast <> le64 1) Conn.ClientClosed (const Pass), scriptTest "a failure before an operation's work is sent twice and closes the connection, as upstream's daemon closes it" $ \fx -> let closed message ops = assertSession Proto.Trusted 38 (startingStore fx) (ops ++ [reqPath 1 fooPath]) (msgError message <> msgError message) (Conn.ClosedOnError (Ops.daemonError (TE.decodeUtf8 message))) (askedOnly []) in closed "invalid operation 99" [le64 99] `andThen` closed "path \"/tmp/x\" is not in the Nix store" [le64 1 <> wstr "/tmp/x"] `andThen` closed "Invalid build mode" [le64 9 <> wstrs [drvOut] <> le64 3], scriptTest "an operation's code too large to read is sent once and closes the connection, and input ending inside a request is sent twice" $ \fx -> assertSession Proto.Trusted 38 (startingStore fx) [le64 4294967296] (msgError "serialised integer 4294967296 is too large for type 'j'") (Conn.ClosedOnError (Ops.daemonError "serialised integer 4294967296 is too large for type 'j'")) (askedOnly []) `andThen` assertSession Proto.Trusted 38 (startingStore fx) [le64 1 <> le64 64 <> "/nix/store"] (msgError "unexpected end-of-file" <> msgError "unexpected end-of-file") (Conn.ClosedOnError (Ops.daemonError "unexpected end-of-file")) (askedOnly []), runTest "a client whose input ends between operations closes the connection, with nothing more sent" $ let (ended, written, _) = runScript serverConfig Proto.Trusted emptyFake [clientHello 38, BS.take 3 (le64 1)] in assertEqual "end" Conn.ClientClosed ended `andThen` assertEqual "written" (serverHello 38 Proto.Trusted) written, scriptTest "an untrusted client is refused what upstream's daemon refuses it, and a trusted one is not" $ \fx -> let store = startingStore fx narUpload repair dontCheck = le64 39 <> uploadInfo newPath ((newInfo fx) {Proto.upiUltimate = True}) <> le64 repair <> le64 dontCheck <> wframe (narOf newPath) <> frameEnd refusedBefore message request = assertSession Proto.NotTrusted 38 store [request, reqPath 1 fooPath] (msgError message <> msgError message) (Conn.ClosedOnError (Ops.daemonError (TE.decodeUtf8 message))) (askedOnly []) refusedInWork message request = assertSession Proto.NotTrusted 38 store [request, reqPath 1 fooPath] (msgError message <> msgLast <> le64 1) Conn.ClientClosed (askedOnly ["IsValidPath foo"]) served trust request reply calls = assertSession trust 38 store [request] reply Conn.ClientClosed (askedOnly calls) in refusedBefore "you are not privileged to repair paths" (le64 7 <> wstr "dump" <> wstr "text:sha256" <> wpaths [] <> le64 1) `andThen` refusedBefore "you are not privileged to repair store paths" (narUpload 1 0) `andThen` refusedBefore "you are not privileged to repair store paths" (le64 44 <> le64 1 <> le64 0) `andThen` refusedBefore "repairing is not allowed because you are not in 'trusted-users'" (le64 9 <> wstrs [drvOut] <> le64 1) `andThen` refusedBefore "repairing is not allowed because you are not in 'trusted-users'" (le64 46 <> wstrs [drvOut] <> le64 1) `andThen` refusedInWork "you are not privileged to repair paths" (le64 35 <> le64 0 <> le64 1) `andThen` served Proto.Trusted (le64 9 <> wstrs [drvOut] <> le64 1) (buildBytes <> msgLast <> le64 1) ["BuildPaths BuildRepair"] `andThen` served Proto.Trusted (le64 35 <> le64 0 <> le64 1) (msgLast <> le64 0) ["VerifyStore SkipContents Repair"] `andThen` served Proto.Trusted (narUpload 1 1) msgLast ["AddToStoreNar new Repair NoCheckSigs ultimate True"] `andThen` served Proto.NotTrusted (narUpload 0 1) msgLast ["AddToStoreNar new NoRepair CheckSigs ultimate False"] `andThen` served Proto.NotTrusted (le64 44 <> le64 0 <> le64 1 <> wframe (le64 1 <> uploadInfo newPath ((newInfo fx) {Proto.upiUltimate = True}) <> narOf newPath) <> frameEnd) msgLast ["AddToStoreNar new NoRepair CheckSigs ultimate False"] `andThen` served Proto.NotTrusted (le64 14) (msgLast <> le64 1 <> wstr "{censored}" <> wstr (pathOnWire fooPath)) ["FindRoots CensorRoots"], scriptTest "no client may have a collection ignore liveness, and the refusal leaves the connection open" $ \fx -> let ignoring = le64 20 <> le64 2 <> le64 1 <> le64 1 <> le64 0 <> le64 0 <> le64 0 <> le64 0 refused trust = assertSession trust 38 (startingStore fx) [ignoring, reqPath 1 fooPath] (msgError "you are not allowed to ignore liveness" <> msgLast <> le64 1) Conn.ClientClosed (askedOnly ["IsValidPath foo"]) in refused Proto.Trusted `andThen` refused Proto.NotTrusted, scriptTest "a collection's paths are a set with a referrers flag under the delete-specific feature and a bare set without it, where a collection of the dead limited to some is refused" $ \fx -> let tail3 = le64 0 <> le64 0 <> le64 0 bare action paths = le64 20 <> le64 action <> wpaths paths <> le64 0 <> le64 0 <> tail3 reply = msgLast <> wstrs ["/nix/store/0000000000000000000000000000000a-dead"] <> le64 4096 <> le64 0 asks request = "CollectGarbage " <> T.pack (show request) message = "Garbage collecting specific paths requested but it is not supported by the negotiated protocol" in assertSession Proto.Trusted 38 (startingStore fx) [le64 20 <> le64 2 <> le64 0 <> wpaths [fooPath] <> le64 1 <> le64 0 <> le64 7 <> tail3] reply Conn.ClientClosed (askedOnly [asks (Ops.GCRequest Proto.DeleteDead (Proto.SpecificPaths (Set.singleton fooPath) True) 7)]) `andThen` assertSession Proto.Trusted 37 (startingStore fx) [bare 3 [fooPath], bare 0 []] (reply <> reply) Conn.ClientClosed (askedOnly [asks (Ops.GCRequest Proto.DeleteSpecific (Proto.SpecificPaths (Set.singleton fooPath) False) 0), asks (Ops.GCRequest Proto.ReturnLive Proto.WholeStore 0)]) `andThen` assertSession Proto.Trusted 37 (startingStore fx) [bare 2 [fooPath]] (msgError message <> msgError message) (Conn.ClosedOnError (Ops.daemonError (TE.decodeUtf8 message))) (askedOnly []), scriptTest "a NAR upload is fed to the store up to its declared size, and the rest of its frames are read past" $ \fx -> let nar = narOf newPath upload = le64 39 <> uploadInfo newPath (newInfo fx) <> le64 0 <> le64 0 <> foldMap wframe [BS.take 3 nar, BS.drop 3 nar <> "trailing", "more"] <> frameEnd in assertSession Proto.Trusted 38 (startingStore fx) [upload, reqPath 1 newPath] (msgLast <> msgLast <> le64 1) Conn.ClientClosed (assertEqual "imported" [(newPath, nar)] . fakeImports), scriptTest "a store that fails an upload, or needs none of it, has the rest read past before the reply, and the connection goes on" $ \fx -> let upload path info nar = le64 39 <> uploadInfo path info <> le64 0 <> le64 0 <> wframe nar <> wframe "more" <> frameEnd unsigned = "cannot add path '/nix/store/00000000000000000000000000000008-refused' because it lacks a signature by a trusted key" mismatch = "hash mismatch importing path '/nix/store/00000000000000000000000000000007-new'" session request reply = assertSession Proto.Trusted 38 (startingStore fx) [request, reqPath 1 fooPath] (reply <> msgLast <> le64 1) Conn.ClientClosed in session (upload refusedPath (refusedInfo fx) (narOf refusedPath)) (msgError unsigned) (assertEqual "imported" [] . fakeImports) `andThen` session (upload newPath (newInfo fx) "not the nar of new") (msgError mismatch) (assertEqual "imported" [] . fakeImports) `andThen` session (upload fooPath (fooInfo fx) (narOf fooPath)) msgLast (assertEqual "imported" [] . fakeImports), scriptTest "a frame too long to read fails its upload, and reading past the upload goes on from the bytes after the length, as upstream's does" $ \fx -> assertSession Proto.Trusted 38 (startingStore fx) [le64 39 <> uploadInfo newPath (newInfo fx) <> le64 0 <> le64 0 <> le64 4294967296 <> wframe "x" <> frameEnd, reqPath 1 fooPath] (msgError "serialised integer 4294967296 is too large for type 'j'" <> msgLast <> le64 1) Conn.ClientClosed (askedOnly ["AddToStoreNar new NoRepair CheckSigs ultimate False", "broken off", "IsValidPath foo"]), scriptTest "input that ends inside an upload fails it once, and the connection then closes as the client's input has ended" $ \fx -> assertSession Proto.Trusted 38 (startingStore fx) [le64 39 <> uploadInfo newPath (newInfo fx) <> le64 0 <> le64 0 <> wframe "abc"] (msgError "unexpected end-of-file") Conn.ClientClosed (askedOnly ["AddToStoreNar new NoRepair CheckSigs ultimate False", "broken off"]), scriptTest "AddMultipleToStore imports each path in turn from one framed stream, reading past the NAR of one already valid, and none is ultimate" $ \fx -> let payload = le64 2 <> uploadInfo fooPath ((fooInfo fx) {Proto.upiUltimate = True}) <> narOf fooPath <> uploadInfo newPath ((newInfo fx) {Proto.upiUltimate = True}) <> narOf newPath request = le64 44 <> le64 0 <> le64 0 <> foldMap wframe [BS.take 5 payload, BS.take 100 (BS.drop 5 payload), BS.drop 105 payload] <> frameEnd in assertSession Proto.Trusted 38 (startingStore fx) [request, reqPath 1 newPath] (msgLast <> msgLast <> le64 1) Conn.ClientClosed ( \after -> askedOnly ["AddToStoreNar foo NoRepair CheckSigs ultimate False", "AddToStoreNar new NoRepair CheckSigs ultimate False", "IsValidPath new"] after `andThen` assertEqual "imported" [(newPath, narOf newPath)] (fakeImports after) ), scriptTest "AddMultipleToStore stops at the first path the store refuses, and an upload that ends before its count does fails it" $ \fx -> let failing = wframe (le64 2 <> uploadInfo refusedPath (refusedInfo fx) <> narOf refusedPath <> uploadInfo newPath (newInfo fx) <> narOf newPath) short = wframe (le64 2 <> uploadInfo newPath (newInfo fx) <> narOf newPath) session frames reply calls = assertSession Proto.Trusted 38 (startingStore fx) [le64 44 <> le64 0 <> le64 0 <> frames <> frameEnd, reqPath 1 fooPath] (reply <> msgLast <> le64 1) Conn.ClientClosed (askedOnly (calls ++ ["IsValidPath foo"])) in session failing (msgError "cannot add path '/nix/store/00000000000000000000000000000008-refused' because it lacks a signature by a trusted key") ["AddToStoreNar refused NoRepair CheckSigs ultimate False"] `andThen` session short (msgError "reached end of FramedSource") ["AddToStoreNar new NoRepair CheckSigs ultimate False"], scriptTest "AddToStore makes a path from its framed dump and replies with the path's info" $ \fx -> case Proto.narHashFromDigest (sha256Digest "hello") of Nothing -> Fail "no hash" Just narHash -> assertSession Proto.Trusted 38 (startingStore fx) [le64 7 <> wstr "dump" <> wstr "fixed:r:sha256" <> wpaths [fooPath] <> le64 0 <> wframe "hel" <> wframe "lo" <> frameEnd] (msgLast <> wstr (pathOnWire dumpPath) <> winfo (Proto.UnkeyedValidPathInfo Nothing narHash (Set.singleton fooPath) 1700000000 5 True Set.empty Nothing)) Conn.ClientClosed (askedOnly ["AddToStore dump FixedMethod NarIngestion sha256"]), scriptTest "an upload's method is read before its dump, so a method refused leaves the dump to be read as the next operation, as upstream leaves it" $ \fx -> assertSession Proto.Trusted 38 (startingStore fx) [le64 7 <> wstr "dump" <> wstr "bogus:sha256" <> wpaths [] <> le64 0 <> wframe "hello" <> frameEnd] ( msgError "content address prefix 'bogus' is unrecognized. Recogonized prefixes are 'text' or 'fixed'" <> msgError "invalid operation 5" <> msgError "invalid operation 5" ) (Conn.ClosedOnError (Ops.daemonError "invalid operation 5")) (askedOnly []), scriptTest "an upload in a form older than a framed one is refused as its request begins" $ \fx -> let refused minor message ops = assertSession Proto.Trusted minor (startingStore fx) ops (msgErrorBefore126 message <> msgErrorBefore126 message) (Conn.ClosedOnError (Ops.daemonError (TE.decodeUtf8 message))) (askedOnly []) in refused 24 "AddToStore before protocol 1.25 is not supported by this daemon" [le64 7, wstr "dump"] `andThen` refused 22 "AddToStoreNar before protocol 1.23 is not supported by this daemon" [le64 39] `andThen` assertSession Proto.Trusted 26 (startingStore fx) [le64 31 <> wpaths [fooPath]] (msgLast <> wpaths [fooPath]) Conn.ClientClosed (askedOnly ["QueryValidPaths NoSubstitute"]), scriptTest "an untrusted client's settings apply as far as upstream's daemon lets them, with its warnings in the settings' order" $ \fx -> let overrides = [ ("substituters", "https://trusted.example.org https://evil.example.org " <> TE.encodeUtf8 daemonSubstituter), ("plugin-files", "/x.so"), ("keep-going", "true"), ("build-poll-interval", "3"), ("ssh-auth-sock", "/tmp/agent"), ("experimental-features", "nix-command") ] warnings = msgNext "warning: ignoring the client-specified setting 'keep-going', because it is a restricted setting and you are not a trusted user\n" <> msgNext "warning: Ignoring the client-specified plugin-files.\nThe client specifying plugins to the daemon never made sense, and was removed in Nix >=2.14.\n" <> msgNext "warning: ignoring untrusted substituter 'https://evil.example.org', you are not a trusted user.\nRun `man nix.conf` for more information on the `substituters` configuration option.\n" in assertSession Proto.NotTrusted 38 (startingStore fx) [setOptionsAt 3 overrides, reqPath 1 fooPath] (warnings <> msgLast <> msgLast <> le64 1) Conn.ClientClosed ( \after -> case fakeSettings after of Nothing -> Fail "the store saw no settings" Just settings -> assertEqual "substituters" [trustedSubstituter, daemonSubstituter] (ncSubstituters (Ops.connConfig settings)) `andThen` assertEqual "keep-failed" True (ncKeepFailed (Ops.connConfig settings)) `andThen` assertEqual "fallback" True (ncFallback (Ops.connConfig settings)) `andThen` assertEqual "cores" (Just 4) (ncCores (Ops.connConfig settings)) `andThen` assertEqual "verbosity" (Proto.Verbosity 3) (Ops.connVerbosity settings) ) `andThen` assertSession Proto.NotTrusted 38 (startingStore fx) [setOptionsAt 0 [("keep-going", "true")]] msgLast Conn.ClientClosed (const Pass), scriptTest "a trusted client's settings apply as a nix.conf's lines would, a value refused warned of as upstream warns of it" $ \fx -> assertSession Proto.Trusted 38 (startingStore fx) [setOptionsAt 3 [("fallback", "maybe"), ("substituters", "https://any.example.org"), ("max-jobs", "8")], reqPath 1 fooPath] (msgNext "warning: Boolean setting 'fallback' has invalid value 'maybe'" <> msgLast <> msgLast <> le64 1) Conn.ClientClosed ( \after -> case fakeSettings after of Nothing -> Fail "the store saw no settings" Just settings -> assertEqual "substituters" ["https://any.example.org"] (ncSubstituters (Ops.connConfig settings)) `andThen` assertEqual "fallback" True (ncFallback (Ops.connConfig settings)) ), scriptTest "a NAR that cannot be written closes the connection, its error following the end of the work" $ \fx -> assertSession Proto.Trusted 38 (startingStore fx) [reqPath 38 missingPath, reqPath 1 fooPath] (msgLast <> "partial" <> msgError "path '/nix/store/00000000000000000000000000000005-missing' is not valid" <> msgError "path '/nix/store/00000000000000000000000000000005-missing' is not valid") (Conn.ClosedOnError (notValid missingPath)) (askedOnly ["NarFromPath missing"]), runTest "a handshake that opens with another word is refused with nothing sent" $ let (ended, written, _) = runScript serverConfig Proto.Trusted emptyFake [le64 serverMagicWord] in assertEqual "end" (Conn.HandshakeFailed "protocol mismatch") ended `andThen` assertEqual "written" "" written, runTest "a client older than 1.18 is refused once the versions are exchanged, and sent nothing more" $ let (ended, written, _) = runScript serverConfig Proto.Trusted emptyFake [clientHello 17, reqPath 1 fooPath] in assertEqual "end" (Conn.HandshakeFailed "the Nix client version is too old") ended `andThen` assertEqual "written" (le64 serverMagicWord <> le64 0x126) written, scriptTest "a client newer than the daemon is served at the daemon's version, and one below 1.38 exchanges no features" $ \fx -> assertSession Proto.Trusted 40 (startingStore fx) [reqPath 1 fooPath] (msgLast <> le64 1) Conn.ClientClosed (const Pass) `andThen` assertSession Proto.NotTrusted 37 (startingStore fx) [reqPath 1 fooPath] (msgLast <> le64 1) Conn.ClientClosed (const Pass), runTestM "however a client's bytes are split into reads, the daemon writes the same bytes, and each reply reads back as what the store answered" $ codecProperty $ QC.forAll genQuerySession $ \(known, queries) -> let input = clientHello 38 <> foldMap queryBytes queries fake = Fake known [] [] Nothing (_, whole, _) = runScript serverConfig Proto.Trusted fake [input] hello = serverHello 38 Proto.Trusted in QC.forAll (genSplit input) $ \pieces -> let (_, split, _) = runScript serverConfig Proto.Trusted fake pieces in QC.conjoin [ split QC.=== whole, BS.take (BS.length hello) whole QC.=== hello, decodeWhole (traverse replyReader queries) (BS.drop (BS.length hello) whole) QC.=== Right (map (answerFrom known) queries) ] ]-- | No paths at all.emptyFake :: FakeemptyFake = Fake Map.empty [] [] Nothing-- | A query the property sends, and the answers it reads back.data Query = AskValid !StorePath | AskInfo !StorePath | AskValidAmong !(Set.Set StorePath) | AskReferrers !StorePath | AskAll deriving (Show)data Answer = Valid !Bool | Info !(Maybe Proto.UnkeyedValidPathInfo) | Paths !(Set.Set StorePath) deriving (Eq, Show)-- | A store of up to four paths, some referring to others, and queries-- about them and about paths it does not hold.genQuerySession :: QC.Gen (Map.Map StorePath Proto.UnkeyedValidPathInfo, [Query])genQuerySession = do paths <- QC.resize 4 (QC.listOf genWireStorePath) infos <- traverse (\_ -> withReferences paths =<< genPathInfo) paths let known = Map.fromList (zip paths infos) anyPath = QC.oneof (genWireStorePath : [QC.elements paths | not (null paths)]) queries <- QC.resize 8 . QC.listOf $ QC.oneof [ AskValid <$> anyPath, AskInfo <$> anyPath, AskValidAmong . Set.fromList <$> QC.resize 3 (QC.listOf anyPath), AskReferrers <$> anyPath, pure AskAll ] pure (known, queries) where withReferences paths info = (\refs -> info {Proto.upiReferences = Set.fromList refs}) <$> QC.sublistOf paths-- | A query as a client sends it.queryBytes :: Query -> BS.ByteStringqueryBytes = \case AskValid path -> reqPath 1 path AskInfo path -> reqPath 26 path AskValidAmong paths -> le64 31 <> wpaths (Set.toList paths) <> le64 0 AskReferrers path -> reqPath 6 path AskAll -> le64 23-- | What the scripts' store answers a query, from its paths alone.answerFrom :: Map.Map StorePath Proto.UnkeyedValidPathInfo -> Query -> AnsweranswerFrom known = \case AskValid path -> Valid (Map.member path known) AskInfo path -> Info (Map.lookup path known) AskValidAmong paths -> Paths (Set.filter (`Map.member` known) paths) AskReferrers path -> Paths (Map.keysSet (Map.filter (Set.member path . Proto.upiReferences) known)) AskAll -> Paths (Map.keysSet known)-- | A query's reply as the protocol's own readers read it: the end of-- the work, then the answer.replyReader :: Query -> Wire.Decoder AnswerreplyReader query = Proto.getStderrMessage replyVersion >>= \case Proto.StderrLast -> case query of AskValid _ -> Valid <$> Wire.getBool AskInfo _ -> Wire.getBool >>= \valid -> Info <$> if valid then Just <$> Proto.getUnkeyedValidPathInfo defaultStoreDir replyVersion else pure Nothing AskValidAmong _ -> Paths <$> Proto.getStorePathSet defaultStoreDir AskReferrers _ -> Paths <$> Proto.getStorePathSet defaultStoreDir AskAll -> Paths <$> Proto.getStorePathSet defaultStoreDir other -> Wire.malformed ("expected the end of the work, got " <> T.pack (show other)) where replyVersion = Proto.Version Proto.latestVersionNumber (Set.fromList (map Proto.Feature serverFeatures))-- | Upstream's handshake fixture is what its daemon writes when it and its-- client both offer 1.10, and what this daemon writes offering 1.10, as it-- then refuses a client below the oldest it serves.alsoWrittenByTheDaemon :: (FilePath, BS.ByteString -> TestResult) -> (FilePath, BS.ByteString -> TestResult)alsoWrittenByTheDaemon (file, check) = (file, \bytes -> check bytes `andThen` daemonWrites bytes) where daemonWrites bytes = let (ended, written, _) = runScript (serverConfigAt (Proto.Version (Proto.VersionNumber 1 10) Set.empty)) Proto.Trusted emptyFake [le64 clientMagicWord <> le64 0x10a] in assertEqual "the daemon's handshake" bytes written `andThen` assertEqual "end" (Conn.HandshakeFailed "the Nix client version is too old") ended-- ----------------------------------------------------------------------------- Tests: who may connect-- ----------------------------------------------------------------------------- | A user database with two users, three groups, and a directory that-- counts @alice@ in @staff@ though the group lists no one.fakeUsers :: Auth.UserDatabase IdentityfakeUsers = Auth.UserDatabase { Auth.udUserName = \uid -> pure (Map.lookup uid (Map.fromList [(1000, "alice"), (1001, "bob")])), Auth.udGroupName = \gid -> pure (Map.lookup gid (Map.fromList [(100, "users"), (200, "wheel"), (300, "staff")])), Auth.udGroup = \name -> pure (Map.lookup name (Map.fromList [("users", Auth.GroupEntry 100 []), ("wheel", Auth.GroupEntry 200 ["bob"]), ("staff", Auth.GroupEntry 300 [])])), Auth.udMembership = \uid gid -> pure (if (uid, gid) == (1000, 300) then Just True else Nothing) }-- | Upstream's refusal of a user.notAllowed :: Text -> Auth.AdmissionnotAllowed user = Auth.Refused ("user '" <> user <> "' is not allowed to connect to the Nix daemon")-- | Admission decided as upstream's daemon decides it, over a user-- database of the test's own.testDaemonAuth :: IO [Bool]testDaemonAuth = do putStrLn "daemon/auth" sequence [ runTest "a peer is trusted and admitted as trusted-users and allowed-users name it, by user, group or everyone" $ let admit trusted allowed buildGroup peer = runIdentity (Auth.admitPeer fakeUsers (Auth.AuthSettings trusted allowed buildGroup) peer) alice = Auth.Peer (Just 7) (Just 1000) (Just 100) bob = Auth.Peer Nothing (Just 1001) (Just 100) in assertEqual "allowed" (Auth.Admitted Proto.NotTrusted (Just "alice")) (admit ["root"] ["*"] "" alice) `andThen` assertEqual "by name" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["alice"] [] "" alice) `andThen` assertEqual "everyone" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["*"] [] "" alice) `andThen` assertEqual "a group's member list" (Auth.Admitted Proto.Trusted (Just "bob")) (admit ["@wheel"] [] "" bob) `andThen` assertEqual "the peer's own group" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["@users"] [] "" alice) `andThen` assertEqual "the directory's membership" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["@staff"] [] "" alice) `andThen` assertEqual "no such group, not named" (notAllowed "alice") (admit ["@nosuch"] ["bob"] "" alice) `andThen` assertEqual "a trusted user always may" (Auth.Admitted Proto.Trusted (Just "bob")) (admit ["bob"] [] "" bob) `andThen` assertEqual "a user with no entry is its number" (Auth.Admitted Proto.NotTrusted (Just "4242")) (admit [] ["4242"] "" (Auth.Peer Nothing (Just 4242) (Just 4243))) `andThen` assertEqual "a peer with no user" (Auth.Admitted Proto.NotTrusted Nothing) (admit [] ["*"] "" Auth.unknownPeer) `andThen` assertEqual "a peer with no user, not allowed" (notAllowed "<unknown>") (admit [] ["alice"] "" Auth.unknownPeer) `andThen` assertEqual "the build users' group, trusted or not" (notAllowed "alice") (admit ["*"] ["*"] "users" alice), runTest "a Windows account is trusted and admitted by SID: its user's, or a group's its token holds, named by SID or by a name the system resolves, or everyone" $ case traverse sidFromText ["S-1-5-21-1-2-3-1000", "S-1-5-21-1-2-3-1001", "S-1-5-21-1-2-3-3000", "S-1-5-32-545", "S-1-5-21-1-2-3-2000"] of Just [alice, bob, unnamed, users, builders] -> let userNames = [("alice", alice), ("HOST\\alice", alice), ("bob", bob)] groupNames = [("Users", users), ("nixbld", builders)] accounts = windowsAccounts userNames groupNames [(alice, [users]), (bob, [builders])] admit trusted allowed buildGroup peer = runIdentity (Auth.admitAccount accounts (Auth.AuthSettings trusted allowed buildGroup) peer) asAlice = Auth.AccountPeer (Just 7) alice [users] in assertEqual "allowed" (Auth.Admitted Proto.NotTrusted (Just "alice")) (admit ["root"] ["*"] "" asAlice) `andThen` assertEqual "by name" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["alice"] [] "" asAlice) `andThen` assertEqual "by domain and name" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["HOST\\alice"] [] "" asAlice) `andThen` assertEqual "by SID" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["S-1-5-21-1-2-3-1000"] [] "" asAlice) `andThen` assertEqual "everyone" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["*"] [] "" asAlice) `andThen` assertEqual "a group the token holds, by SID" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["@S-1-5-32-545"] [] "" asAlice) `andThen` assertEqual "a group the token holds, by name" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["@Users"] [] "" asAlice) `andThen` assertEqual "a group the token does not hold" (Auth.Admitted Proto.NotTrusted (Just "alice")) (admit ["@nixbld"] ["*"] "" asAlice) `andThen` assertEqual "a group's SID names no user" (notAllowed "alice") (admit ["S-1-5-32-545"] [] "" asAlice) `andThen` assertEqual "a group's name is no user's" (Auth.Admitted Proto.NotTrusted (Just "alice")) (admit ["Users"] ["*"] "" asAlice) `andThen` assertEqual "another user" (notAllowed "alice") (admit ["bob"] ["@nosuch"] "" asAlice) `andThen` assertEqual "an account with no name is its SID" (Auth.Admitted Proto.NotTrusted (Just "S-1-5-21-1-2-3-3000")) (admit [] ["*"] "" (Auth.AccountPeer Nothing unnamed [])) `andThen` assertEqual "the build users' group, by the account's groups, whatever the token shows" (notAllowed "bob") (admit ["*"] ["*"] "nixbld" (Auth.AccountPeer Nothing bob [])) `andThen` assertEqual "the build users' group, trusted or not" (notAllowed "bob") (admit ["*"] ["*"] "nixbld" (Auth.AccountPeer Nothing bob [builders])) `andThen` assertEqual "a group the token shows is not the account's" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["*"] [] "nixbld" (Auth.AccountPeer (Just 7) alice [builders])) `andThen` assertEqual "the build users' group, not held" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["*"] [] "nixbld" asAlice) `andThen` assertEqual "a build users' group no account has holds no one" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["*"] [] "nosuchgroup" asAlice) _ -> Fail "the tests' SIDs do not read as SIDs", runTest "a client the daemon cannot place in the build users' group is refused, and an entry it cannot look up only withholds trust" $ case traverse sidFromText ["S-1-5-21-1-2-3-1000", "S-1-5-32-545", "S-1-5-21-1-2-3-2000"] of Just [alice, users, builders] -> let healthy = windowsAccounts [("alice", alice)] [("Users", users), ("nixbld", builders)] [(alice, [users])] groupsFail = healthy {Auth.adAccountGroups = const (pure (Left "the groups cannot be read"))} groupLookupFails = healthy {Auth.adAccountSid = \kind name -> if kind == Auth.GroupAccount && name == "nixbld" then pure (Left "the lookup failed") else Auth.adAccountSid healthy kind name} entryLookupFails = healthy {Auth.adAccountSid = \kind name -> if kind == Auth.UserAccount && name == "carol" then pure (Left "the lookup failed") else Auth.adAccountSid healthy kind name} admit db trusted buildGroup = runIdentity (Auth.admitAccount db (Auth.AuthSettings trusted ["*"] buildGroup) (Auth.AccountPeer (Just 7) alice [users])) in assertEqual "healthy" (Auth.Admitted Proto.NotTrusted (Just "alice")) (admit healthy [] "nixbld") `andThen` assertEqual "the account's groups cannot be read" (Auth.Refused "user 'alice' is not allowed to connect to the Nix daemon: cannot tell the groups of the account: the groups cannot be read") (admit groupsFail [] "nixbld") `andThen` assertEqual "the group cannot be looked up" (Auth.Refused "user 'alice' is not allowed to connect to the Nix daemon: cannot look up build-users-group 'nixbld': the lookup failed") (admit groupLookupFails [] "nixbld") `andThen` assertEqual "no build users' group, no question" (Auth.Admitted Proto.NotTrusted (Just "alice")) (admit groupsFail [] "") `andThen` assertEqual "a trusted-users entry that cannot be looked up trusts no one" (Auth.Admitted Proto.NotTrusted (Just "alice")) (admit entryLookupFails ["carol"] "") _ -> Fail "the tests' SIDs do not read as SIDs", runTest "a service's SID is derived from its name as Windows derives it" $ assertEqual "TrustedInstaller" (sidFromText "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464") (Just (serviceSid "TrustedInstaller")) `andThen` assertEqual "ALG" (sidFromText "S-1-5-80-2387347252-3645287876-2469496166-3824418187-3586569773") (Just (serviceSid "ALG")) `andThen` assertEqual "nova-nix" (sidFromText "S-1-5-80-3559003300-525236055-3252912499-3879747958-1619201019") (Just novaNixServiceSid) `andThen` assertEqual "the name's case does not matter" (serviceSid "Nova-Nix") (serviceSid "NOVA-NIX"), runTest "a client trusts a pipe its own account, SYSTEM, Administrators or the nova-nix service owns, and no other account" $ case traverse sidFromText [clientSid, otherUserSid, "S-1-5-18", "S-1-5-19", "S-1-5-20", "S-1-5-32-544", "S-1-5-32-545", "S-1-1-0", "S-1-5-11", "S-1-5-80-0", "S-1-5-80-1-2", trustedInstallerSid] of Just [client, other, system, localService, networkService, administrators, users, everyone, authenticated, allServices, shortService, trustedInstaller] -> let trusts = Auth.trustsPipeOwner client in assertEqual "its own account" True (trusts client) `andThen` assertEqual "SYSTEM" True (trusts system) `andThen` assertEqual "Administrators, the owner of what an elevated administrator makes" True (trusts administrators) `andThen` assertEqual "the nova-nix service" True (trusts novaNixServiceSid) `andThen` assertEqual "LOCAL SERVICE, which other services share" False (trusts localService) `andThen` assertEqual "NETWORK SERVICE, which other services share" False (trusts networkService) `andThen` assertEqual "another service's SID" False (trusts trustedInstaller) `andThen` assertEqual "another user, an administrator that is not elevated among them, whose pipes it owns as itself" False (trusts other) `andThen` assertEqual "the Users group" False (trusts users) `andThen` assertEqual "Everyone" False (trusts everyone) `andThen` assertEqual "Authenticated Users" False (trusts authenticated) `andThen` assertEqual "ALL SERVICES, a group every service's token holds" False (trusts allServices) `andThen` assertEqual "a SID that only starts as a service's does" False (trusts shortService) `andThen` assertEqual "any other client trusts its own account too" True (Auth.trustsPipeOwner other other) _ -> Fail "the tests' SIDs do not read as SIDs", runTestM "a client trusts a pipe's owner exactly when it is its own account, among the accounts of users" $ codecProperty $ QC.forAll genUserSidText $ \(clientText, ownerText) -> case (sidFromText clientText, sidFromText ownerText) of (Just client, Just owner) -> Auth.trustsPipeOwner client owner QC.=== (client == owner) QC..&&. Auth.trustsPipeOwner client client QC.=== True _ -> QC.counterexample "a generated SID does not read as one" False, runTestM "a service's SID reads as a SID of five subauthorities after S-1-5-80, whatever its name" $ codecProperty $ QC.forAll (QC.listOf1 (QC.elements (['A' .. 'Z'] <> ['a' .. 'z'] <> ['0' .. '9'] <> "-_"))) $ \name -> case T.splitOn "-" (sidText (serviceSid (T.pack name))) of "S" : "1" : "5" : "80" : rest -> QC.counterexample (show rest) (length rest == 5) other -> QC.counterexample (show other) False, runTest "an admitted connection is logged as upstream's daemon logs it" $ assertEqual "trusted" "accepted connection from pid 7, user alice (trusted)" (Auth.acceptedMessage (Just 7) (Auth.Admitted Proto.Trusted (Just "alice"))) `andThen` assertEqual "not trusted, nothing known" "accepted connection from pid <unknown>, user <unknown>" (Auth.acceptedMessage Nothing (Auth.Admitted Proto.NotTrusted Nothing)) ]-- | The SIDs of the client in the pipe-owner tests and of another user,-- and a service's SID, as Windows writes the one of TrustedInstaller.clientSid, otherUserSid, trustedInstallerSid :: TextclientSid = "S-1-5-21-1-2-3-1000"otherUserSid = "S-1-5-21-1-2-3-1001"trustedInstallerSid = "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464"-- | Windows' accounts as a test supplies them: the users and the groups-- by name, and the groups each account belongs to. A name with no account-- is found to have none, and an account with no entry has no groups.windowsAccounts :: [(BS.ByteString, Sid)] -> [(BS.ByteString, Sid)] -> [(Sid, [Sid])] -> Auth.AccountDatabase IdentitywindowsAccounts users groups memberships = Auth.AccountDatabase { Auth.adAccountSid = \kind name -> pure (Right (lookup name (case kind of Auth.UserAccount -> users; Auth.GroupAccount -> groups))), Auth.adAccountName = \sid -> pure (lookup sid [(named, spelled) | (spelled, named) <- users <> groups]), Auth.adAccountGroups = \sid -> pure (Right (fromMaybe [] (lookup sid memberships))) }-- | Two SIDs of the accounts of users, a machine's or a domain's, which-- Windows numbers @S-1-5-21@, three subauthorities that name the machine-- or domain, and the account's RID. Drawn from a few values, so a pair is-- often equal as well as different.genUserSidText :: QC.Gen (Text, Text)genUserSidText = (,) <$> userSid <*> userSid where userSid = (\machine rid -> "S-1-5-21-" <> T.pack (show machine) <> "-2-3-" <> T.pack (show rid)) <$> few <*> few few = QC.elements [1, 2, 1000, 1001 :: Word32]-- ----------------------------------------------------------------------------- Tests: the daemon on a socket-- ----------------------------------------------------------------------------- | How long a socket test may take before it fails: well past what any-- of them takes, so only a daemon that stopped answering reaches it.socketTestMicros :: IntsocketTestMicros = 60 * 1000 * 1000-- | A store of its own in a directory of its own, served as a daemon-- serves one, holding 'fooPath', valid, and a logger keeping what is-- logged, which the test is given in order; the directory is removed-- after.withServedStore :: (FilePath -> Store -> ServedStore -> Logger -> IO [Text] -> IO TestResult) -> IO TestResultwithServedStore body = do tmp <- Dir.getTemporaryDirectory let root = tmp </> "nn-daemon" forceRemoveIfExists root Dir.createDirectoryIfMissing True (root </> "store") logged <- newIORef [] let logger = plainLogger (\_ message -> atomicModifyIORef' logged (\messages -> (message : messages, ()))) (const (pure ())) result <- bracket (openStore logger (StoreDir (root </> "store"))) closeStore $ \store -> do registerPath (stDB store) (PathRegistration fooPath (Hash.formatNixHash (Hash.hashBytes (narOf fooPath))) (BS.length (narOf fooPath)) Nothing [] NotUltimate Set.empty Nothing RegisteredNow) served <- newServedStore testDefaults store body root store served logger (reverse <$> readIORef logged) forceRemoveIfExists root pure result-- | The scripts' daemon configuration, for a store a test serves.servedConfig :: NixConfig -> Conn.ServerConfigservedConfig config = serverConfig {Conn.scConfig = config}-- | A daemon serving a store of its own, on a socket beside it or on-- Windows a pipe of its own ("DaemonLink"), on a thread stopped once the-- test is done, with what it logged. The test is given the directory the-- store keeps its files in and the address the daemon listens at. A-- daemon that does not stop is a failure, as a stop that waits forever-- would otherwise hang the suite.withSocketDaemon :: Listen.TrustOverride -> (NixConfig -> NixConfig) -> (StoreDir -> BS.ByteString -> IO [Text] -> IO TestResult) -> IO TestResultwithSocketDaemon trust configure body = withServedStore $ \root store served logger logged -> do let config = configure defaultNixConfig auth <- Listen.authSettingsFor config daemonAddress root >>= \case Nothing -> pure (Fail "the socket path has no spelling as bytes") Just address -> Listen.openListener address >>= \case Left refusal -> pure (Fail refusal) Right listener -> do stopped <- newEmptyMVar let options = Listen.DaemonOptions trust auth (serveLocal served (servedConfig config)) thread <- forkFinally (Listen.serveListener logger options listener) (\_ -> putMVar stopped ()) ran <- timeout socketTestMicros (body (stDir store) address logged) `onException` stop thread stopped listener stoppedInTime <- stop thread stopped listener pure $ case (ran, stoppedInTime) of (Nothing, _) -> Fail "the daemon stopped answering" (_, Nothing) -> Fail "the daemon did not stop" (Just result, Just ()) -> result where stop thread stopped listener = timeout socketTestMicros (killThread thread >> takeMVar stopped) <* Listen.closeListener listener-- | A transport over a client's input, given in chunks, and what the-- daemon wrote to it.memoryTransport :: [BS.ByteString] -> IO (Conn.Transport IO, IO BS.ByteString)memoryTransport input = do pending <- newIORef (filter (not . BS.null) input) written <- newIORef [] let receive = atomicModifyIORef' pending (\case [] -> ([], Nothing); chunk : rest -> (rest, Just chunk)) send bytes = atomicModifyIORef' written (\chunks -> (builtBytes bytes : chunks, ())) pure (Conn.Transport receive send, BS.concat . reverse <$> readIORef written)-- | Send bytes, and read back as many as are expected, or what the-- daemon wrote before it closed the connection.exchange :: DaemonLink -> BS.ByteString -> Int -> IO BS.ByteStringexchange link request count = linkSend link request >> receiveCount link countreceiveCount :: DaemonLink -> Int -> IO BS.ByteStringreceiveCount link count = go [] 0 where go chunks got | got >= count = pure (BS.concat (reverse chunks)) | otherwise = linkReceive link (count - got) >>= \chunk -> if BS.null chunk then pure (BS.concat (reverse chunks)) else go (chunk : chunks) (got + BS.length chunk)-- | Everything the daemon writes until it closes the connection.receiveToEnd :: DaemonLink -> IO BS.ByteStringreceiveToEnd link = go [] where go chunks = linkReceive link receiveSize >>= \chunk -> if BS.null chunk then pure (BS.concat (reverse chunks)) else go (chunk : chunks) receiveSize = 4096-- | A client's opening, and what the daemon answers it with.helloOver :: DaemonLink -> Proto.Trust -> IO TestResulthelloOver link trust = assertEqual "handshake" (serverHello 38 trust) <$> exchange link (clientHello 38) (BS.length (serverHello 38 trust))-- | The daemon's socket tests, which on Windows run over its pipe: a-- client served over it, two at once, an untrusted one refused what it-- may not ask, and one refused outright.testDaemonSocketIO :: IO [Bool]testDaemonSocketIO = do putStrLn "daemon/socket" sequence [ runTestM "a client is served over a socket every user may write, or a pipe Users may read and write, its paths' info read from the store" $ withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = ["*"]}) $ \_ address logged -> bracket (connectDaemon address) linkClose $ \link -> do hello <- helloOver link Proto.Trusted valid <- exchange link (reqPath 1 fooPath <> reqPath 1 missingPath) (2 * BS.length (msgLast <> le64 1)) info <- exchange link (reqPath 26 fooPath) infoReplySize messages <- logged open <- listenerOpenToUsers address pure $ open `andThen` hello `andThen` assertEqual "valid" (msgLast <> le64 1 <> msgLast <> le64 0) valid `andThen` assertEqual "info" (Right (Just (fromIntegral (BS.length (narOf fooPath)), False, Proto.narHashFromDigest (sha256Digest (narOf fooPath))))) (fmap (\i -> (Proto.upiNarSize i, Proto.upiUltimate i, Just (Proto.upiNarHash i))) <$> decodeWhole pathInfoReply info) `andThen` assertEqual "logged" [True] (map (\message -> "accepted connection from pid " `T.isPrefixOf` message && " (trusted)" `T.isSuffixOf` message) messages), runTestM "two clients are served at once, one shown the temporary root the other holds" $ withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = ["*"]}) $ \_ address _ -> bracket (connectDaemon address) linkClose $ \first -> do firstHello <- helloOver first Proto.Trusted rooted <- exchange first (reqPath 11 fooPath) (BS.length (msgLast <> le64 1)) bracket (connectDaemon address) linkClose $ \second -> do secondHello <- helloOver second Proto.Trusted shown <- exchange second (le64 14) (BS.length (rootsHeldBy 0)) firstValid <- exchange first (reqPath 1 fooPath) (BS.length (msgLast <> le64 1)) pure $ firstHello `andThen` assertEqual "rooted" (msgLast <> le64 1) rooted `andThen` secondHello `andThen` assertEqual "the first's root, shown to the second" (rootsHeldBy 0) shown `andThen` assertEqual "the first, served after the second" (msgLast <> le64 1) firstValid, runTestM "a connection's temporary roots go with it, and a client the daemon does not trust is not told who holds one" $ withServedStore $ \_ _ served _ _ -> do let serveOne trust input = do (transport, written) <- memoryTransport input ended <- serveLocal served (servedConfig defaultNixConfig) trust transport (,) ended <$> written first <- serveOne Proto.Trusted [clientHello 38, reqPath 11 fooPath, le64 14] second <- serveOne Proto.NotTrusted [clientHello 38, le64 14] pure $ assertEqual "first" (Conn.ClientClosed, serverHello 38 Proto.Trusted <> msgLast <> le64 1 <> rootsHeldBy 0) first `andThen` assertEqual "second" (Conn.ClientClosed, serverHello 38 Proto.NotTrusted <> rootsWithNone) second, runTestM "a client trusted-users does not name is not trusted, and is refused a repair as upstream's daemon refuses it" $ withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = []}) $ \_ address logged -> bracket (connectDaemon address) linkClose $ \link -> do hello <- helloOver link Proto.NotTrusted linkSend link (le64 9 <> wstrs [pathOnWire drvPath <> "!out"] <> le64 1) refused <- receiveToEnd link messages <- logged let message = "repairing is not allowed because you are not in 'trusted-users'" pure $ hello `andThen` assertEqual "refused" (msgError message <> msgError message) refused `andThen` assertEqual "logged" [False] (map (" (trusted)" `T.isSuffixOf`) messages), runTestM "a client allowed-users does not name is sent nothing and the connection closed, and the daemon says why" $ withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = [], ncAllowedUsers = []}) $ \_ address logged -> bracket (connectDaemon address) linkClose $ \link -> do written <- receiveToEnd link messages <- logged pure $ assertEqual "written" "" written `andThen` assertEqual "logged" [True] (map (\message -> "error: while processing connection: user '" `T.isPrefixOf` message && "' is not allowed to connect to the Nix daemon" `T.isSuffixOf` message) messages), runTestM "a daemon told to trust every client trusts one no setting names, without asking who it is" $ withSocketDaemon Listen.ForceTrusted (\config -> config {ncTrustedUsers = [], ncAllowedUsers = []}) $ \_ address logged -> bracket (connectDaemon address) linkClose $ \link -> do hello <- helloOver link Proto.Trusted messages <- logged pure (hello `andThen` assertEqual "logged" ["accepted connection from pid <unknown>, user <unknown> (trusted)"] messages) ] where -- A path's info, answered: the end of the work, the flag, the info. pathInfoReply = Proto.getStderrMessage replyVersion >>= \case Proto.StderrLast -> Wire.getBool >>= \found -> if found then Just <$> Proto.getUnkeyedValidPathInfo defaultStoreDir replyVersion else pure Nothing other -> Wire.malformed ("expected the end of the work, got " <> T.pack (show other)) replyVersion = Proto.Version Proto.latestVersionNumber (Set.fromList (map Proto.Feature serverFeatures)) infoReplySize = BS.length (msgLast <> le64 1) + BS.length (winfoSized (narOf fooPath)) -- A path's info with no deriver, references or signatures: its size -- on the wire, whatever its registration time. winfoSized nar = wstr "" <> wstr (BS.replicate 64 0x30) <> wpaths [] <> le64 0 <> le64 (fromIntegral (BS.length nar)) <> le64 0 <> wstrs [] <> wstr "" rootsHeldBy holder = msgLast <> le64 1 <> wstr ("{temp:" <> BS8.pack (show (holder :: Int)) <> "}") <> wstr (pathOnWire fooPath) rootsWithNone = msgLast <> le64 0-- ----------------------------------------------------------------------------- Tests: builds and substitution through the daemon-- ---------------------------------------------------------------------------testDaemonBuilds :: IO [Bool]testDaemonBuilds = do putStrLn "daemon/builds" basics <- sequence [ runTest "a build is the activity upstream's derivation goal starts, and a check says it checks" $ assertEqual "activities" [ Proto.Activity (Proto.ActivityId 7) (Proto.Verbosity 3) Proto.actBuild ("building '" <> spelled builtDrvPath <> "'") [Proto.FieldString (spelled builtDrvPath), Proto.FieldString "", Proto.FieldInt 1, Proto.FieldInt 1] (Proto.ActivityId 0), Proto.Activity (Proto.ActivityId 8) (Proto.Verbosity 3) Proto.actBuild ("checking outputs of '" <> spelled builtDrvPath <> "'") [Proto.FieldString (spelled builtDrvPath), Proto.FieldString "", Proto.FieldInt 1, Proto.FieldInt 1] (Proto.ActivityId 0) ] [ Ops.storeActivity defaultStoreDir (Proto.ActivityId 7) (Building builtDrvPath), Ops.storeActivity defaultStoreDir (Proto.ActivityId 8) (Checking builtDrvPath) ], runTestM "the activity a store starts reads back from what the daemon sends of it" $ codecProperty $ QC.forAll ((,) <$> genActivityStart <*> QC.arbitrary) $ \(start, number) -> Ops.activityStart defaultStoreDir (Ops.storeActivity defaultStoreDir (Proto.ActivityId number) start) QC.=== Just start, runTest "an upstream daemon's build on a machine, and a repair, read as a build, and an activity of another kind, or that names nothing the store holds, reads as none" $ let activity text fields kind = Proto.Activity (Proto.ActivityId 3) (Proto.Verbosity 3) kind text fields (Proto.ActivityId 0) derivationFields = [Proto.FieldString (spelled builtDrvPath), Proto.FieldString "", Proto.FieldInt 1, Proto.FieldInt 1] building text fields = activity text fields Proto.actBuild startOf = Ops.activityStart defaultStoreDir in assertEqual "on a machine" (Just (Building builtDrvPath)) (startOf (building ("building '" <> spelled builtDrvPath <> "' on 'ssh://builder'") [Proto.FieldString (spelled builtDrvPath), Proto.FieldString "ssh://builder", Proto.FieldInt 1, Proto.FieldInt 1])) `andThen` assertEqual "repair" (Just (Building builtDrvPath)) (startOf (building ("repairing outputs of '" <> spelled builtDrvPath <> "'") derivationFields)) `andThen` assertEqual "check" (Just (Checking builtDrvPath)) (startOf (building ("checking outputs of '" <> spelled builtDrvPath <> "'") derivationFields)) `andThen` assertEqual "another kind" Nothing (startOf (activity "copying" derivationFields (Proto.ActivityType 100))) `andThen` assertEqual "no fields" Nothing (startOf (building "building 'x'" [])) `andThen` assertEqual "a number first" Nothing (startOf (building "building 'x'" [Proto.FieldInt 1])) `andThen` assertEqual "no store path" Nothing (startOf (building "building 'x'" [Proto.FieldString "/not/a/store/path"])) `andThen` assertEqual "a path elsewhere" Nothing (startOf (building "building 'x'" [Proto.FieldString (BS8.pack (storePathToFilePath (StoreDir "/elsewhere/store") builtDrvPath))])) `andThen` assertEqual "substitution without a cache" Nothing (startOf (activity "" [Proto.FieldString (spelled builtPath)] Proto.actSubstitute)) `andThen` assertEqual "a cache that is not UTF-8" Nothing (startOf (activity "" [Proto.FieldString (spelled builtPath), Proto.FieldString "\xFF"] Proto.actSubstitute)), runTest "a substitution is the activity upstream's substitution goal starts, with no text, naming the path and the cache" $ assertEqual "activity" (Proto.Activity (Proto.ActivityId 9) (Proto.Verbosity 0) Proto.actSubstitute "" [Proto.FieldString (spelled builtPath), Proto.FieldString "https://cache.example"] (Proto.ActivityId 0)) (Ops.storeActivity defaultStoreDir (Proto.ActivityId 9) (Substituting builtPath "https://cache.example")), runTest "a connection's download-attempts sets how many times each of its downloads is tried, upstream's number when it sets none" $ let attempts config = frpAttempts (bcFetchRetry (settingsBuildConfig testDefaults config defaultStoreDir)) in assertEqual "default" defaultDownloadAttempts (attempts defaultNixConfig) `andThen` assertEqual "set" 2 (attempts defaultNixConfig {ncDownloadAttempts = 2}), runTest "settings give a build the cores they name, and the machine's count where cores is 0 or nothing sets it" $ let buildCores cores = bcCores (settingsBuildConfig testDefaults {mdCores = 5} defaultNixConfig {ncCores = cores} defaultStoreDir) in assertEqual "unset" 5 (buildCores Nothing) `andThen` assertEqual "zero" 5 (buildCores (Just 0)) `andThen` assertEqual "set" 3 (buildCores (Just 3)), runTestM "for any machine count, 0 and nothing give it and a positive count is the build's" $ codecProperty $ \machine (QC.Positive count) -> let buildCores cores = bcCores (settingsBuildConfig testDefaults {mdCores = machine} defaultNixConfig {ncCores = cores} defaultStoreDir) in QC.conjoin [buildCores Nothing QC.=== machine, buildCores (Just 0) QC.=== machine, buildCores (Just count) QC.=== count], runTest "a client's cores of 0 replaces the daemon's own count, so a build takes the machine's default as upstream's does, and a count it sends is the build's" $ let current = Ops.ConnectionSettings (Proto.Verbosity 3) defaultNixConfig {ncCores = Just 6} Nothing client cores = Ops.ClientSettings False False False (Proto.Verbosity 3) 1 0 True cores True Map.empty buildCores cores = let (applied, _) = Ops.applyClientSettings Proto.Trusted (client cores) current in bcCores (settingsBuildConfig testDefaults {mdCores = 5} (Ops.connConfig applied) defaultStoreDir) in assertEqual "zero" 5 (buildCores Ops.unsetCores) `andThen` assertEqual "set" 3 (buildCores 3) ] shell <- findTestShell served <- sequence [ runTestM "a build through the daemon is an activity the client is sent, its builder's line a result of it, and its output is valid after" $ withBuildable shell $ \store serve -> do (ended, reply) <- serve [le64 9 <> wstrs [pathOnWire builtDrvPath <> "!*"] <> le64 0] valid <- isValid store builtPath pure $ assertEqual "ended" Conn.ClientClosed ended `andThen` assertEqual "valid" True valid `andThen` assertEqual "reported, then answered" (Right ([builtStart, Proto.StderrResult (Proto.ActivityId 1) Proto.resBuildLogLine [Proto.FieldString "hi"], Proto.StderrStopActivity (Proto.ActivityId 1)], True)) (decodeWhole (workThenReply Wire.getBool) reply), runTestM "a build with results says it was built, and where its output is" $ withBuildable shell $ \_ serve -> do let requested = Proto.DerivedBuilt builtDrvPath Proto.AllOutputs outputs = Map.singleton (Proto.OutputName "out") (Proto.UnkeyedRealisation builtPath Set.empty) (_, reply) <- serve [le64 46 <> wstrs [pathOnWire builtDrvPath <> "!*"] <> le64 0] pure $ assertEqual "results" (Right [Proto.KeyedBuildResult requested (Proto.BuildResult (Proto.Succeeded (Proto.Success Proto.Built outputs)) 1 0 0 Nothing Nothing)]) (snd <$> decodeWhole (workThenReply (Proto.getKeyedBuildResults defaultStoreDir builtVersion)) reply), runTestM "what realising a derivation and a path would take: a build of the one, and the other unknown" $ withBuildable shell $ \_ serve -> do (_, reply) <- serve [le64 40 <> wstrs [pathOnWire builtDrvPath <> "!*", pathOnWire missingPath]] pure $ assertEqual "missing" (Right (Proto.Missing (Set.singleton builtDrvPath) Set.empty (Set.singleton missingPath) 0 0)) (snd <$> decodeWhole (workThenReply (Proto.getMissing defaultStoreDir)) reply), runTestM "a derivation the store does not hold and no cache gives fails its request, in upstream's words" $ withServedStore $ \_ _ served _ _ -> do let message = "failed to obtain derivation of '" <> pathOnWire builtDrvPath <> "'" serve request = do (transport, written) <- memoryTransport [clientHello 38, request] _ <- serveLocal served (servedConfig buildableConfig) Proto.Trusted transport BS.drop (BS.length (serverHello 38 Proto.Trusted)) <$> written withResults <- serve (le64 46 <> wstrs [pathOnWire builtDrvPath <> "!*"] <> le64 0) built <- serve (le64 9 <> wstrs [pathOnWire builtDrvPath <> "!*"] <> le64 0) pure $ assertEqual "results" (Right [Proto.KeyedBuildResult (Proto.DerivedBuilt builtDrvPath Proto.AllOutputs) (Proto.BuildResult (Proto.Failed (Proto.Failure Proto.DependencyFailed message False)) 0 0 0 Nothing Nothing)]) (snd <$> decodeWhole (workThenReply (Proto.getKeyedBuildResults defaultStoreDir builtVersion)) withResults) `andThen` assertEqual "built" (msgError message) built, runTestM "a fixed output with other contents than its derivation fixes is rejected, as upstream reports a hash mismatch" $ withServedStore $ \_ store served _ _ -> do let dir = stDir store fixed = (mkTestBuildDrv shell builtPath "printf other > $out") {drvOutputs = [DerivationOutput "out" builtPath "sha256" (T.replicate 64 "0")]} holdDerivation (stDB store) dir builtDrvPath fixed (transport, written) <- memoryTransport [clientHello 38, le64 46 <> wstrs [pathOnWire builtDrvPath <> "!*"] <> le64 0] _ <- serveLocal served (servedConfig buildableConfig) Proto.Trusted transport reply <- BS.drop (BS.length (serverHello 38 Proto.Trusted)) <$> written pure $ case snd <$> decodeWhole (workThenReply (Proto.getKeyedBuildResults defaultStoreDir builtVersion)) reply of Right [Proto.KeyedBuildResult _ (Proto.BuildResult (Proto.Failed (Proto.Failure Proto.OutputRejected message _)) _ _ _ _ _)] | "hash mismatch" `BS.isInfixOf` message -> Pass other -> Fail ("expected the output rejected for its hash, got " <> T.pack (show other)), runTestM "results asked for an output a derivation does not have are refused, as upstream's goal throws" $ withBuildable shell $ \store serve -> do let dir = stDir store refusal = Realise.realiseFailureMessage dir (Realise.MissingOutputs builtDrvPath ("absent" :| [])) (_, reply) <- serve [le64 46 <> wstrs [pathOnWire builtDrvPath <> "!absent"] <> le64 0] pure (assertEqual "refused" (msgError (TE.encodeUtf8 refusal)) reply), runTestM "a repair is refused before anything is substituted or built" $ withBuildable shell $ \_ serve -> do (_, reply) <- serve [le64 9 <> wstrs [pathOnWire missingPath] <> le64 1] pure (assertEqual "refused" (msgError "repairing is not available in nova-nix") reply), runTestM "a path no cache holds has no substituter in the results, in upstream's words" $ withBuildable shell $ \_ serve -> do let message = "path '" <> pathOnWire missingPath <> "' is required, but there is no substituter that can build it" (_, reply) <- serve [le64 46 <> wstrs [pathOnWire missingPath] <> le64 0] pure $ assertEqual "results" (Right [Proto.KeyedBuildResult (Proto.DerivedOpaque missingPath) (Proto.BuildResult (Proto.Failed (Proto.Failure Proto.NoSubstituters message False)) 0 0 0 Nothing Nothing)]) (snd <$> decodeWhole (workThenReply (Proto.getKeyedBuildResults defaultStoreDir builtVersion)) reply), -- Every send after the request has been read fails, as one to a -- client that went away does: the build's reports are dropped, -- and the build still makes its output. runTestM "a build whose client can no longer be sent anything still builds" $ withServedStore $ \_ store served _ _ -> do let dir = stDir store holdDerivation (stDB store) dir builtDrvPath (mkTestBuildDrv shell builtPath "echo hi; echo built > $out") transport <- goneAfterInput [clientHello 38, le64 9 <> wstrs [pathOnWire builtDrvPath <> "!*"] <> le64 0] _ <- try (serveLocal served (servedConfig buildableConfig) Proto.Trusted transport) :: IO (Either IOException Conn.ConnectionEnd) assertEqual "built" True <$> isValid store builtPath, -- The builder says which process it started in the background, -- and the test waits for that process to end once it hangs up. runTestM "a client that hangs up during a build has the build stopped, and every process its builder started killed" $ if SI.os == "mingw32" then Pass <$ putStrLn " SKIP the daemon does not watch a Windows client for its hangup" else withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = ["*"], ncSandbox = Just SandboxDisabled, ncSubstituters = []}) $ \dir address _ -> do bracket (openStoreDB dir) closeStoreDB $ \db -> holdDerivation db dir builtDrvPath (mkTestBuildDrv shell builtPath "sleep 1000 & echo \"started $!\"; wait") bracket (connectDaemon address) linkClose $ \link -> do hello <- helloOver link Proto.Trusted linkSend link (le64 9 <> wstrs [pathOnWire builtDrvPath <> "!*"] <> le64 0) started <- receiveResultLine link startedPrefix case BS8.readInt =<< BS.stripPrefix startedPrefix =<< started of Nothing -> pure (Fail ("the builder did not say which process it started: " <> T.pack (show started))) Just (background, _) -> do linkClose link ended <- c_await_exit (fromIntegral background) (fromIntegral killWaitMillis) pure $ case ended of 0 -> hello 1 -> Fail "a process the builder started outlived the client's hangup" _ -> Fail "the process the builder started could not be watched", runTestM "a path no cache holds cannot be ensured, in upstream's words, and the connection goes on" $ withBuildable shell $ \_ serve -> do (_, reply) <- serve [reqPath 10 missingPath, reqPath 1 missingPath] pure $ assertEqual "refused, then answered" (msgError ("path '" <> pathOnWire missingPath <> "' is required, but there is no substituter that can build it") <> msgLast <> le64 0) reply, runTestM "a path a file:// cache holds is ensured through the daemon, as a substitution activity naming the path and the cache, and is valid after with the cache's NAR hash" $ withServedStore $ \root _ served _ _ -> do let cache = root </> "cache" url = directoryUrl cache holdInFileCache cache cachedPath >>= \case Left err -> pure (Fail ("the cache could not be written: " <> T.pack err)) Right publicKey -> do let config = buildableConfig {ncSubstituters = [url], ncTrustedPublicKeys = [publicKey]} substituted = Proto.Activity (Proto.ActivityId 1) (Proto.Verbosity 0) Proto.actSubstitute "" [Proto.FieldString (pathOnWire cachedPath), Proto.FieldString (TE.encodeUtf8 url)] (Proto.ActivityId 0) infoReply = Wire.getBool >>= \found -> if found then Just . Proto.narHashDigest . Proto.upiNarHash <$> Proto.getUnkeyedValidPathInfo defaultStoreDir builtVersion else pure Nothing (transport, written) <- memoryTransport [clientHello 38, reqPath 10 cachedPath, reqPath 26 cachedPath] _ <- serveLocal served (servedConfig config) Proto.Trusted transport reply <- BS.drop (BS.length (serverHello 38 Proto.Trusted)) <$> written pure $ assertEqual "substituted, then its info" (Right (([Proto.StderrStartActivity substituted, Proto.StderrStopActivity (Proto.ActivityId 1)], True), ([], Just (sha256Digest (servedNar cachedPath))))) (decodeWhole ((,) <$> workThenReply Wire.getBool <*> workThenReply infoReply) reply), -- Upstream's store reads require-sigs as it opens, before a -- client's settings arrive, so the daemon's setting holds a -- substitution to a signature whatever a trusted client sets. runTestM "a trusted client that turns require-sigs off does not have a path substituted that no key the daemon trusts signed" $ withServedStore $ \root store served _ _ -> do let cache = root </> "cache" config = buildableConfig {ncSubstituters = [directoryUrl cache]} refusal = msgError ("path '" <> pathOnWire cachedPath <> "' is required, but there is no substituter that can build it") holdInFileCache cache cachedPath >>= \case Left err -> pure (Fail ("the cache could not be written: " <> T.pack err)) Right _ -> do (_, reply) <- serveAdding served config Proto.Trusted [setOptionsAt 3 [("require-sigs", "false")], reqPath 10 cachedPath] valid <- isValid store cachedPath pure (assertEqual "valid" False valid `andThen` assertEqual "refused" refusal (BS.takeEnd (BS.length refusal) reply)), runTestM "a trusted client that turns require-sigs on does not have a path refused that the daemon takes unsigned by any key it trusts" $ withServedStore $ \root store served _ _ -> do let cache = root </> "cache" config = buildableConfig {ncSubstituters = [directoryUrl cache], ncRequireSigs = False} holdInFileCache cache cachedPath >>= \case Left err -> pure (Fail ("the cache could not be written: " <> T.pack err)) Right _ -> do (_, reply) <- serveAdding served config Proto.Trusted [setOptionsAt 3 [("require-sigs", "true")], reqPath 10 cachedPath] valid <- isValid store cachedPath pure (assertEqual "valid" True valid `andThen` assertEqual "answered" (le64 1) (BS.takeEnd 8 reply)) ] pure (basics ++ served) where spelled = TE.encodeUtf8 . storePathToText defaultStoreDir builtVersion = Proto.Version Proto.latestVersionNumber (Set.fromList (map Proto.Feature serverFeatures)) builtStart = Proto.StderrStartActivity (Proto.Activity (Proto.ActivityId 1) (Proto.Verbosity 3) Proto.actBuild ("building '" <> pathOnWire builtDrvPath <> "'") [Proto.FieldString (pathOnWire builtDrvPath), Proto.FieldString "", Proto.FieldInt 1, Proto.FieldInt 1] (Proto.ActivityId 0)) -- The work's reports other than its lines, then the reply. workThenReply reply = go [] where go seen = Proto.getStderrMessage builtVersion >>= \case Proto.StderrLast -> (,) (reverse seen) <$> reply Proto.StderrNext _ -> go seen message -> go (message : seen)-- | Read a daemon's messages from a socket until a build's line that-- starts with the bytes arrives: that line, or 'Nothing' when the input-- ends or does not read as messages first.receiveResultLine :: DaemonLink -> BS.ByteString -> IO (Maybe BS.ByteString)receiveResultLine link prefix = go BS.empty where version = Proto.Version Proto.latestVersionNumber (Set.fromList (map Proto.Feature serverFeatures)) go arrived = case Wire.runDecoder (Proto.getStderrMessage version) arrived of Right (Proto.StderrResult _ kind [Proto.FieldString line], _) | kind == Proto.resBuildLogLine && prefix `BS.isPrefixOf` line -> pure (Just line) Right (_, rest) -> go rest Left Wire.InputEnded -> linkReceive link receiveSize >>= \chunk -> if BS.null chunk then pure Nothing else go (arrived <> chunk) Left (Wire.Malformed _) -> pure Nothing receiveSize = 4096-- | What the hangup test's builder says before the process it started.startedPrefix :: BS.ByteStringstartedPrefix = "started "-- | How long a hangup test waits for the process a builder started to be-- gone, within the time the whole socket test has.killWaitMillis :: IntkillWaitMillis = socketTestMicros `div` 2000-- | Wait up to the milliseconds given for a process to end, not only a-- child ("process_wait.c"): 0 once it has, 1 when it still runs, -1 on-- failure.foreign import ccall safe "nova_test_await_exit" c_await_exit :: CInt -> CInt -> IO CInt-- | Write a derivation into a store and register it, as a client's-- AddToStore would leave it.holdDerivation :: StoreDB -> StoreDir -> StorePath -> Derivation -> IO ()holdDerivation db dir path drv = do let aterm = toATerm drv BS.writeFile (storePathToFilePath dir path) aterm registerPath db (PathRegistration path (Hash.formatNixHash (Hash.hashBytes aterm)) (BS.length aterm) Nothing [] NotUltimate Set.empty Nothing RegisteredNow)-- | A transport over input given whose sends fail once the last of the-- input has been read, as they do to a client that went away.goneAfterInput :: [BS.ByteString] -> IO (Conn.Transport IO)goneAfterInput input = do pending <- newIORef (filter (not . BS.null) input) let receive = atomicModifyIORef' pending (\case [] -> ([], Nothing); chunk : rest -> (rest, Just chunk)) send _ = readIORef pending >>= \case [] -> ioError (mkIOError resourceVanishedErrorType "the client went away" Nothing Nothing) _ -> pure () pure (Conn.Transport receive send)-- | The settings a daemon test's builds run under: unsandboxed, and with-- no cache to ask.buildableConfig :: NixConfigbuildableConfig = defaultNixConfig {ncSandbox = Just SandboxDisabled, ncSubstituters = []}-- | A served store holding a derivation whose builder, run by the shell-- given, writes one line, and a way to serve a trusted client at 1.38 that sends requests: how-- its connection ended and what it was sent after the handshake. Builds-- run unsandboxed and nothing is substituted, so the test asks no cache.withBuildable :: Text -> (Store -> ([BS.ByteString] -> IO (Conn.ConnectionEnd, BS.ByteString)) -> IO TestResult) -> IO TestResultwithBuildable shell body = withServedStore $ \_ store served _ _ -> do holdDerivation (stDB store) (stDir store) builtDrvPath (mkTestBuildDrv shell builtPath "echo hi; echo built > $out") let config = buildableConfig serve requests = do (transport, written) <- memoryTransport (clientHello 38 : requests) ended <- serveLocal served (servedConfig config) Proto.Trusted transport (,) ended . BS.drop (BS.length (serverHello 38 Proto.Trusted)) <$> written body store serve-- | The derivation a daemon test builds, and its output.builtDrvPath, builtPath :: StorePathbuiltDrvPath = StorePath "0000000000000000000000000000000b" "built.drv"builtPath = StorePath "0000000000000000000000000000000c" "built"-- | The path a daemon test substitutes from a file:// cache.cachedPath :: StorePathcachedPath = StorePath "0000000000000000000000000000000d" "cached"-- | Write a file:// cache holding a path, uncompressed, as the NAR-- 'servedNar' gives it, with its narinfo signed by 'sigTestKeyText': the-- public key that verifies it, or why it could not be signed.holdInFileCache :: FilePath -> StorePath -> IO (Either String Text)holdInFileCache cache path = case signedTestNarInfo path [] (T.pack narFile) (servedNar path) of Left err -> pure (Left err) Right (publicKey, narInfo) -> do Dir.createDirectoryIfMissing True (cache </> "nar") BS.writeFile (cache </> cacheInfoFileName) cacheInfoText BS.writeFile (cache </> T.unpack (spHash path) <> ".narinfo") (TE.encodeUtf8 narInfo) BS.writeFile (cache </> narFile) (servedNar path) pure (Right publicKey) where narFile = "nar/" <> T.unpack (spName path) <> ".nar"-- | Machine defaults a served store's builds fall back on, the same on-- every machine: one core, no sandbox helper or bundled shell, not root,-- so no build users, and no certificate bundle.testDefaults :: MachineDefaultstestDefaults = MachineDefaults { mdCores = 1, mdSandboxHelper = Nothing, mdSandboxShell = Set.empty, mdPrivilege = RunsUnprivileged, mdUserPool = "/nix/var/nix/userpool", mdCaFile = Nothing }-- ----------------------------------------------------------------------------- Tests: adding paths through the daemon-- ----------------------------------------------------------------------------- | Derivations, dumps and NARs a client adds to a served store through-- the daemon, over a transport in memory, so they run wherever the store-- does: each is valid after with what it was added with, or refused in-- upstream's words with nothing left behind.testDaemonAdds :: IO [Bool]testDaemonAdds = do putStrLn "daemon/adds" linked <- symlinksAvailable sequence [ runTestM "a client the daemon does not trust adds a derivation as a text, and is answered upstream's path for it" $ withServedStore $ \_ store served _ _ -> case upstreamDrv of Left err -> pure (Fail err) Right (aterm, drvFile) | drvFile /= StorePath "wwk71dy0w17kn5spjd8hbsrk6520xs11" "d.drv" -> pure (Fail ("the derivation's own path is not upstream's: " <> T.pack (show drvFile))) | otherwise -> do let dir = stDir store expected = addedFrom drvFile (regularNar aterm) [] (textAddress aterm) (ended, reply) <- serveAdding served defaultNixConfig Proto.NotTrusted [dumpRequest "d.drv" "text:sha256" [] <> framedIn 7 aterm] held <- addedAs store drvFile contents <- BS.readFile (storePathToFilePath dir drvFile) pure $ assertEqual "ended" Conn.ClientClosed ended `andThen` assertEqual "answered" (Right (Right expected)) (decodeWhole (answerOf (answeredAs <$> Proto.getValidPathInfo defaultStoreDir addVersion)) reply) `andThen` assertEqual "registered" (Just expected) held `andThen` assertEqual "contents" aterm contents, runTestM "a source tree is added as a recursive dump, arriving in frames that split its archive anywhere, with the paths it references" $ withServedStore $ \_ store served _ _ -> do let dir = stDir store nar = NAR.serialise ( NAR.NarDirectory [ ("bin", NAR.NarDirectory [("run", NAR.NarRegular True "#!/bin/sh\n")]), ("data", NAR.NarRegular False ("refers to " <> pathOnWire fooPath)) ] ) case makeSourcePath "source" (sha256Digest nar) (Set.singleton fooPath) of Left err -> pure (Fail (T.pack (show err))) Right sourcePath -> do let expected = addedFrom sourcePath nar [fooPath] (Proto.contentAddressFromParts (Proto.FixedMethod NarIngestion) "sha256" (sha256Digest nar)) (_, reply) <- serveAdding served defaultNixConfig Proto.Trusted [dumpRequest "source" "fixed:r:sha256" [fooPath] <> framedIn 13 nar] held <- addedAs store sourcePath executable <- ExecBit.isExecutable (storePathToFilePath dir sourcePath </> "bin" </> "run") staged <- stagingLeft store pure $ assertEqual "answered" (Right (Right expected)) (decodeWhole (answerOf (answeredAs <$> Proto.getValidPathInfo defaultStoreDir addVersion)) reply) `andThen` assertEqual "registered" (Just expected) held `andThen` assertEqual "executable" True executable `andThen` assertEqual "staging left" [] staged, runTestM "a fixed output is added from a flat dump hashed with the algorithm it names" $ withServedStore $ \_ store served _ _ -> do let dir = stDir store contents = "hello\n" case Hash.rawHashWithAlgo "sha1" contents of Nothing -> pure (Fail "no SHA-1") Just digest -> case makeFixedOutputPath "hello.txt" "sha1" FlatIngestion digest of Left err -> pure (Fail (T.pack (show err))) Right flatPath -> do let expected = addedFrom flatPath (regularNar contents) [] (Proto.contentAddressFromParts (Proto.FixedMethod FlatIngestion) "sha1" digest) (_, reply) <- serveAdding served defaultNixConfig Proto.NotTrusted [dumpRequest "hello.txt" "fixed:sha1" [] <> framedIn 4 contents] held <- addedAs store flatPath onDisk <- BS.readFile (storePathToFilePath dir flatPath) pure $ assertEqual "answered" (Right (Right expected)) (decodeWhole (answerOf (answeredAs <$> Proto.getValidPathInfo defaultStoreDir addVersion)) reply) `andThen` assertEqual "registered" (Just expected) held `andThen` assertEqual "contents" contents onDisk, runTestM "what a dump's address cannot make is refused in upstream's words, the dump read past, and the connection goes on" $ withServedStore $ \_ store served _ _ -> do (ended, reply) <- serveAdding served defaultNixConfig Proto.NotTrusted [ dumpRequest "refused" "fixed:sha256" [fooPath] <> framedIn 4 "contents", dumpRequest "refused" "text:sha1" [] <> framedIn 4 "contents", reqPath 1 fooPath ] staged <- stagingLeft store pure $ assertEqual "ended" Conn.ClientClosed ended `andThen` assertEqual "refused, then answered" ( msgError "fixed output derivation 'refused' is not allowed to refer to other store paths.\nYou may need to use the 'unsafeDiscardReferences' derivation attribute, see the manual for more details." <> msgError "cannot add 'refused' as a text hashed with sha1: a text's content address is its sha256 hash" <> msgLast <> le64 1 ) reply `andThen` assertEqual "staging left" [] staged, runTestM "a dump whose archive goes on past its end is refused, and nothing is left of it" $ withServedStore $ \_ store served _ _ -> do (_, reply) <- serveAdding served defaultNixConfig Proto.NotTrusted [dumpRequest "trailing" "fixed:r:sha256" [] <> framedIn 16 (regularNar "contents" <> "more")] staged <- stagingLeft store pure (assertEqual "refused" (msgError "trailing bytes after NAR root node") reply `andThen` assertEqual "staging left" [] staged), runTestM "the git-hashing method is refused as upstream refuses it without the experimental feature, before the dump is read" $ withServedStore $ \_ _ served _ _ -> do (_, reply) <- serveAdding served defaultNixConfig Proto.Trusted [dumpRequest "git" "fixed:git:sha1" [], reqPath 1 fooPath] pure (assertEqual "refused, then answered" (msgError "experimental Nix feature 'git-hashing' is disabled; add '--extra-experimental-features git-hashing' to enable it" <> msgLast <> le64 1) reply), runTestM "a NAR a trusted client sends unchecked is imported with its deriver, references and signatures, and its path is a root of the connection" $ withServedStore $ \_ store served _ _ -> do let dir = stDir store nar = regularNar "imported" case (narInfoOf nar [fooPath] (Just builtDrvPath), Proto.parseSignature ("other-key:" <> TE.encodeUtf8 (B64.encode (BS.replicate 64 7)))) of (Just info, Right sig) -> do let sent = info {Proto.upiSignatures = Set.singleton sig, Proto.upiUltimate = True} (_, reply) <- serveAdding served defaultNixConfig Proto.Trusted [narRequest importedPath sent NoCheck <> framedIn 9 nar, le64 14] held <- addedAs store importedPath row <- queryPathInfo (stDB store) importedPath pure $ assertEqual "imported, then the roots" (Right (Right (), Right [(importedPath, ["{temp:0}"])])) (decodeWhole ((,) <$> answerOf (pure ()) <*> answerOf (rootsListed <$> Proto.getRoots defaultStoreDir)) reply) `andThen` assertEqual "registered" (Just (addedFrom importedPath nar [fooPath] Nothing)) held `andThen` assertEqual "deriver, signatures, ultimate" (Just (Just (T.pack (storePathToFilePath dir builtDrvPath)), Set.singleton sig, Ultimate)) ((\found -> (piDeriver found, piSignatures found, piUltimate found)) <$> row) other -> pure (Fail ("no info to send: " <> T.pack (show other))), runTestM "a NAR signed by a key trusted-public-keys names is imported from a client the daemon does not trust, which cannot ask that it not be checked" $ withServedStore $ \_ store served _ _ -> do let nar = regularNar "signed" case (narInfoOf nar [fooPath] Nothing, testPublicKey) of (Just info, Right publicKey) -> case signedFor signedPath info of Left err -> pure (Fail (T.pack err)) Right sig -> do let sent = info {Proto.upiSignatures = Set.singleton sig} (_, reply) <- serveAdding served defaultNixConfig {ncTrustedPublicKeys = [publicKey]} Proto.NotTrusted [narRequest signedPath sent NoCheck <> framedIn 64 nar] held <- addedAs store signedPath row <- queryPathInfo (stDB store) signedPath pure $ assertEqual "imported" msgLast reply `andThen` assertEqual "registered" (Just (addedFrom signedPath nar [fooPath] Nothing)) held `andThen` assertEqual "signatures" (Just (Set.singleton sig)) (piSignatures <$> row) other -> pure (Fail ("no info or key: " <> T.pack (show other))), runTestM "an unsigned NAR of a path that is not content-addressed is refused a client the daemon does not trust, in upstream's words, and nothing of it is kept" $ withServedStore $ \_ store served _ _ -> do let dir = stDir store nar = regularNar "unsigned" case narInfoOf nar [] Nothing of Nothing -> pure (Fail "no info to send") Just info -> do (ended, reply) <- serveAdding served defaultNixConfig Proto.NotTrusted [narRequest unsignedPath info NoCheck <> framedIn 8 nar, le64 14, reqPath 1 unsignedPath] written <- Dir.doesPathExist (storePathToFilePath dir unsignedPath) staged <- stagingLeft store pure $ assertEqual "ended" Conn.ClientClosed ended `andThen` assertEqual "refused, no root kept for it, and not valid" (msgError ("cannot add path '" <> pathOnWire unsignedPath <> "' because it lacks a signature by a trusted key") <> msgLast <> le64 0 <> msgLast <> le64 0) reply `andThen` assertEqual "written" False written `andThen` assertEqual "staging left" [] staged, runTestM "a NAR whose hash or size is not its info's is refused in upstream's words, and nothing of it is kept" $ withServedStore $ \_ store served _ _ -> do let dir = stDir store nar = regularNar "mismatch" sri bytes = "sha256-" <> TE.encodeUtf8 (B64.encode bytes) case (narInfoOf nar [] Nothing, Proto.narHashFromDigest (sha256Digest "not the nar")) of (Just info, Just otherHash) -> do let wrongHash = info {Proto.upiNarHash = otherHash} wrongSize = info {Proto.upiNarSize = Proto.upiNarSize info + 8} (_, reply) <- serveAdding served defaultNixConfig Proto.Trusted [narRequest mismatchPath wrongHash NoCheck <> framedIn 16 nar, narRequest mismatchPath wrongSize NoCheck <> framedIn 16 nar] written <- Dir.doesPathExist (storePathToFilePath dir mismatchPath) valid <- isValid store mismatchPath staged <- stagingLeft store let spelled = pathOnWire mismatchPath pure $ assertEqual "refused" ( msgError ("hash mismatch importing path '" <> spelled <> "';\n specified: " <> sri (sha256Digest "not the nar") <> "\n got: " <> sri (sha256Digest nar)) <> msgError ("size mismatch importing path '" <> spelled <> "';\n specified: " <> BS8.pack (show (BS.length nar + 8)) <> "\n got: " <> BS8.pack (show (BS.length nar))) ) reply `andThen` assertEqual "written, valid" (False, False) (written, valid) `andThen` assertEqual "staging left" [] staged other -> pure (Fail ("no info to send: " <> T.pack (show other))), -- The daemon reads a NAR to the size its info states, where upstream -- reads it to its root node's close and then holds it to that size. runTestM "a NAR longer than the size its info states is refused as an archive cut short there, and nothing of it is kept" $ withServedStore $ \_ store served _ _ -> do let dir = stDir store nar = regularNar "longer" case narInfoOf nar [] Nothing of Nothing -> pure (Fail "no info to send") Just info -> do (ended, reply) <- serveAdding served defaultNixConfig Proto.Trusted [narRequest mismatchPath info {Proto.upiNarSize = Proto.upiNarSize info - 8} NoCheck <> framedIn 16 nar, reqPath 1 mismatchPath] written <- Dir.doesPathExist (storePathToFilePath dir mismatchPath) staged <- stagingLeft store pure $ assertEqual "ended" Conn.ClientClosed ended `andThen` assertEqual "refused, then not valid" (msgError "unexpected end of NAR: node closing" <> msgLast <> le64 0) reply `andThen` assertEqual "written, staging left" (False, []) (written, staged), runTestM "a path already valid is answered as added without its NAR or dump being written, and its registration is kept" $ withServedStore $ \_ store served _ _ -> do let dir = stDir store otherNar = regularNar "other contents" contents = "flat\n" case (narInfoOf otherNar [] Nothing, makeFixedOutputPath "kept" "sha256" FlatIngestion (sha256Digest contents)) of (Just info, Right keptPath) -> do -- Registered with a NAR that is not its dump's, which the -- answer names only if it comes from the registration. let registeredNar = regularNar "what was there" BS.writeFile (storePathToFilePath dir keptPath) "what was there" registerPath (stDB store) (PathRegistration keptPath (Hash.formatNixHash (Hash.hashBytes registeredNar)) (BS.length registeredNar) Nothing [] NotUltimate Set.empty Nothing RegisteredNow) (_, reply) <- serveAdding served defaultNixConfig Proto.Trusted [narRequest fooPath info NoCheck <> framedIn 8 otherNar, dumpRequest "kept" "fixed:sha256" [] <> framedIn 8 contents] fooWritten <- Dir.doesPathExist (storePathToFilePath dir fooPath) fooHeld <- addedAs store fooPath keptContents <- BS.readFile (storePathToFilePath dir keptPath) pure $ assertEqual "answered, the dump from its registration" (Right (Right (), Right (addedFrom keptPath registeredNar [] Nothing))) (decodeWhole ((,) <$> answerOf (pure ()) <*> answerOf (answeredAs <$> Proto.getValidPathInfo defaultStoreDir addVersion)) reply) `andThen` assertEqual "foo written" False fooWritten `andThen` assertEqual "foo kept" (Just (addedFrom fooPath (narOf fooPath) [] Nothing)) fooHeld `andThen` assertEqual "kept contents" "what was there" keptContents other -> pure (Fail ("no info to send: " <> T.pack (show other))), runTestM "several NARs sent together are each imported, one already valid passed over" $ withServedStore $ \_ store served _ _ -> do let fooNar = narOf fooPath newNar = NAR.serialise (NAR.NarDirectory [("file", NAR.NarRegular False "new")]) case (narInfoOf fooNar [] Nothing, narInfoOf newNar [fooPath] Nothing) of (Just fooSent, Just newSent) -> do let upload = le64 2 <> addressedUploadInfo fooPath fooSent <> fooNar <> addressedUploadInfo importedPath newSent <> newNar (_, reply) <- serveAdding served defaultNixConfig Proto.Trusted [le64 44 <> le64 0 <> le64 1 <> framedIn 24 upload, reqPath 1 importedPath] held <- addedAs store importedPath pure $ assertEqual "imported, then valid" (msgLast <> msgLast <> le64 1) reply `andThen` assertEqual "registered" (Just (addedFrom importedPath newNar [fooPath] Nothing)) held other -> pure (Fail ("no info to send: " <> T.pack (show other))), runTestM "a trusted key that does not read refuses a checked import in upstream's words" $ withServedStore $ \_ _ served _ _ -> do let nar = regularNar "keyed" importWith keys = case narInfoOf nar [] Nothing of Nothing -> pure (Left "no info to send") Just info -> do (_, reply) <- serveAdding served defaultNixConfig {ncTrustedPublicKeys = keys} Proto.NotTrusted [narRequest signedPath info Check <> framedIn 8 nar] pure (decodeWhole (answerOf (pure ())) reply) refusal message traces = Right (Left ((Ops.daemonError message) {Proto.errTraces = traces})) corrupt <- importWith ["not a key"] short <- importWith ["k:AAAA"] pure $ assertEqual "corrupt" (refusal "key is corrupt" ["while decoding key named '' with raw value 'not a key'"]) corrupt `andThen` assertEqual "short" (refusal "public key is not valid" []) short, runTestM "a secret key file that does not read refuses a checked import in upstream's words, which keep its contents out of the trace" $ withServedStore $ \root _ served _ _ -> do let nar = regularNar "keyed" keyFile = root </> "corrupt-key" BS.writeFile keyFile "not a key\n" spelled <- argumentBytes keyFile case (narInfoOf nar [] Nothing, spelled) of (Nothing, _) -> pure (Fail "no info to send") (_, Nothing) -> pure (Fail "the key file's path has no spelling as bytes") (Just info, Just file) -> do (_, reply) <- serveAdding served defaultNixConfig {ncSecretKeyFiles = [file]} Proto.NotTrusted [narRequest signedPath info Check <> framedIn 8 nar] pure (assertEqual "refused" (Right (Left ((Ops.daemonError "key is corrupt") {Proto.errTraces = ["while decoding key named ''"]}))) (decodeWhole (answerOf (pure ())) reply)), runTestM "a NAR signed by the key in a file secret-key-files names is imported from a client the daemon does not trust, and a file that cannot be read is passed over" $ withServedStore $ \root store served _ _ -> do let nar = regularNar "signed by a secret key" keyFile = root </> "secret-key" case (narInfoOf nar [] Nothing, sigTestSecretKeyFile) of (Just info, Right keyBytes) -> case signedFor signedPath info of Left err -> pure (Fail (T.pack err)) Right sig -> do BS.writeFile keyFile keyBytes spelled <- sequence <$> traverse argumentBytes [root </> "missing-key", keyFile] case spelled of Nothing -> pure (Fail "a key file's path has no spelling as bytes") Just files -> do (_, reply) <- serveAdding served defaultNixConfig {ncSecretKeyFiles = files} Proto.NotTrusted [narRequest signedPath info {Proto.upiSignatures = Set.singleton sig} Check <> framedIn 16 nar] held <- addedAs store signedPath pure (assertEqual "imported" msgLast reply `andThen` assertEqual "registered" (Just (addedFrom signedPath nar [] Nothing)) held) other -> pure (Fail ("no info or key: " <> T.pack (show other))), runTestM "under require-sigs off an unsigned NAR is imported from a client the daemon does not trust, and no key is read" $ withServedStore $ \_ store served _ _ -> do let nar = regularNar "unsigned, unchecked" case narInfoOf nar [] Nothing of Nothing -> pure (Fail "no info to send") Just info -> do (_, reply) <- serveAdding served defaultNixConfig {ncRequireSigs = False, ncTrustedPublicKeys = ["not a key"]} Proto.NotTrusted [narRequest unsignedPath info Check <> framedIn 16 nar] held <- addedAs store unsignedPath pure (assertEqual "imported" msgLast reply `andThen` assertEqual "registered" (Just (addedFrom unsignedPath nar [] Nothing)) held), -- Upstream's store reads require-sigs as it opens, before a client's -- settings arrive. runTestM "a trusted client that turns require-sigs off still has a checked import held to the daemon's" $ withServedStore $ \_ store served _ _ -> do let nar = regularNar "checked anyway" case narInfoOf nar [] Nothing of Nothing -> pure (Fail "no info to send") Just info -> do (_, reply) <- serveAdding served defaultNixConfig Proto.Trusted [setOptionsAt 3 [("require-sigs", "false")], narRequest unsignedPath info Check <> framedIn 16 nar] valid <- isValid store unsignedPath pure $ assertEqual "refused" (msgLast <> msgError ("cannot add path '" <> pathOnWire unsignedPath <> "' because it lacks a signature by a trusted key")) reply `andThen` assertEqual "valid" False valid, -- Upstream prints the warning at its error level, so a client that -- asks to hear errors alone hears it. runTestM "a content address that does not make its path is warned of at the error level, which a client hearing only errors is sent" $ withServedStore $ \_ _ served _ _ -> do let nar = regularNar "misaddressed" case narInfoOf nar [] Nothing of Nothing -> pure (Fail "no info to send") Just info -> do let claimed = info {Proto.upiContentAddress = Proto.contentAddressFromParts (Proto.FixedMethod NarIngestion) "sha256" (sha256Digest nar)} spelled = pathOnWire unsignedPath (_, reply) <- serveAdding served defaultNixConfig Proto.NotTrusted [setOptionsAt 0 [], narRequest unsignedPath claimed Check <> framedIn 16 nar] pure $ assertEqual "warned, then refused" ( msgLast <> msgNext ("warning: path '" <> spelled <> "' claims to be content-addressed but isn't\n") <> msgError ("cannot add path '" <> spelled <> "' because it lacks a signature by a trusted key") ) reply, runTestM "a NAR's path is registered at the time its info states, sent alone or with others, and at the time of its import where its info states 0" $ withServedStore $ \_ store served _ _ -> do let stated = 1234567890 aloneNar = regularNar "stated alone" togetherNar = regularNar "stated together" unstatedNar = regularNar "unstated" case (narInfoOf aloneNar [] Nothing, narInfoOf togetherNar [] Nothing, narInfoOf unstatedNar [] Nothing) of (Just alone, Just together, Just unstated) -> do let upload = le64 1 <> addressedUploadInfo signedPath together {Proto.upiRegistrationTime = stated} <> togetherNar before <- floor <$> getPOSIXTime (_, reply) <- serveAdding served defaultNixConfig Proto.Trusted [ narRequest importedPath alone {Proto.upiRegistrationTime = stated} NoCheck <> framedIn 16 aloneNar, le64 44 <> le64 0 <> le64 1 <> framedIn 24 upload, narRequest unsignedPath unstated NoCheck <> framedIn 16 unstatedNar ] after <- ceiling <$> getPOSIXTime times <- traverse (fmap (fmap piRegTime) . queryPathInfo (stDB store)) [importedPath, signedPath, unsignedPath] pure $ assertEqual "imported" (msgLast <> msgLast <> msgLast) reply `andThen` case times of [Just aloneTime, Just togetherTime, Just importTime] | (aloneTime, togetherTime) == (fromIntegral stated, fromIntegral stated) && before <= importTime && importTime <= after -> Pass other -> Fail ("registration times: " <> T.pack (show other) <> ", imported between " <> T.pack (show (before :: Int, after))) other -> pure (Fail ("no info to send: " <> T.pack (show other))), runTestM "an upload that breaks off, or whose client is stopped between two of its chunks, leaves nothing behind" $ withServedStore $ \_ store served _ _ -> do let nar = NAR.serialise (NAR.NarDirectory [("a", NAR.NarRegular False (BS.replicate 64 1)), ("b", NAR.NarRegular False "b")]) opening = dumpRequest "cut" "fixed:r:sha256" [] <> wframe (BS.take 100 nar) (transport, written) <- memoryTransport [clientHello 38, opening] broken <- serveLocal served (servedConfig defaultNixConfig) Proto.Trusted transport told <- BS.drop (BS.length (serverHello 38 Proto.Trusted)) <$> written brokenLeft <- stagingLeft store reached <- newEmptyMVar stopped <- newEmptyMVar block <- newEmptyMVar stalling <- stallingTransport [clientHello 38, opening] (putMVar reached ()) block thread <- forkFinally (serveLocal served (servedConfig defaultNixConfig) Proto.Trusted stalling) (\_ -> putMVar stopped ()) takeMVar reached stalledLeft <- stagingLeft store killThread thread takeMVar stopped putMVar block () killedLeft <- stagingLeft store pure $ assertEqual "broken off" (Conn.ClientClosed, msgError "unexpected end-of-file") (broken, told) `andThen` assertEqual "left once broken off" [] brokenLeft `andThen` assertEqual "staged while it stalls" 1 (length stalledLeft) `andThen` assertEqual "left once stopped" [] killedLeft, runTestM "a NAR whose root is a symlink is imported where the host makes links" $ if not linked then Pass <$ putStrLn " SKIP this host does not make symlinks" else withServedStore $ \_ store served _ _ -> do let dir = stDir store nar = NAR.serialise (NAR.NarSymlink "target") case narInfoOf nar [] Nothing of Nothing -> pure (Fail "no info to send") Just info -> do (_, reply) <- serveAdding served defaultNixConfig Proto.Trusted [narRequest importedPath info NoCheck <> framedIn 8 nar] target <- Dir.getSymbolicLinkTarget (storePathToFilePath dir importedPath) held <- addedAs store importedPath pure (assertEqual "imported" msgLast reply `andThen` assertEqual "target" "target" target `andThen` assertEqual "registered" (Just (addedFrom importedPath nar [] Nothing)) held), -- A link's Windows flavour is read off what its target reaches from -- where the link is made, so a link made before its tree is moved -- to its path reaches one directory too deep. runTestM "a link that an imported NAR or a recursive dump makes to a directory of a sibling path reaches it as a directory" $ if not linked then Pass <$ putStrLn " SKIP this host does not make symlinks" else withServedStore $ \_ store served _ _ -> do let dir = stDir store depLib = storePathToFilePath dir siblingPath </> "lib" nar = NAR.serialise (NAR.NarDirectory [("lib", NAR.NarSymlink ("../" <> TE.encodeUtf8 (storePathBasename siblingPath) <> "/lib"))]) digest = sha256Digest nar Dir.createDirectoryIfMissing True depLib BS.writeFile (depLib </> "hello") "hello" case (narInfoOf nar [] Nothing, makeSourcePath "linked" digest Set.empty) of (Just info, Right dumpedPath) -> do (_, reply) <- serveAdding served defaultNixConfig Proto.Trusted [narRequest importedPath info NoCheck <> framedIn 16 nar, dumpRequest "linked" "fixed:r:sha256" [] <> framedIn 16 nar] reached <- traverse (\path -> let lib = storePathToFilePath dir path </> "lib" in (,) <$> Dir.doesDirectoryExist lib <*> Dir.doesFileExist (lib </> "hello")) [importedPath, dumpedPath] pure $ assertEqual "imported, then added" (Right (Right (), Right (addedFrom dumpedPath nar [] (Proto.contentAddressFromParts (Proto.FixedMethod NarIngestion) "sha256" digest)))) (decodeWhole ((,) <$> answerOf (pure ()) <*> answerOf (answeredAs <$> Proto.getValidPathInfo defaultStoreDir addVersion)) reply) `andThen` assertEqual "a directory, and its file, through each link" [(True, True), (True, True)] reached other -> pure (Fail ("no info to send: " <> T.pack (show other))), runTestM "an unsigned NAR whose content address makes its path is imported from a client the daemon does not trust" $ withServedStore $ \_ store served _ _ -> do let nar = NAR.serialise (NAR.NarDirectory [("file", NAR.NarRegular False ("refers to " <> pathOnWire fooPath))]) digest = sha256Digest nar address = Proto.contentAddressFromParts (Proto.FixedMethod NarIngestion) "sha256" digest case (narInfoOf nar [fooPath] Nothing, makeSourcePath "addressed" digest (Set.singleton fooPath)) of (Just info, Right addressedPath) -> do (_, reply) <- serveAdding served defaultNixConfig Proto.NotTrusted [narRequest addressedPath info {Proto.upiContentAddress = address} Check <> framedIn 16 nar] held <- addedAs store addressedPath pure (assertEqual "imported" msgLast reply `andThen` assertEqual "registered" (Just (addedFrom addressedPath nar [fooPath] address)) held) other -> pure (Fail ("no info to send: " <> T.pack (show other))), -- Upstream refuses to make a path from such an address, which it -- does while it counts a path's signatures, before it reads the NAR, -- and again as it registers the path. runTestM "a fixed address other than a NAR's SHA-256 stated with references is refused in upstream's words: before the NAR is read where signatures are checked, and as the path is registered where they are not" $ withServedStore $ \_ store served _ _ -> do let dir = stDir store contents = "fixed contents" nar = regularNar contents digest = sha256Digest contents refusal = msgError "fixed output derivation 'fixed' is not allowed to refer to other store paths.\nYou may need to use the 'unsafeDiscardReferences' derivation attribute, see the manual for more details." case (narInfoOf nar [fooPath] Nothing, makeFixedOutputPath "fixed" "sha256" FlatIngestion digest) of (Just info, Right fixedPath) -> do let sent = info {Proto.upiContentAddress = Proto.contentAddressFromParts (Proto.FixedMethod FlatIngestion) "sha256" digest} -- Bytes no archive begins with, which a read would -- refuse in other words. notArchive = BS.replicate (BS.length nar) 0 (_, checked) <- serveAdding served defaultNixConfig Proto.NotTrusted [narRequest fixedPath sent Check <> framedIn 16 notArchive, reqPath 1 fixedPath] checkedStaged <- stagingLeft store (_, unchecked) <- serveAdding served defaultNixConfig Proto.Trusted [narRequest fixedPath sent NoCheck <> framedIn 16 nar, reqPath 1 fixedPath] written <- Dir.doesPathExist (storePathToFilePath dir fixedPath) staged <- stagingLeft store pure $ assertEqual "checked, then not valid" (refusal <> msgLast <> le64 0) checked `andThen` assertEqual "staged where checked" [] checkedStaged `andThen` assertEqual "unchecked, then not valid" (refusal <> msgLast <> le64 0) unchecked `andThen` assertEqual "written, staging left" (False, []) (written, staged) other -> pure (Fail ("no info to send: " <> T.pack (show other))), runTestM "a reference that is not valid is refused in upstream's words, a NAR's or a dump's, and nothing of either is kept" $ withServedStore $ \_ store served _ _ -> do let dir = stDir store nar = regularNar "refers" dumped = regularNar "dumped" refusedReference = msgError ("path '" <> pathOnWire missingPath <> "' is not valid") case (narInfoOf nar [missingPath] Nothing, makeSourcePath "dumped" (sha256Digest dumped) (Set.singleton missingPath)) of (Just info, Right dumpedPath) -> do (_, reply) <- serveAdding served defaultNixConfig Proto.Trusted [narRequest importedPath info NoCheck <> framedIn 16 nar, dumpRequest "dumped" "fixed:r:sha256" [missingPath] <> framedIn 16 dumped] written <- traverse (Dir.doesPathExist . storePathToFilePath dir) [importedPath, dumpedPath] valid <- traverse (isValid store) [importedPath, dumpedPath] staged <- stagingLeft store pure $ assertEqual "refused" (refusedReference <> refusedReference) reply `andThen` assertEqual "written, valid" ([False, False], [False, False]) (written, valid) `andThen` assertEqual "staging left" [] staged other -> pure (Fail ("no info to send: " <> T.pack (show other))), runTestM "a derivation sent as a text whose output is not the path its inputs make is refused in upstream's words, and nothing of it is kept" $ withServedStore $ \_ store served _ _ -> case upstreamMade of Left err -> pure (Fail err) Right made -> case drvOutputs (drvFileDerivation made) of [out] -> do let dir = stDir store wrongOut = StorePath (T.replicate 32 "1") "d" wrongDrv = (drvFileDerivation made) {drvOutputs = [out {doPath = wrongOut}], drvEnv = Map.insert "out" (pathOnWire wrongOut) (drvEnv (drvFileDerivation made))} aterm = toATerm wrongDrv (_, reply) <- serveAdding served defaultNixConfig Proto.NotTrusted [dumpRequest "d.drv" "text:sha256" [] <> framedIn 7 aterm] left <- filter (".drv" `isSuffixOf`) <$> Dir.listDirectory (unStoreDir dir) staged <- stagingLeft store pure $ assertEqual "refused" (msgError ("derivation has incorrect output '" <> pathOnWire wrongOut <> "', should be '" <> pathOnWire (doPath out) <> "'")) reply `andThen` assertEqual "derivations, staging left" ([], []) (left, staged) outputs -> pure (Fail ("expected one output, got: " <> T.pack (show outputs))) ] where rootsListed = map (fmap Set.toList) . Map.toList-- | Paths the add tests import, and a path beside them that one links to.importedPath, signedPath, unsignedPath, mismatchPath, siblingPath :: StorePathimportedPath = StorePath "0000000000000000000000000000000f" "imported"signedPath = StorePath "0000000000000000000000000000000g" "signed"unsignedPath = StorePath "0000000000000000000000000000000h" "unsigned"mismatchPath = StorePath "0000000000000000000000000000000i" "mismatch"siblingPath = StorePath "0000000000000000000000000000000j" "dep"-- | The derivation upstream writes for-- @derivation { name = "d"; system = "x"; builder = "/bin/sh"; }@, whose-- path the evaluator's tests hold to upstream's: its file's contents and-- its path.upstreamDrv :: Either Text (BS.ByteString, StorePath)upstreamDrv = (\made -> (drvFileATerm made, drvFilePath made)) <$> upstreamMade-- | That derivation as made from its inputs.upstreamMade :: Either Text DrvFileupstreamMade = Bifunctor.first (T.pack . show) (inputAddressed "d" [] drv) where drv = Derivation { drvOutputs = [DerivationOutput "out" (StorePath (T.replicate 32 "0") "d") "" ""], drvInputDrvs = Map.empty, drvInputSrcs = [], drvPlatform = OtherPlatform "x", drvBuilder = "/bin/sh", drvArgs = [], drvEnv = Map.fromList [("builder", "/bin/sh"), ("name", "d"), ("system", "x")] }-- | The version an add test's client and the daemon agree, a client at-- 1.38 sending the features 'clientHello' sends.addVersion :: Proto.VersionaddVersion = Proto.Version Proto.latestVersionNumber (Set.fromList (map Proto.Feature serverFeatures))-- | Serve one connection over a served store, under the settings given,-- to a client at 1.38 sending the requests: how it ended, and what it was-- sent after the handshake.serveAdding :: ServedStore -> NixConfig -> Proto.Trust -> [BS.ByteString] -> IO (Conn.ConnectionEnd, BS.ByteString)serveAdding served config trust requests = do (transport, written) <- memoryTransport (clientHello 38 : requests) ended <- serveLocal served (servedConfig config) trust transport (,) ended . BS.drop (BS.length (serverHello 38 trust)) <$> written-- | A transport over a client's input, given in chunks, that once it has-- given them signals, then waits on the variable given, as one whose-- client went quiet mid-upload; what is sent to it is dropped.stallingTransport :: [BS.ByteString] -> IO () -> MVar () -> IO (Conn.Transport IO)stallingTransport input signal block = do pending <- newIORef (filter (not . BS.null) input) let receive = atomicModifyIORef' pending (\case [] -> ([], Nothing); chunk : rest -> (rest, Just chunk)) >>= \case Just chunk -> pure (Just chunk) Nothing -> signal >> takeMVar block >> pure Nothing pure (Conn.Transport receive (const (pure ())))-- | The staging directories a store holds, by name.stagingLeft :: Store -> IO [FilePath]stagingLeft store = filter ("tmp-" `isPrefixOf`) <$> Dir.listDirectory (unStoreDir (stDir store))-- | An operation's answer: its reply once its work ends, or the error that-- ended it, what it reports on the way passed over.answerOf :: Wire.Decoder a -> Wire.Decoder (Either Proto.DaemonError a)answerOf reply = Proto.getStderrMessage addVersion >>= \case Proto.StderrLast -> Right <$> reply Proto.StderrError err -> pure (Left err) _ -> answerOf reply-- | Bytes as an upload sends them: in frames of at most the size given,-- then the frame that ends the upload.framedIn :: Int -> BS.ByteString -> BS.ByteStringframedIn size bytes | BS.null bytes = frameEnd | otherwise = wframe (BS.take size bytes) <> framedIn size (BS.drop size bytes)-- | A dump's request, not repairing: its name, its method and algorithm,-- and the paths it refers to. The dump follows.dumpRequest :: BS.ByteString -> BS.ByteString -> [StorePath] -> BS.ByteStringdumpRequest name method refs = le64 7 <> wstr name <> wstr method <> wstrs (map pathOnWire refs) <> le64 0-- | Whether an import asks that its signatures be checked.data Checking = Check | NoCheck-- | An import of a path from its NAR, not repairing. The NAR follows.narRequest :: StorePath -> Proto.UnkeyedValidPathInfo -> Checking -> BS.ByteStringnarRequest path info checking = le64 39 <> addressedUploadInfo path info <> le64 0 <> le64 (case checking of Check -> 0; NoCheck -> 1)-- | A path's info as an upload sends it, its content address with it.addressedUploadInfo :: StorePath -> Proto.UnkeyedValidPathInfo -> BS.ByteStringaddressedUploadInfo path info = wstr (pathOnWire path) <> wstr (maybe "" pathOnWire (Proto.upiDeriver info)) <> wstr (TE.encodeUtf8 (Hash.bytesToHexText (Proto.narHashDigest (Proto.upiNarHash info)))) <> wstrs (map pathOnWire (Set.toAscList (Proto.upiReferences info))) <> le64 (fromIntegral (Proto.upiRegistrationTime info)) <> le64 (Proto.upiNarSize info) <> le64 (if Proto.upiUltimate info then 1 else 0) <> wstrs (map sigBytes (Set.toAscList (Proto.upiSignatures info))) <> wstr (maybe "" (TE.encodeUtf8 . Proto.renderContentAddress) (Proto.upiContentAddress info))-- | The info a NAR is sent with: its hash and size, the references and-- deriver given, unsigned, not ultimate, with no content address.narInfoOf :: BS.ByteString -> [StorePath] -> Maybe StorePath -> Maybe Proto.UnkeyedValidPathInfonarInfoOf nar references deriver = (\narHash -> Proto.UnkeyedValidPathInfo deriver narHash (Set.fromList references) 0 (fromIntegral (BS.length nar)) False Set.empty Nothing) <$> Proto.narHashFromDigest (sha256Digest nar)-- | The public key 'sigTestKeyText' makes, as @trusted-public-keys@-- spells it.testPublicKey :: Either String TexttestPublicKey = Signing.renderPublicKey <$> (Signing.parseSecretKey sigTestKeyText >>= Signing.toPublicKey)-- | A signature by 'sigTestKeyText' of a path's info: of the fingerprint-- upstream signs, its path under the logical store directory.signedFor :: StorePath -> Proto.UnkeyedValidPathInfo -> Either String Proto.SignaturesignedFor path info = do secretKey <- Signing.parseSecretKey sigTestKeyText sig <- Signing.sign secretKey fingerprinted either (Left . T.unpack) Right (Proto.parseSignature (TE.encodeUtf8 sig)) where fingerprinted = NarInfo.NarInfo { NarInfo.niStorePath = storePathToText defaultStoreDir path, NarInfo.niUrl = "", NarInfo.niCompression = "", NarInfo.niFileHash = Nothing, NarInfo.niFileSize = Nothing, NarInfo.niNarHash = Hash.formatNixHash (CHash.NixHash (Proto.narHashDigest (Proto.upiNarHash info))), NarInfo.niNarSize = toInteger (Proto.upiNarSize info), NarInfo.niReferences = map storePathBasename (Set.toAscList (Proto.upiReferences info)), NarInfo.niDeriver = Nothing, NarInfo.niSigs = [], NarInfo.niCA = Nothing }-- | The NAR of a regular file that is not executable.regularNar :: BS.ByteString -> BS.ByteStringregularNar contents = NAR.serialise (NAR.NarRegular False contents)-- | A text's content address.textAddress :: BS.ByteString -> Maybe Proto.ContentAddresstextAddress contents = Proto.contentAddressFromParts Proto.TextMethod "sha256" (sha256Digest contents)-- | What an add test holds a path's info to: the path, its NAR's hash and-- size, its references and its content address.data Added = Added !StorePath !(Maybe Proto.NarHash) !Word64 ![StorePath] !(Maybe Proto.ContentAddress) deriving (Eq, Show)-- | A path added from a NAR, with the references and the address given.addedFrom :: StorePath -> BS.ByteString -> [StorePath] -> Maybe Proto.ContentAddress -> AddedaddedFrom path nar = Added path (Proto.narHashFromDigest (sha256Digest nar)) (fromIntegral (BS.length nar))-- | An answered path's info, as an add test holds it.answeredAs :: Proto.ValidPathInfo -> AddedansweredAs (Proto.ValidPathInfo path info) = Added path (Just (Proto.upiNarHash info)) (Proto.upiNarSize info) (Set.toAscList (Proto.upiReferences info)) (Proto.upiContentAddress info)-- | A path's registration, as an add test holds it, if the path is valid.-- A reference the store spells as no path is left out, which a test sees-- as a reference missing.addedAs :: Store -> StorePath -> IO (Maybe Added)addedAs store path = do row <- queryPathInfo (stDB store) path references <- queryReferences (stDB store) path pure (registered references <$> row) where registered references row = Added path (either (const Nothing) (\(CHash.NixHash digest) -> Proto.narHashFromDigest digest) (CHash.parseNixHash (piNarHash row))) (fromIntegral (piNarSize row)) (mapMaybe (parseStorePath (stDir store)) references) (piContentAddress row)