packages feed

memcache-0.5.1.0: Database/Memcache/Auth.hs

{-# LANGUAGE OverloadedStrings #-}

{-|
Module      : Database.Memcache.Auth
Description : Meta Text auth-file authentication
Copyright   : (c) David Terei, 2016
License     : BSD
Maintainer  : code@davidterei.com
Stability   : stable
Portability : GHC

Authentication for Memcached's experimental text-protocol auth-file mode.
-}
module Database.Memcache.Auth
  ( Authentication(..)
  , Username
  , Password
  , authenticate
  , validateCredentials
  ) where

import Database.Memcache.Errors
import Database.Memcache.Socket
import Database.Memcache.Types
import Database.Memcache.Types.Authentication (validateCredentials)

import Control.Monad (void, when)
import qualified Data.ByteString.Char8 as B8
import UnliftIO.Exception (catch, throwIO)

-- | Authenticate a connection using text-protocol credentials.
--
-- The credentials are sent only to a server in auth-file mode: first this
-- sends @version@, which such a server rejects with @CLIENT_ERROR@ until the
-- connection has authenticated. A server that answers it with @VERSION@
-- isn't in that mode, and would store the credentials as an ordinary item,
-- so this throws 'InvalidAuthentication' instead, as it does, before sending
-- anything, for credentials that contain a forbidden delimiter. An @ERROR@
-- or @SERVER_ERROR@ reply throws what it would as the reply to any request
-- (see 'responseStatus'), such as 'ServerError' for the
-- @ERROR Too many open connections@ that memcached sends to a new connection
-- when it is at its connection limit. Any other reply throws 'UnknownOp',
-- quoting it, as the same reply does in the version check that every new
-- connection makes.
--
-- Once the credentials are sent, this throws @'OpError' 'TextAuthFail'@ when
-- the server rejects them, and another 'MemcacheError', such as
-- 'UnexpectedResponse', for any other reply but @STORED@.
authenticate :: Connection -> Authentication -> IO ()
authenticate _ NoAuth = return ()
authenticate socket (Auth user pass) = do
  case validateCredentials user pass of
    Left message -> throwIO $ ClientError (InvalidAuthentication message)
    Right () -> return ()
  -- Without -Y authfile, "set auth ..." is just a normal store, so credentials
  -- would be readable via "get auth"; probe with a real command first so we
  -- never send them to a server that isn't gating on auth-file mode.
  sendRaw socket versionRequest
  probe <- recvResponse socket
  case responseCode probe of
    "CLIENT_ERROR" -> return ()
    "VERSION" -> throwIO $ ClientError
      (InvalidAuthentication "server is not in auth-file mode; refusing to send credentials")
    -- Any other reply doesn't show the mode either way, and fails as it would
    -- fail the version check that follows: an error reply throws as it would
    -- for any request, so that memcached at its connection limit is a server
    -- failure, and anything else throws UnknownOp, a client fault, as a retry
    -- would get the same reply.
    code -> do
      when (code `elem` ["ERROR", "SERVER_ERROR"]) $ void (responseStatus probe)
      throwIO $ ProtocolError UnknownOp
        { protocolError = "Expected VERSION or CLIENT_ERROR, got: "
            <> show (B8.unwords (code : responseTokens probe)) }
  let credentials = user <> B8.singleton ' ' <> pass
  sendRaw socket (authRequest credentials)
  response <- recvResponse socket
  result <- responseStatus response `catch` handleAuthFailure
  case result of
    NoError | responseCode response == "STORED" -> return ()
    -- Any other reply could leave the connection out of step, so it must not
    -- reach the pool.
    NoError -> throwIO $ ProtocolError UnexpectedResponse
      { protocolError = "Expected AUTH, got: " <> show (responseCode response) }
    status -> throwIO $ OpError status
  where
    handleAuthFailure (ProtocolError BadCommand{}) = throwIO $ OpError TextAuthFail
    handleAuthFailure err = throwIO (err :: MemcacheError)