packages feed

okf-core-0.14.0.0: src/Okf/BundlePath.hs

-- | Filesystem policy for paths inside a caller-selected bundle root.
module Okf.BundlePath
  ( BundleEntry (..),
    listBundleDirectory,
    requireBundlePath,
  )
where

import Control.Exception (IOException, throwIO, tryJust)
import Control.Monad (forM, unless)
import Data.List (sort)
import System.Directory (listDirectory)
import System.FilePath qualified as Path
import System.IO.Error (isDoesNotExistError)
import System.Posix.Files (FileStatus, getSymbolicLinkStatus, isDirectory, isRegularFile)

data BundleEntry = BundleDirectory FilePath | BundleFile FilePath

-- The root itself is selected by the caller. Below it, only real directories
-- and regular files participate. This also excludes dangling links and cycles.
listBundleDirectory :: FilePath -> FilePath -> IO [BundleEntry]
listBundleDirectory root directory = do
  let absolute = root Path.</> directory
  names <- sort <$> listDirectory absolute
  fmap concat $ forM (filter visiblePart names) $ \name -> do
    let relative = directory Path.</> name
    status <- statusIfPresent (root Path.</> relative)
    pure $ case status of
      Just s | isDirectory s -> [BundleDirectory relative]
      Just s | isRegularFile s -> [BundleFile relative]
      _ -> []

-- | Check a direct file target and all its descendant directory components
-- before reading or writing. Missing components may be created by a writer.
requireBundlePath :: FilePath -> FilePath -> IO FilePath
requireBundlePath root path = do
  unless (Path.isRelative path && not (null parts) && all visiblePart parts) refuse
  inspect root parts
  pure (root Path.</> path)
  where
    parts = Path.splitDirectories path
    refuse = throwIO (userError ("unsafe bundle path: " <> path))
    inspect _ [] = pure ()
    inspect directory (part : rest) = do
      let target = directory Path.</> part
      status <- statusIfPresent target
      case status of
        Nothing -> pure ()
        Just s
          | null rest && isRegularFile s -> pure ()
          | not (null rest) && isDirectory s -> inspect target rest
          | otherwise -> refuse

visiblePart :: FilePath -> Bool
visiblePart [] = False
visiblePart ('.' : _) = False
visiblePart _ = True

statusIfPresent :: FilePath -> IO (Maybe FileStatus)
statusIfPresent path =
  either (const Nothing) Just <$> tryJust missing (getSymbolicLinkStatus path)
  where
    missing :: IOException -> Maybe ()
    missing exception
      | isDoesNotExistError exception = Just ()
      | otherwise = Nothing