module Main (main) whereimport Control.Applicative ((<|>))import Control.Exception (IOException, try)import Data.Bifunctor (first)import qualified Data.ByteString as BSimport Data.Maybe (fromMaybe)import Data.String (fromString)import Data.Text (Text)import qualified Data.Text as Timport qualified Data.Text.Encoding as TEimport Network.Wai (Response)import qualified Network.Wai.Handler.Warp as Warpimport Network.Wai.Middleware.RequestLogger (logStdout)import NovaCache.Server (ServerConfig (..), cacheApp, defaultRootResponse, htmlRootResponse, onExceptionResponse)import NovaCache.Signing (SecretKey, normalizeKeyText, parseSecretKey, renderPublicKey, toPublicKey)import NovaCache.Store (newFileStore)import System.Environment (getArgs, lookupEnv)import System.Exit (exitFailure)import System.IO (BufferMode (LineBuffering), hPutStrLn, hSetBuffering, stderr, stdout)import Text.Read (readMaybe)-- ----------------------------------------------------------------------------- Constants-- ----------------------------------------------------------------------------- | Default server port.defaultPort :: IntdefaultPort = 5000-- | Default bind host. @*@ binds every interface - the server's-- historical behavior, kept as the default so existing deployments do-- not silently rebind; a deployment opts into loopback itself via-- @--host@ or @HOST@.defaultBindHost :: StringdefaultBindHost = "*"-- | Default store directory.defaultStoreRoot :: FilePathdefaultStoreRoot = "./nix-cache"-- | The flag naming the HTML file @GET \/@ serves.rootPageFlag :: StringrootPageFlag = "--root-page"-- | Environment variable for the server port.portEnvVar :: StringportEnvVar = "PORT"-- | Environment variable for the bind host.hostEnvVar :: StringhostEnvVar = "HOST"-- | Environment variable for the store root directory.storeEnvVar :: StringstoreEnvVar = "NIX_CACHE_DIR"-- | Environment variable for the write API key.apiKeyEnvVar :: StringapiKeyEnvVar = "CACHE_API_KEY"-- | Environment variable for the signing key file path.signingKeyEnvVar :: StringsigningKeyEnvVar = "SIGNING_KEY_FILE"-- | Environment variable to disable request logging.requestLogEnvVar :: StringrequestLogEnvVar = "LOG_REQUESTS"-- | A subcommand this executable does not have: the server reclaims-- NARs itself, through @GET \/reclaim@ and @POST \/reclaim@. Named so-- that running it stops with a pointer to those requests rather than-- reaching 'serve', which ignores arguments it does not know and would-- start a second server over the store.reclaimNarsCommand :: StringreclaimNarsCommand = "reclaim-nars"-- ----------------------------------------------------------------------------- Main-- ---------------------------------------------------------------------------main :: IO ()main = do args <- getArgs case args of command : _ | command == reclaimNarsCommand -> do hPutStrLn stderr $ "FATAL: " ++ reclaimNarsCommand ++ " is not a subcommand: the server removes unreferenced NARs itself." ++ " With the write key, GET /reclaim lists them and POST /reclaim removes them;" ++ " see the README." exitFailure _ -> serve args-- | Run the cache server.serve :: [String] -> IO ()serve args = do -- Under systemd, stdout is a pipe to the journal, which GHC buffers by -- block. The request logger flushes after each line it writes, so -- without this the startup lines would wait for the first request, or, -- with request logging off, for a block to fill. hSetBuffering stdout LineBuffering portEnv <- lookupEnv portEnvVar hostEnv <- lookupEnv hostEnvVar storeEnv <- lookupEnv storeEnvVar apiKeyEnv <- lookupEnv apiKeyEnvVar sigKeyPath <- lookupEnv signingKeyEnvVar logRequestsEnv <- lookupEnv requestLogEnvVar -- Order-independent flag parsing: take the value following a flag wherever it -- appears, so e.g. `--allow-open-writes --port 8080` still honours --port. let argValue flag = case dropWhile (/= flag) args of (_ : v : _) -> Just v _ -> Nothing port = case argValue "--port" >>= readMaybe of Just p -> p Nothing -> maybe defaultPort (fromMaybe defaultPort . readMaybe) portEnv bindHost = fromMaybe defaultBindHost (argValue "--host" <|> hostEnv) storeRoot = fromMaybe (fromMaybe defaultStoreRoot storeEnv) (argValue "--store") allowOpenWrites = "--allow-open-writes" `elem` args rootPage = argValue rootPageFlag store <- newFileStore storeRoot apiKey <- loadApiKey apiKeyEnv sigKey <- loadSigningKey sigKeyPath pubKey <- derivePublicKeyLine sigKey rootResponse <- loadRootResponse rootPage let cfg = ServerConfig { scStore = store, scApiKey = apiKey, scSigningKey = sigKey, scRootResponse = rootResponse } let logRequests = logRequestsEnv /= Just "0" requestLogger = if logRequests then logStdout else id putStrLn ("nova-cache-server listening on " ++ bindHost ++ ":" ++ show port) putStrLn ("store root: " ++ storeRoot) putStrLn ("signing: " ++ maybe "disabled" (const "enabled") sigKey) mapM_ (\k -> putStrLn ("public key: " ++ T.unpack k)) pubKey putStrLn ("write auth: " ++ maybe "disabled (open writes!)" (const "enabled") apiKey) putStrLn ("request logging: " ++ if logRequests then "enabled" else "disabled (LOG_REQUESTS=0)") putStrLn ("root page: " ++ fromMaybe "none, plain text" rootPage) case apiKey of Nothing | not allowOpenWrites -> do hPutStrLn stderr $ "FATAL: " ++ apiKeyEnvVar ++ " is not set - refusing to start with unauthenticated writes. " ++ "Set " ++ apiKeyEnvVar ++ ", or pass --allow-open-writes to override (not recommended on a public host)." exitFailure _ -> pure () let settings = Warp.setHost (fromString bindHost) $ Warp.setPort port $ Warp.setOnExceptionResponse onExceptionResponse Warp.defaultSettings Warp.runSettings settings (requestLogger (cacheApp cfg))-- ----------------------------------------------------------------------------- Root response-- ----------------------------------------------------------------------------- | The response for @GET \/@: the HTML file 'rootPageFlag' names, read-- once at startup, or the library's line of plain text without one. A-- file that cannot be read stops the server at startup.loadRootResponse :: Maybe FilePath -> IO (IO Response)loadRootResponse Nothing = pure defaultRootResponseloadRootResponse (Just path) = do readResult <- try (BS.readFile path) :: IO (Either IOException BS.ByteString) case readResult of Right page -> pure (htmlRootResponse page) Left err -> do hPutStrLn stderr ("FATAL: cannot read the root page " ++ path ++ ": " ++ show err) exitFailure-- ----------------------------------------------------------------------------- Credential loading-- ----------------------------------------------------------------------------- | Normalize and validate the write API key. A key that normalizes to-- empty (BOM or whitespace only - the classic copy-paste artifact) would-- arm the auth gate with an empty secret that an empty bearer token-- matches, so it is a startup error, never an armed guard.loadApiKey :: Maybe String -> IO (Maybe BS.ByteString)loadApiKey Nothing = pure NothingloadApiKey (Just raw) | T.null normalized = do hPutStrLn stderr $ "FATAL: " ++ apiKeyEnvVar ++ " is set but empty after normalization - refusing to arm write auth with an empty key. " ++ "Set a real key, or unset it and pass --allow-open-writes to run open." exitFailure | otherwise = pure (Just (TE.encodeUtf8 normalized)) where normalized = normalizeKeyText (T.pack raw)-- | Load a signing key from a file, if configured. A configured key that-- fails to load is FATAL: falling back to unsigned would persist narinfos-- no trust anchor can verify (the same fail-closed policy as signing).loadSigningKey :: Maybe FilePath -> IO (Maybe SecretKey)loadSigningKey Nothing = pure NothingloadSigningKey (Just path) = do raw <- BS.readFile path case first show (TE.decodeUtf8' raw) >>= parseSecretKey . normalizeKeyText of Left err -> do hPutStrLn stderr ("FATAL: cannot load the signing key from " ++ path ++ ": " ++ err) exitFailure Right sk -> pure (Just sk)-- | Derive the rendered public key line from the signing key, if any,-- for the startup log, so the key an operator publishes can be checked-- against the key in use; on a derivation failure the log omits it.derivePublicKeyLine :: Maybe SecretKey -> IO (Maybe Text)derivePublicKeyLine Nothing = pure NothingderivePublicKeyLine (Just sk) = case toPublicKey sk of Left err -> do hPutStrLn stderr ("WARNING: cannot derive the public key from the signing key: " ++ err) pure Nothing Right pk -> pure (Just (renderPublicKey pk))