{-# LANGUAGE LambdaCase #-}-- | Tests of fetched archives: the tar reader, the tar sink's rules, a-- tree's NAR, and @builtins.fetchTarball@ unpacking in process, each as-- upstream reads and places an archive's entries.module Test.Archive ( testTarReader, testTarSink, testArchiveProperties, testFetchTarballIO, )whereimport qualified Codec.Archive.Tar as Tarimport qualified Codec.Archive.Tar.Entry as TarEntryimport qualified Codec.Compression.GZip as GZipimport Control.Exception (evaluate)import Control.Monad (void)import Control.Monad.State.Strict (State, evalState, gets, modify, state)import Data.Bifunctor (second)import Data.ByteString (ByteString)import qualified Data.ByteString as BSimport qualified Data.ByteString.Char8 as BCimport qualified Data.ByteString.Lazy as BLimport qualified Data.ByteString.Unsafe as BSUimport Data.Char (toLower)import Data.IORef (atomicModifyIORef', newIORef)import Data.List (isPrefixOf)import qualified Data.Map.Strict as Mapimport Data.Text (Text)import qualified Data.Text as Timport Foreign.Ptr (minusPtr)import Nix.Eval.CanonPath (canonPathValue)import Nix.Fetch.Archive (ArchiveEntry (..), ArchiveNode (..), FetchFailure (..), drainFile, emptySink, finishSink, readArchive, sinkEntry, unpackArchive)import Nix.Fetch.Tar (TarFailure (..), TarStep (..), tarReader)import Nix.Fetch.Tree (Blob (..), NarPiece (..), Tree (..), blobFile, dereferenceSingleton, narPieces)import Nix.Hash (FileIngestionMethod (..), makeFixedOutputPath, sha256Digest)import Nix.Store.CaseSensitive (probeCaseSensitivity, volumeCaseHack)import qualified Nix.Store.ExecBit as ExecBitimport Nix.Store.Path (StoreDir (..), storePathToFilePath)import qualified NovaCache.Hash as Hashimport qualified NovaCache.NAR as NARimport qualified NovaCache.Zstd as Zstdimport Numeric (showOct)import System.Directory (createDirectoryIfMissing, getTemporaryDirectory)import System.FilePath ((</>))import System.Timeout (timeout)import Test.Harness (TestResult (..), allFailures, andThen, assertEqual, evalNixIOStore, fetchedStorePath, forceRemoveIfExists, runTest, runTestM)import qualified Test.QuickCheck as QC-- | A QuickCheck property as a test result.property :: (QC.Testable prop) => prop -> IO TestResultproperty 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)))-- ----------------------------------------------------------------------------- Driving the reader over bytes in memory-- ----------------------------------------------------------------------------- | Unpack an archive's bytes, fed in the chunks given, with each file's-- contents as its blob.unpackChunks :: [ByteString] -> ([Text], Either FetchFailure (Tree ByteString))unpackChunks chunks = evalState (readArchive pull store) (chunks, []) where pull :: State ([ByteString], [ByteString]) (Either Text ByteString) pull = state $ \(remaining, held) -> case remaining of chunk : rest -> (Right chunk, (rest, held)) [] -> (Right BS.empty, ([], held)) store _ _ contents = do modify (\(remaining, _) -> (remaining, [])) after <- drainFile pull (modify . second . (:)) contents held <- gets snd pure ((,) (BS.concat (reverse held)) <$> after)-- | Unpack an archive's bytes in one chunk.unpackBytes :: BL.ByteString -> ([Text], Either FetchFailure (Tree ByteString))unpackBytes = unpackChunks . BL.toChunks-- | The tree an archive unpacks to, or why it does not.treeOf :: BL.ByteString -> Either FetchFailure (Tree ByteString)treeOf = snd . unpackBytes-- | An archive the tar package writes, long names and link targets as GNU-- entries.archiveOf :: [Tar.GenEntry BL.ByteString FilePath FilePath] -> BL.ByteStringarchiveOf = Tar.write . concatMap Tar.encodeLongNamesfile :: FilePath -> BL.ByteString -> Tar.GenEntry BL.ByteString FilePath FilePathfile = TarEntry.fileEntryexecutable :: FilePath -> BL.ByteString -> Tar.GenEntry BL.ByteString FilePath FilePathexecutable path contents = (TarEntry.fileEntry path contents) {TarEntry.entryPermissions = TarEntry.executableFilePermissions}directory :: FilePath -> Tar.GenEntry BL.ByteString FilePath FilePathdirectory = TarEntry.directoryEntrysymlink :: FilePath -> FilePath -> Tar.GenEntry BL.ByteString FilePath FilePathsymlink path target = TarEntry.simpleEntry path (Tar.SymbolicLink target)hardLink :: FilePath -> FilePath -> Tar.GenEntry BL.ByteString FilePath FilePathhardLink path target = TarEntry.simpleEntry path (Tar.HardLink target)-- | An entry of another type, with its body, as a pax or global header is.special :: Char -> FilePath -> BL.ByteString -> Tar.GenEntry BL.ByteString FilePath FilePathspecial flag path body = TarEntry.simpleEntry path (Tar.OtherEntryType flag body (BL.length body))-- | A pax body of records, each with its length counted as pax counts it:-- the digits of the length are part of the record.paxBody :: [(ByteString, ByteString)] -> BL.ByteStringpaxBody = BL.fromStrict . BS.concat . map record where record (key, value) = let rest = " " <> key <> "=" <> value <> "\n" in BC.pack (show (recordLength (BS.length rest))) <> rest recordLength restLength = let guess = restLength + digits restLength in if digits guess == digits restLength then guess else guess + 1 digits = length . show-- | A directory of entries.dir :: [(ByteString, Tree blob)] -> Tree blobdir = TreeDirectory . Map.fromList-- ----------------------------------------------------------------------------- Archives written by hand-- ----------------------------------------------------------------------------- | The magic a hand-written header carries: POSIX's, GNU's, POSIX's with-- a version that is not its own, or none.data Magic = MagicUstar | MagicGnu | MagicOddVersion | MagicNone-- | The bytes of a block that a header's size does not fill, to the width.padTo :: Int -> ByteString -> ByteStringpadTo width bytes = BS.take width bytes <> BS.replicate (width - BS.length bytes) 0-- | A number as the octal field of the width holds one.octal :: Int -> Int -> ByteStringoctal width number = BC.pack (replicate (width - 1 - length digits) '0' <> digits) <> BS.singleton 0 where digits = showOct number ""-- | A header block with its checksum filled in: its type flag, name, size-- and link target.headerBlock :: Magic -> Char -> ByteString -> Int -> ByteString -> ByteStringheaderBlock magic flag name size link = withChecksum (padTo 512 unsummed) where unsummed = BS.concat [ padTo 100 name, "0000644\0", "0000000\0", "0000000\0", octal 12 size, octal 12 0, BC.replicate 8 ' ', BC.singleton flag, padTo 100 link, stamp ] stamp = case magic of MagicUstar -> "ustar\0" <> "00" MagicGnu -> "ustar " <> " \0" MagicOddVersion -> "ustar\0" <> "01" MagicNone -> BS.replicate 8 0-- | A header block whose checksum field, spaces until now, holds the sum-- of the block's bytes.withChecksum :: ByteString -> ByteStringwithChecksum block = BS.take 148 block <> checksum <> BS.drop 156 block where checksum = BC.pack (replicate (6 - length digits) '0' <> digits) <> "\0 " digits = showOct (BS.foldl' (\total byte -> total + fromIntegral byte) (0 :: Int) block) ""-- | A body padded to whole blocks.blocks :: ByteString -> ByteStringblocks body = body <> BS.replicate (negate (BS.length body) `mod` 512) 0-- | A member: its header, with the size of the body, and the body.member :: Magic -> Char -> ByteString -> ByteString -> ByteString -> ByteStringmember magic flag name link body = headerBlock magic flag name (BS.length body) link <> blocks body-- | A GNU long link header holding a target.longLink :: ByteString -> ByteStringlongLink target = member MagicGnu 'K' "././@LongLink" "" (target <> "\0")-- | The two blocks that end an archive.endMark :: ByteStringendMark = BS.replicate 1024 0-- | A pax body, as strict bytes.paxBytes :: [(ByteString, ByteString)] -> ByteStringpaxBytes = BL.toStrict . paxBody-- | An archive's bytes unpacked in one chunk.unpackRaw :: ByteString -> ([Text], Either FetchFailure (Tree ByteString))unpackRaw bytes = unpackChunks [bytes]-- | What an archive's bytes refuse with, or the tree.treeOfRaw :: ByteString -> Either Text (Tree ByteString)treeOfRaw = either (Left . fetchMessage) Right . snd . unpackRaw-- | What the reader is doing once chunks are fed: waiting for the next, stopped,-- or going on with an entry.data Standing = Waiting | Stopped TarFailure | Moving deriving (Eq, Show)standingAfter :: [ByteString] -> StandingstandingAfter = go tarReader where go step chunks = case step of TarAwait continue -> case chunks of [] -> Waiting chunk : rest -> go (continue chunk) rest TarFail failure -> Stopped failure _ -> Moving-- | Every name and link target a tree holds.namesIn :: Tree blob -> [ByteString]namesIn tree = case tree of TreeDirectory entries -> concatMap (\(name, sub) -> name : namesIn sub) (Map.toList entries) TreeSymlink target -> [target] TreeFile _ _ -> []-- | Whether a name's bytes are a slice of a chunk's memory.withinChunk :: ByteString -> ByteString -> IO BoolwithinChunk chunk name = BSU.unsafeUseAsCStringLen chunk $ \(chunkStart, chunkLength) -> BSU.unsafeUseAsCStringLen name $ \(nameStart, _) -> let offset = nameStart `minusPtr` chunkStart in pure (offset >= 0 && offset < chunkLength)-- ----------------------------------------------------------------------------- The reader-- ----------------------------------------------------------------------------- | The tar formats libarchive reads, and its refusals.testTarReader :: IO [Bool]testTarReader = do putStrLn "fetch/tar-reader" sequence [ runTest "a ustar archive's files, directories and links unpack" $ assertEqual "tree" (Right (dir [("a", TreeFile False "one"), ("bin", dir [("run", TreeFile True "#!")]), ("empty", dir []), ("link", TreeSymlink "a")])) (treeOf (archiveOf [file "top/a" "one", directory "top/bin", executable "top/bin/run" "#!", symlink "top/link" "a", directory "top/empty"])), runTest "a long name is a GNU long name, and a long path a ustar prefix" $ let long = replicate 120 'n' deep = replicate 60 'd' <> "/" <> replicate 60 'e' <> "/f" in assertEqual "tree" (Right (dir [(BC.pack long, TreeFile False "long"), (BC.pack (replicate 60 'd'), dir [(BC.pack (replicate 60 'e'), dir [("f", TreeFile False "deep")])]), ("t", TreeSymlink (BC.pack (replicate 150 't')))])) (treeOf (archiveOf [file long "long", file deep "deep", symlink "t" (replicate 150 't')])), runTest "a pax header names the path of the entry after it" $ assertEqual "tree" (Right (dir [("named by pax", TreeFile False "pax"), ("other", TreeFile False "o")])) (treeOf (archiveOf [special 'x' "PaxHeader" (paxBody [("path", "named by pax"), ("mtime", "1234567.5")]), file "ignored" "pax", file "other" "o"])), runTest "a pax header's size is the entry's size" $ assertEqual "tree" (Right (dir [("f", TreeFile False "abc"), ("g", TreeFile False "y")])) (treeOfRaw (member MagicUstar 'x' "PaxHeader" "" (paxBytes [("size", "3")]) <> headerBlock MagicUstar '0' "f" 0 "" <> blocks "abc" <> member MagicUstar '0' "g" "" "y" <> endMark)), runTest "a pax global header is passed over, as GitHub's archives carry one" $ assertEqual "tree" (Right (dir [("f", TreeFile False "x")])) (treeOf (archiveOf [special 'g' "pax_global_header" (paxBody [("comment", "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed")]), directory "repo", file "repo/f" "x"])), runTest "a pax global header that sets what an entry would be is refused" $ let refusedKey key = assertEqual (T.pack (BC.unpack key)) (Left ("cannot get archive member name: Unsupported pax global extended header attribute '" <> T.pack (BC.unpack key) <> "'")) (treeOfRaw (member MagicUstar 'g' "pax_global_header" "" (paxBytes [("comment", "c"), (key, "v")]) <> member MagicUstar '0' "f" "" "x" <> endMark)) in allFailures (map refusedKey ["path", "linkpath", "size", "mtime", "atime", "ctime", "uid", "gid", "uname", "gname", "hdrcharset", "GNU.sparse", "GNU.sparse.major", "LIBARCHIVE.creationtime", "LIBARCHIVE.xattr.user.k", "SCHILY.xattr.user.k", "SCHILY.realsize", "SUN.holesdata"]), runTest "a pax global header of other attributes is accepted" $ let acceptedKey key = assertEqual (T.pack (BC.unpack key)) (Right (dir [("f", TreeFile False "x")])) (treeOfRaw (member MagicUstar 'g' "pax_global_header" "" (paxBytes [(key, "v")]) <> member MagicUstar '0' "f" "" "x" <> endMark)) in allFailures (map acceptedKey ["comment", "SCHILY.xattr", "LIBARCHIVE.other", "vendor.key"]), runTest "an empty pax global header is refused" $ assertEqual "refused" (Left "cannot get archive member name: Invalid empty pax global extended header") (treeOfRaw (member MagicUstar 'g' "pax_global_header" "" "" <> member MagicUstar '0' "f" "" "x" <> endMark)), runTest "a malformed record in a pax global header warns, naming the entry after it" $ assertEqual "unpacked" (["getting archive member 'f': Ignoring malformed pax attributes: malformed attribute size field"], Right (dir [("f", TreeFile False "x")])) (unpackRaw (member MagicUstar 'g' "pax_global_header" "" "x9 comment=c\n" <> member MagicUstar '0' "f" "" "x" <> endMark)), runTest "a pax body is read as it arrives, so a refused global attribute stops the reader before the rest of the body" $ let body = paxBytes [("path", "x"), ("comment", BC.replicate 1990 'c')] refusal = TarHeaderFailure Nothing "Unsupported pax global extended header attribute 'path'" in assertEqual "standing" (Stopped refusal) (standingAfter [headerBlock MagicUstar 'g' "pax_global_header" (BS.length body) "", BS.take 700 body]), runTest "a malformed pax record warns, naming the member, and is ignored" $ assertEqual "unpacked" (["getting archive member 'f': Ignoring malformed pax attributes: malformed attribute size field"], Right (dir [("f", TreeFile False "x"), ("g", TreeFile False "y")])) (unpackBytes (archiveOf [special 'x' "PaxHeader" "x9 path=no\n", file "f" "x", file "g" "y"])), runTest "a malformed pax record drops the names before it" $ assertEqual "unpacked" (["getting archive member 'f': Ignoring malformed pax attributes: malformed attribute size field"], Right (dir [("f", TreeFile False "x")])) (unpackRaw (member MagicUstar 'x' "PaxHeader" "" (paxBytes [("path", "named")] <> "x9 comment=c\n") <> member MagicUstar '0' "f" "" "x" <> endMark)), runTest "a pax value is applied before its record's newline is checked" $ assertEqual "unpacked" (["getting archive member 'f': Malformed pax attributes"], Right (dir [("f", TreeFile False "abc"), ("g", TreeFile False "y")])) (unpackRaw (member MagicUstar 'x' "PaxHeader" "" "9 size=3X" <> headerBlock MagicUstar '0' "f" 0 "" <> blocks "abc" <> member MagicUstar '0' "g" "" "y" <> endMark)), runTest "a pax path past a mebibyte is not applied" $ let (warnings, tree) = unpackRaw (member MagicUstar 'x' "PaxHeader" "" (paxBytes [("path", BC.replicate 1048577 'p')]) <> member MagicUstar '0' "f" "" "x" <> endMark) in assertEqual "unpacked" (1, Right (dir [("f", TreeFile False "x")])) (length warnings, tree), runTest "a hard link entry names its target" $ assertEqual "tree" (Right (dir [("a", TreeFile False "same"), ("b", TreeFile False "same")])) (treeOf (archiveOf [file "a" "same", hardLink "b" "a"])), runTest "a ustar hard link keeps no body, whatever size its header holds" $ assertEqual "tree" (Right (dir [("a", TreeFile False "same"), ("l", TreeFile False "same")])) (treeOfRaw (member MagicUstar '0' "a" "" "same" <> headerBlock MagicUstar '1' "l" 512 "a")), runTest "a hard link whose header the bidder does not take keeps its body" $ assertEqual "tree" (Right (dir [("a", TreeFile False "same"), ("b", TreeFile False "b"), ("l", TreeFile False "same")])) (treeOfRaw (member MagicUstar '0' "a" "" "same" <> headerBlock MagicOddVersion '1' "l" 512 "a" <> BS.replicate 512 0x7a <> member MagicUstar '0' "b" "" "b" <> endMark)), runTest "a link a GNU long link header gives is a hard link on a regular entry" $ assertEqual "tree" (Right (dir [("a", TreeFile False "same"), ("b", TreeFile False "same")])) (treeOfRaw (member MagicGnu '0' "a" "" "same" <> longLink "a" <> member MagicGnu '0' "b" "" "" <> endMark)), runTest "a pax linkpath is a hard link on a directory entry" $ assertEqual "tree" (Right (dir [("a", TreeFile False "same"), ("d", TreeFile False "same")])) (treeOfRaw (member MagicUstar '0' "a" "" "same" <> member MagicUstar 'x' "PaxHeader" "" (paxBytes [("linkpath", "a")]) <> member MagicUstar '5' "d/" "" "" <> endMark)), runTest "a GNU long link header gives a symlink its target" $ assertEqual "tree" (Right (dir [("s", TreeSymlink (BC.replicate 150 't'))])) (treeOfRaw (longLink (BC.replicate 150 't') <> member MagicGnu '2' "s" "" "" <> endMark)), runTest "a long link header past a mebibyte gives no link, with a warning" $ assertEqual "unpacked" (["getting archive member 'f': Special header too large: 1048577 > 1MiB"], Right (dir [("f", TreeFile False "x")])) (unpackRaw (member MagicGnu 'K' "././@LongLink" "" (BC.replicate 1048577 'k') <> member MagicGnu '0' "f" "" "x" <> endMark)), runTest "a regular entry whose name ends in a slash is a directory" $ assertEqual "tree" (Right (dir [("d", dir [("f", TreeFile False "x")]), ("g", TreeFile False "y")])) (treeOf (archiveOf [(file "d/" "") {TarEntry.entryTarPath = "d/"}, file "d/f" "x", file "g" "y"])), runTest "an empty input is an empty archive" $ assertEqual "unpacked" ([], Right (dir [])) (unpackBytes BL.empty), runTest "bytes that are not an archive are refused as libarchive refuses them" $ assertEqual "refused" (Left "Failed to open archive (Unrecognized archive format)") (treeOfRaw "this is not a tar archive"), runTest "a page of markup is refused as no archive, not as a damaged one" $ assertEqual "refused" (Left "Failed to open archive (Unrecognized archive format)") (treeOfRaw (BC.replicate 600 '<')), runTest "a damaged header after the first is refused" $ let archive = archiveOf [file "a" "x", file "b" "y"] damaged = BL.take 1024 archive <> BL.map (const 0x41) (BL.take 512 (BL.drop 1024 archive)) <> BL.drop 1536 archive in assertEqual "refused" (Left "cannot get archive member name: Damaged tar archive (bad header checksum)") (failureOf (treeOf damaged)), runTest "an archive that ends inside a file is refused" $ assertEqual "refused" (Left "cannot read file from tarball: Truncated tar archive detected while reading data") (failureOf (treeOf (BL.take 600 (archiveOf [file "a" (BL.replicate 1000 0x61)])))), runTest "an archive that ends in a file's padding is refused with the bytes it lacked" $ assertEqual "refused" (Left "cannot read file from tarball: Truncated input file (needed 412 bytes, only 0 available)") (failureOf (treeOf (BL.take 612 (archiveOf [file "a" (BL.replicate 100 0x61)])))), runTest "an archive that ends in a skipped body is refused with the bytes it lacked" $ assertEqual "refused" (Left "cannot get archive member name: Truncated input file (needed 512 bytes, only 50 available)") (treeOfRaw (headerBlock MagicGnu 'D' "d/" 100 "" <> BS.replicate 50 0x78)), runTest "an archive that ends in a long name's padding is refused with the bytes it lacked" $ assertEqual "refused" (Left "failed to extract archive (Truncated input file (needed 512 bytes, only 10 available))") (treeOfRaw (headerBlock MagicGnu 'L' "././@LongLink" 10 "" <> "long-name\0")), runTest "every chunking of an archive reads the same" $ let archive = BL.toStrict (archiveOf [file "a" (BL.replicate 700 0x61), symlink "l" "a", directory "d", file "d/b" "b"]) whole = snd (unpackChunks [archive]) byteWise = snd (unpackChunks (map BS.singleton (BS.unpack archive))) in assertEqual "unpacked" whole byteWise, runTest "every chunking of an archive of pax and GNU headers reads the same" $ let archive = BS.concat [ member MagicUstar 'g' "pax_global_header" "" (paxBytes [("comment", "c")]), member MagicUstar 'x' "PaxHeader" "" (paxBytes [("path", "named by pax"), ("comment", BC.replicate 600 'c'), ("size", "4")]), headerBlock MagicUstar '0' "ignored" 0 "" <> blocks "data", longLink "named by pax", member MagicGnu '0' "hard" "" "", endMark ] whole = snd (unpackChunks [archive]) byteWise = snd (unpackChunks (map BS.singleton (BS.unpack archive))) in assertEqual "unpacked" (Right (dir [("hard", TreeFile False "data"), ("named by pax", TreeFile False "data")])) whole `andThen` assertEqual "chunked" whole byteWise, runTestM "entry names and link targets are copies, so none keeps its chunk alive" $ let archive = BL.toStrict (archiveOf [directory "top", file "top/a" "x", file ("top/" <> replicate 120 'n') "y", symlink "top/s" (replicate 150 't'), hardLink "top/h" "top/a"]) in case snd (unpackChunks [archive]) of Left failure -> pure (Fail (fetchMessage failure)) Right tree -> do inside <- mapM (withinChunk archive) (namesIn tree) pure (assertEqual "names read" 5 (length inside) `andThen` assertEqual "names inside the chunk" (replicate 5 False) inside) ] where failureOf = either (Left . fetchMessage) (const (Right ()))-- ----------------------------------------------------------------------------- The sink-- ----------------------------------------------------------------------------- | Place entries in order, as the sink places them.placed :: [ArchiveEntry Text] -> ([Text], Either FetchFailure (Tree Text))placed = go [] emptySink where go warnings sink entries = case entries of [] -> (warnings, finishSink sink) entry : rest -> case sinkEntry sink entry of (Left failure, given) -> (warnings ++ given, Left failure) (Right updated, given) -> go (warnings ++ given) updated restat :: ByteString -> ArchiveNode Text -> ArchiveEntry Textat = ArchiveEntry-- | The rules of upstream's tar sink.testTarSink :: IO [Bool]testTarSink = do putStrLn "fetch/tar-sink" sequence [ runTest "the last entry at a path wins" $ assertEqual "tree" (Right (dir [("a", TreeFile False "second"), ("b", TreeFile False "b")])) (treeIn [at "a" (ArchiveFile False "first"), at "a" (ArchiveFile False "second"), at "b" (ArchiveFile False "b")]), runTest "a directory onto a directory changes nothing" $ assertEqual "tree" (Right (dir [("d", dir [("f", TreeFile False "x")]), ("e", dir [])])) (treeIn [at "d" ArchiveDirectory, at "d/f" (ArchiveFile False "x"), at "d" ArchiveDirectory, at "e" ArchiveDirectory]), runTest "a non-empty directory is not replaced" $ assertEqual "refused" (Left (FetchFailure [] "cannot create '/d', conflicting non-empty directory")) (treeIn [at "d/f" (ArchiveFile False "x"), at "d" (ArchiveFile False "y")]), runTest "an empty directory is replaced" $ assertEqual "tree" (Right (dir [("d", TreeFile False "y"), ("e", dir [])])) (treeIn [at "d" ArchiveDirectory, at "d" (ArchiveFile False "y"), at "e" ArchiveDirectory]), runTest "an entry under a file is refused" $ assertEqual "refused" (Left (FetchFailure [] "parent of '/a/b' is not a directory")) (treeIn [at "a" (ArchiveFile False "x"), at "a/b" (ArchiveFile False "y")]), runTest "a path is read as CanonPath reads it" $ assertEqual "tree" (Right (dir [("b", TreeFile False "x"), ("c", TreeFile False "y")])) (treeIn [at "./a/../b" (ArchiveFile False "x"), at "/c//" (ArchiveFile False "y")]), runTest "a hard link made before its target is replaced keeps what the target was, with a warning" $ assertEqual "placed" ( [ "'/t' is replaced, though a hard link makes it the same file as '/l'. Older versions of Nix resolved hard links differently, so this archive unpacks to a different store path than it used to." ], Right (dir [("l", TreeFile False "old"), ("t", TreeFile False "new")]) ) (placed [at "t" (ArchiveFile False "old"), at "l" (ArchiveHardLink "t"), at "t" (ArchiveFile False "new")]), runTest "a hard link made after its target is replaced names what replaced it" $ assertEqual "placed" ([], Right (dir [("l", TreeFile False "new"), ("t", TreeFile False "new")])) (placed [at "t" (ArchiveFile False "old"), at "t" (ArchiveFile False "new"), at "l" (ArchiveHardLink "t")]), runTest "replacing one of three linked paths names the other two" $ assertEqual "warnings" ["'/b' is replaced, though a hard link makes it the same file as '/a', '/c'. Older versions of Nix resolved hard links differently, so this archive unpacks to a different store path than it used to."] (fst (placed [at "a" (ArchiveFile False "x"), at "b" (ArchiveHardLink "a"), at "c" (ArchiveHardLink "a"), at "b" (ArchiveFile False "y")])), runTest "a hard link to nothing is refused, naming the link" $ assertEqual "refused" (Left (FetchFailure ["while creating a hard link from '/l' to '/x'"] "target does not exist")) (treeIn [at "l" (ArchiveHardLink "x")]), runTest "a hard link to a directory is refused" $ assertEqual "refused" (Left (FetchFailure ["while creating a hard link from '/l' to '/d'"] "target is a directory")) (treeIn [at "d" ArchiveDirectory, at "l" (ArchiveHardLink "d")]), runTest "a device is refused by its file type" $ assertEqual "refused" (Left (FetchFailure [] "file 'top/dev' in tarball has unsupported file type 8192")) (treeIn [at "top/dev" (ArchiveSpecial 8192)]), runTest "one top-level directory is the tree" $ assertEqual "tree" (Right (dir [("f", TreeFile False "x")])) (treeIn [at "pkg/f" (ArchiveFile False "x")]), runTest "two top-level directories are kept" $ assertEqual "tree" (Right (dir [("a", dir [("f", TreeFile False "x")]), ("b", dir [("g", TreeFile False "y")])])) (treeIn [at "a/f" (ArchiveFile False "x"), at "b/g" (ArchiveFile False "y")]), runTest "one top-level file is kept under the root" $ assertEqual "tree" (Right (dir [("f", TreeFile False "x")])) (treeIn [at "f" (ArchiveFile False "x")]), runTest "a root replaced by a file is refused" $ assertEqual "refused" (Left (FetchFailure [] "the archive's root is not a directory")) (treeIn [at "." (ArchiveFile False "x")]), runTest "a name upstream's tree builder refuses is refused, at any depth" $ let refusedName name = assertEqual (T.pack (BC.unpack name)) (Left (treeBuilderRefusal name)) (treeIn [at ("top/" <> name <> "/f") (ArchiveFile False "x")]) in allFailures (map refusedName [".git", ".GIT", ".Git", "git~1", "GIT~1", ".git ", ".git.", ".git . .", ".git:stream", ".git\\x"]) `andThen` assertEqual "deep" (Left (treeBuilderRefusal ".git")) (treeIn [at "top/a/b/c/.git" (ArchiveFile False "x"), at "top/a/b/other" (ArchiveFile False "y")]), runTest "a name that only resembles one is kept" $ let keptName name = assertEqual (T.pack (BC.unpack name)) (Right (dir [(name, TreeFile False "x")])) (treeIn [at name (ArchiveFile False "x")]) in allFailures (map keptName [".gitignore", ".github", ".gitmodules", "git~", "git~0", "git~2", "x.git", ".gi", "git", "git~1x", ".git x", "..git"]), runTest "the first refusal is the one a depth-first write in name order meets, a name after what it holds" $ assertEqual "first" (Left (treeBuilderRefusal ".git")) (treeIn [at "GIT~1/.git" (ArchiveFile False "x"), at "a/.GIT" (ArchiveFile False "y")]) `andThen` assertEqual "sorted" (Left (treeBuilderRefusal ".GIT")) (treeIn [at "a/.git" (ArchiveFile False "x"), at ".GIT" (ArchiveFile False "y")]), runTest "an archive holding such a name is refused" $ assertEqual "refused" (Left (fetchMessage (treeBuilderRefusal ".git"))) (either (Left . fetchMessage) Right (treeOf (archiveOf [directory "pkg", directory "pkg/.git", file "pkg/.git/config" "x"]))) ] where treeIn = snd . placed-- | Upstream's refusal of a name its tree builder will not hold.treeBuilderRefusal :: ByteString -> FetchFailuretreeBuilderRefusal name = FetchFailure [] ("adding '" <> shown <> "' to a tree builder: failed to insert entry: invalid name for a tree entry - " <> shown <> " (libgit2 error code = 14)") where shown = T.pack (BC.unpack name)-- ----------------------------------------------------------------------------- Properties-- ----------------------------------------------------------------------------- | A tree's NAR, from its pieces with each blob its own bytes.narOfPieces :: Tree ByteString -> ByteStringnarOfPieces tree = BS.concat (map piece (narPieces (fromIntegral . BS.length) tree)) where piece p = case p of NarBytes bytes -> bytes NarContents _ contents -> contents-- | A tree as nova-cache's NAR holds one.narEntryOf :: Tree ByteString -> NAR.NarEntrynarEntryOf tree = case tree of TreeFile isExecutable contents -> NAR.NarRegular isExecutable contents TreeSymlink target -> NAR.NarSymlink target TreeDirectory entries -> NAR.NarDirectory (Map.toList (Map.map narEntryOf entries))-- | A tree whose directories each hold something, its names from the-- characters a ustar name holds, some long enough to need a prefix or a-- GNU long name.genTree :: Int -> QC.Gen (Tree ByteString)genTree depth = dir <$> QC.listOf1 ((,) <$> genName <*> genNode) where genNode = QC.frequency [ (4, TreeFile <$> QC.arbitrary <*> (BS.pack <$> QC.resize 1200 (QC.listOf QC.arbitrary))), (1, TreeSymlink . BC.pack <$> QC.listOf1 (QC.elements nameChars)), (if depth > 0 then 2 else 0, genTree (depth - 1)) ] genName = QC.oneof [short, long] short = BC.pack <$> QC.resize 12 (QC.listOf1 (QC.elements nameChars)) `QC.suchThat` (\name -> name `notElem` [".", ".."] && not (".git" `isPrefixOf` map toLower name)) long = BC.pack <$> (QC.choose (90, 130) >>= (`QC.vectorOf` QC.elements nameChars)) nameChars = ['a' .. 'z'] ++ ['A' .. 'Z'] ++ ['0' .. '9'] ++ "._-"-- | A tree's entries in the order a writer lists them, a directory before-- what it holds. Paths join with a slash on every platform: the tar-- package writes a GNU long name as it is given, so a native separator-- would reach the archive on Windows.entriesOf :: Tree ByteString -> [Tar.GenEntry BL.ByteString FilePath FilePath]entriesOf = go "" where go prefix node = case node of TreeDirectory entries -> concatMap (\(name, sub) -> visit (joined prefix (BC.unpack name)) sub) (Map.toList entries) _ -> [] visit path node = case node of TreeFile isExecutable contents -> [(if isExecutable then executable else file) path (BL.fromStrict contents)] TreeSymlink target -> [symlink path (BC.unpack target)] TreeDirectory _ -> directory path : go path node joined prefix name = if null prefix then name else prefix <> "/" <> name-- | Entries this many make one run of structural NAR bytes.largeRunEntries :: IntlargeRunEntries = 100000-- | The longest a large run may take to join: far past a linear join and-- far under a quadratic one.largeRunMicroseconds :: IntlargeRunMicroseconds = 10 * 1000000-- | The reader and the sink unpack an archive written from a tree to that-- tree, however it is chunked; a tree's NAR pieces are its NAR, and a-- directory of very many entries joins its structural bytes in one run.testArchiveProperties :: IO [Bool]testArchiveProperties = do putStrLn "fetch/archive-properties" unpacks <- property $ QC.forAll (genTree 2) $ \tree -> QC.forAll (QC.listOf1 (QC.choose (1, 2000))) $ \sizes -> let archive = BL.toStrict (archiveOf (entriesOf tree)) in snd (unpackChunks (chunked sizes archive)) == Right (dereferenceSingleton tree) pieces <- property (QC.forAll (genTree 2) (\tree -> narOfPieces tree == NAR.serialise (narEntryOf tree))) let largeRun = dir [(BC.pack (show index), TreeSymlink "t") | index <- [1 .. largeRunEntries]] joined <- timeout largeRunMicroseconds (evaluate (case narPieces (fromIntegral . BS.length) largeRun of [NarBytes bytes] -> BS.length bytes; other -> negate (length other))) sequence [ runTest "an archive written from a tree unpacks to that tree" unpacks, runTest "a tree's NAR pieces are its NAR" pieces, runTest "a directory of very many entries is one piece, joined in time" $ assertEqual "joined" (Just (BS.length (NAR.serialise (narEntryOf largeRun)))) joined ] where chunked sizes = go (cycle sizes) where go sizesLeft remaining | BS.null remaining = [] | otherwise = case sizesLeft of size : more -> BS.take size remaining : go more (BS.drop size remaining) [] -> [remaining]-- ----------------------------------------------------------------------------- fetchTarball-- ----------------------------------------------------------------------------- | @builtins.fetchTarball@ unpacks in process, as upstream does: the-- tree is the archive's own, its path the one its NAR gives, and a pair-- of names a volume folds keeps both names. An unpacked archive's files-- are numbered blobs under the scratch directory.testFetchTarballIO :: IO [Bool]testFetchTarballIO = do putStrLn "fetch/fetch-tarball-io" tmpBase <- getTemporaryDirectory let root = tmpBase </> "nova-nix-test-fetch-tarball" storeDir = StoreDir (root </> "store") pathText = canonPathValue . T.pack fileUrl path = "file://" <> pathText path fetchOf path = "builtins.fetchTarball \"" <> T.concatMap nixEscaped (fileUrl path) <> "\"" nixEscaped c = if c == '"' || c == '\\' then T.pack ['\\', c] else T.singleton c write name = BL.writeFile (root </> name) expectedPath tree = either (const Nothing) Just (makeFixedOutputPath "source" "sha256" NarIngestion (sha256Digest (NAR.serialise (narEntryOf tree)))) fetchedAs tree name = do fetched <- evalNixIOStore storeDir root (fetchOf (root </> name)) pure $ case fetched of Right val -> assertEqual "path" (expectedPath tree) (fetchedStorePath val) Left err -> Fail err refusedAs message expr = do fetched <- evalNixIOStore storeDir root expr pure (assertEqual "refused" (Left message) (void fetched)) twoTops = dir [("a", dir [("f", TreeFile False "f\n")]), ("b", dir [("g", TreeFile False "g\n")])] folded = dir [("Makefile", TreeFile False "upper\n"), ("makefile", TreeFile False "lower\n"), ("run", TreeFile True "#!/bin/sh\n")] forceRemoveIfExists root createDirectoryIfMissing True (root </> "plain-directory") write "two.tar.gz" (GZip.compress (archiveOf [directory "a", file "a/f" "f\n", directory "b", file "b/g" "g\n"])) write "dotgit.tar" (archiveOf [directory "pkg", directory "pkg/.git", file "pkg/.git/config" "x\n"]) write "folded.tar" (archiveOf [directory "pkg", file "pkg/Makefile" "upper\n", file "pkg/makefile" "lower\n", executable "pkg/run" "#!/bin/sh\n"]) write "folded.tar.zst" (BL.fromStrict (Zstd.compress Zstd.defaultCompressionLevel (BL.toStrict (archiveOf [directory "pkg", file "pkg/Makefile" "upper\n", file "pkg/makefile" "lower\n", executable "pkg/run" "#!/bin/sh\n"])))) results <- sequence [ runTestM "a tarball with two top-level directories keeps both" (fetchedAs twoTops "two.tar.gz"), runTestM "a zstd tarball unpacks to the same tree as a plain one" $ andThen <$> fetchedAs folded "folded.tar" <*> fetchedAs folded "folded.tar.zst", runTestM "a pair of names the store's volume folds keeps both names" $ do fetched <- evalNixIOStore storeDir root (fetchOf (root </> "folded.tar")) case fetched >>= maybe (Left "not a store path") Right . fetchedStorePath of Left err -> pure (Fail err) Right sp -> do let dest = storePathToFilePath storeDir sp sensitivity <- probeCaseSensitivity (unStoreDir storeDir) Hash.NixHash onDisk <- ExecBit.narHashOfPath (volumeCaseHack sensitivity) dest pure (assertEqual "NAR on disk" (sha256Digest (NAR.serialise (narEntryOf folded))) onDisk), runTestM "a tarball that is not there is refused in upstream's words" $ refusedAs ("tarball \"" <> pathText (root </> "absent.tar.gz") <> "\" does not exist.") (fetchOf (root </> "absent.tar.gz")), runTestM "a directory is refused as no tarball" $ refusedAs ("tarball \"" <> pathText (root </> "plain-directory") <> "\" is a directory, not a file.") (fetchOf (root </> "plain-directory")), runTestM "a tarball holding a name upstream's tree builder refuses is refused in its words" $ refusedAs (fetchMessage (treeBuilderRefusal ".git")) (fetchOf (root </> "dotgit.tar")), runTestM "an unpacked archive's files are numbered blobs under the scratch directory" $ do let scratch = root </> "scratch" createDirectoryIfMissing True scratch source <- chunkSource (BL.toChunks (GZip.compress (archiveOf [directory "pkg", file "pkg/a" "first", file "pkg/b" "second", symlink "pkg/l" "a"]))) (warnings, unpacked) <- unpackArchive scratch source case unpacked of Left failure -> pure (Fail (fetchMessage failure)) Right tree -> do contents <- readBlobs scratch tree pure (assertEqual "unpacked" ([], [0, 1], dir [("a", TreeFile False "first"), ("b", TreeFile False "second"), ("l", TreeSymlink "a")]) (warnings, blobNumbers tree, contents)) ] forceRemoveIfExists root pure results-- | A pull source that gives the chunks in order, then the end.chunkSource :: [ByteString] -> IO (IO ByteString)chunkSource chunks = do remaining <- newIORef chunks pure $ atomicModifyIORef' remaining $ \case chunk : rest -> (rest, chunk) [] -> ([], BS.empty)-- | A tree with each blob read back from the scratch directory.readBlobs :: FilePath -> Tree Blob -> IO (Tree ByteString)readBlobs scratch tree = case tree of TreeFile isExecutable blob -> TreeFile isExecutable <$> BS.readFile (blobFile scratch blob) TreeSymlink target -> pure (TreeSymlink target) TreeDirectory entries -> TreeDirectory <$> traverse (readBlobs scratch) entries-- | The numbers of a tree's blobs, in the order of its names.blobNumbers :: Tree Blob -> [Int]blobNumbers tree = case tree of TreeFile _ blob -> [blobNumber blob] TreeSymlink _ -> [] TreeDirectory entries -> concatMap blobNumbers (Map.elems entries)