{-# OPTIONS_GHC -Wall #-}

{- | For a typical webhook server implemented with Scotty, probably the only
thing you need from this module is one of these two actions:

  - 'requireSig' - If your live mode and test mode webhooks use separate
    URLs.

  - 'requireSig_eitherMode' - If your live mode and test mode webhooks use
    the same URL. -}

module Stripe.Scotty
  ( requireSig, requireSig_eitherMode
  , hasValidSig, getSig, getSigText
  ) where

-- aeson
import qualified Data.Aeson

-- base
import Control.Monad (when, (>=>))
import Control.Monad.IO.Class (MonadIO)

-- bytestring
import qualified Data.ByteString
import qualified Data.ByteString.Lazy

-- http-types
import qualified Network.HTTP.Types.Status

-- scotty
import qualified Web.Scotty.Trans as Scotty

-- stripe-concepts
import qualified Stripe.Concepts as Stripe

-- stripe-signature
import qualified Stripe.Signature as Stripe

-- text
import qualified Data.Text
import qualified Data.Text.Lazy
import qualified Data.Text.Lazy.Builder

-- unordered-containers
import qualified Data.HashMap.Strict

{- | Terminates request processing if the request does not contain a valid
Stripe signature header.

This action returns the request body as a strict byte string; it has to fully
evaluate the request body to do the signature check, so we might as well return
this information to you for subsequent use. -}

requireSig
    :: (MonadIO m, Scotty.ScottyError e) =>
    Stripe.WebhookSecretKey
    -> Scotty.ActionT e m Data.ByteString.ByteString

requireSig :: WebhookSecretKey -> ActionT e m ByteString
requireSig WebhookSecretKey
secret =
  do
    ByteString
body <- ActionT e m ByteString
forall (m :: * -> *) e.
(MonadIO m, ScottyError e) =>
ActionT e m ByteString
getBody
    Bool
okay <- WebhookSecretKey -> ByteString -> ActionT e m Bool
forall (m :: * -> *) e.
(Monad m, ScottyError e) =>
WebhookSecretKey -> ByteString -> ActionT e m Bool
hasValidSig WebhookSecretKey
secret ByteString
body

    Bool -> ActionT e m () -> ActionT e m ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not Bool
okay) ActionT e m ()
forall (m :: * -> *) e a. (Monad m, ScottyError e) => ActionT e m a
invalidSigAction

    ByteString -> ActionT e m ByteString
forall (m :: * -> *) a. Monad m => a -> m a
return ByteString
body

{- | Terminates request processing if the request does not contain a valid
Stripe signature header.

This action returns the mode and JSON request body; it has to do this much
parsing to determine the mode so that we can know which secret key to use in the
verification, so we might as well return this information to you for subsequent
use. -}

requireSig_eitherMode
    :: (MonadIO m, Scotty.ScottyError e) =>
    Stripe.BothModes (Maybe Stripe.WebhookSecretKey)
    -> Scotty.ActionT e m (Stripe.Mode, Data.Aeson.Value)

requireSig_eitherMode :: BothModes (Maybe WebhookSecretKey) -> ActionT e m (Mode, Value)
requireSig_eitherMode BothModes (Maybe WebhookSecretKey)
secrets =
  do
    ByteString
body   <- ActionT e m ByteString
forall (m :: * -> *) e.
(MonadIO m, ScottyError e) =>
ActionT e m ByteString
getBody
    Value
value  <- ByteString -> ActionT e m Value
forall (m :: * -> *) e.
(Monad m, ScottyError e) =>
ByteString -> ActionT e m Value
parseBody ByteString
body
    Mode
mode   <- Value -> ActionT e m Mode
forall (m :: * -> *) e.
(Monad m, ScottyError e) =>
Value -> ActionT e m Mode
getMode Value
value
    WebhookSecretKey
secret <- Mode
-> BothModes (Maybe WebhookSecretKey)
-> ActionT e m WebhookSecretKey
forall (m :: * -> *) e.
(Monad m, ScottyError e) =>
Mode
-> BothModes (Maybe WebhookSecretKey)
-> ActionT e m WebhookSecretKey
chooseSecret Mode
mode BothModes (Maybe WebhookSecretKey)
secrets
    Bool
okay   <- WebhookSecretKey -> ByteString -> ActionT e m Bool
forall (m :: * -> *) e.
(Monad m, ScottyError e) =>
WebhookSecretKey -> ByteString -> ActionT e m Bool
hasValidSig WebhookSecretKey
secret ByteString
body

    Bool -> ActionT e m () -> ActionT e m ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not Bool
okay) ActionT e m ()
forall (m :: * -> *) e a. (Monad m, ScottyError e) => ActionT e m a
invalidSigAction

    (Mode, Value) -> ActionT e m (Mode, Value)
forall (m :: * -> *) a. Monad m => a -> m a
return (Mode
mode, Value
value)

getBody :: (MonadIO m, Scotty.ScottyError e) =>
    Scotty.ActionT e m Data.ByteString.ByteString
getBody :: ActionT e m ByteString
getBody = ByteString -> ByteString
Data.ByteString.Lazy.toStrict (ByteString -> ByteString)
-> ActionT e m ByteString -> ActionT e m ByteString
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ActionT e m ByteString
forall e (m :: * -> *).
(ScottyError e, MonadIO m) =>
ActionT e m ByteString
Scotty.body

invalidSigAction :: (Monad m, Scotty.ScottyError e) => Scotty.ActionT e m a
invalidSigAction :: ActionT e m a
invalidSigAction =
  do
    Status -> ActionT e m ()
forall (m :: * -> *) e. Monad m => Status -> ActionT e m ()
Scotty.status Status
Network.HTTP.Types.Status.forbidden403
    Text -> ActionT e m ()
forall e (m :: * -> *).
(ScottyError e, Monad m) =>
Text -> ActionT e m ()
Scotty.text (String -> Text
Data.Text.Lazy.pack String
"Invalid Stripe signature")
    ActionT e m a
forall e (m :: * -> *) a. (ScottyError e, Monad m) => ActionT e m a
Scotty.finish

missingKeyAction :: (Monad m, Scotty.ScottyError e) =>
    Stripe.Mode -> Scotty.ActionT e m a
missingKeyAction :: Mode -> ActionT e m a
missingKeyAction Mode
mode =
  do
    Status -> ActionT e m ()
forall (m :: * -> *) e. Monad m => Status -> ActionT e m ()
Scotty.status Status
Network.HTTP.Types.Status.internalServerError500
    Text -> ActionT e m ()
forall e (m :: * -> *).
(ScottyError e, Monad m) =>
Text -> ActionT e m ()
Scotty.text Text
message
    ActionT e m a
forall e (m :: * -> *) a. (ScottyError e, Monad m) => ActionT e m a
Scotty.finish
  where
    message :: Text
message =
        Builder -> Text
Data.Text.Lazy.Builder.toLazyText (Builder -> Text) -> Builder -> Text
forall a b. (a -> b) -> a -> b
$
            (String -> Builder) -> [String] -> Builder
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap String -> Builder
Data.Text.Lazy.Builder.fromString
                [ String
"Configuration error: No webhook secret for "
                , case Mode
mode of
                    Mode
Stripe.LiveMode -> String
"live"
                    Mode
Stripe.TestMode -> String
"test"
                , String
" mode."
                ]

chooseSecret
    :: (Monad m, Scotty.ScottyError e) =>
    Stripe.Mode
    -> Stripe.BothModes (Maybe Stripe.WebhookSecretKey)
    -> Scotty.ActionT e m Stripe.WebhookSecretKey
chooseSecret :: Mode
-> BothModes (Maybe WebhookSecretKey)
-> ActionT e m WebhookSecretKey
chooseSecret Mode
mode BothModes (Maybe WebhookSecretKey)
secrets =
    case Mode
-> BothModes (Maybe WebhookSecretKey) -> Maybe WebhookSecretKey
forall a. Mode -> BothModes a -> a
Stripe.applyMode Mode
mode BothModes (Maybe WebhookSecretKey)
secrets of
        Just WebhookSecretKey
x -> WebhookSecretKey -> ActionT e m WebhookSecretKey
forall (m :: * -> *) a. Monad m => a -> m a
return WebhookSecretKey
x
        Maybe WebhookSecretKey
Nothing -> Mode -> ActionT e m WebhookSecretKey
forall (m :: * -> *) e a.
(Monad m, ScottyError e) =>
Mode -> ActionT e m a
missingKeyAction Mode
mode

parseBody
    :: (Monad m, Scotty.ScottyError e) =>
    Data.ByteString.ByteString
    -> Scotty.ActionT e m Data.Aeson.Value
parseBody :: ByteString -> ActionT e m Value
parseBody ByteString
bs =
    case ByteString -> Either String Value
forall a. FromJSON a => ByteString -> Either String a
Data.Aeson.eitherDecode (ByteString -> ByteString
Data.ByteString.Lazy.fromStrict ByteString
bs) of
        Left String
x ->
          do
            Status -> ActionT e m ()
forall (m :: * -> *) e. Monad m => Status -> ActionT e m ()
Scotty.status Status
Network.HTTP.Types.Status.badRequest400
            Text -> ActionT e m ()
forall e (m :: * -> *).
(ScottyError e, Monad m) =>
Text -> ActionT e m ()
Scotty.text (String -> Text
Data.Text.Lazy.pack String
x)
            ActionT e m Value
forall e (m :: * -> *) a. (ScottyError e, Monad m) => ActionT e m a
Scotty.finish
        Right Value
x ->
            Value -> ActionT e m Value
forall (m :: * -> *) a. Monad m => a -> m a
return Value
x

getMode :: (Monad m, Scotty.ScottyError e) =>
    Data.Aeson.Value -> Scotty.ActionT e m Stripe.Mode
getMode :: Value -> ActionT e m Mode
getMode Value
val =
    case (String -> Value -> Maybe Value
aesonAttr String
"livemode" (Value -> Maybe Value)
-> (Value -> Maybe Bool) -> Value -> Maybe Bool
forall (m :: * -> *) a b c.
Monad m =>
(a -> m b) -> (b -> m c) -> a -> m c
>=> Value -> Maybe Bool
aesonBool) Value
val of

      Maybe Bool
Nothing ->
        do
          Status -> ActionT e m ()
forall (m :: * -> *) e. Monad m => Status -> ActionT e m ()
Scotty.status Status
Network.HTTP.Types.Status.badRequest400
          Text -> ActionT e m ()
forall e (m :: * -> *).
(ScottyError e, Monad m) =>
Text -> ActionT e m ()
Scotty.text (String -> Text
Data.Text.Lazy.pack
              String
"Webhook attribute \"livemode\" is missing.")
          ActionT e m Mode
forall e (m :: * -> *) a. (ScottyError e, Monad m) => ActionT e m a
Scotty.finish

      Just Bool
livemode ->
          Mode -> ActionT e m Mode
forall (m :: * -> *) a. Monad m => a -> m a
return (Bool -> Mode
Stripe.isLiveMode' Bool
livemode)

{- | Determines whether the request contains a valid Stripe signature header. -}

hasValidSig
    :: (Monad m, Scotty.ScottyError e) =>
    Stripe.WebhookSecretKey
    -> Data.ByteString.ByteString
    -> Scotty.ActionT e m Bool
hasValidSig :: WebhookSecretKey -> ByteString -> ActionT e m Bool
hasValidSig WebhookSecretKey
secret ByteString
body =
  do
    Maybe Sig
sigMaybe <- ActionT e m (Maybe Sig)
forall (m :: * -> *) e.
(Monad m, ScottyError e) =>
ActionT e m (Maybe Sig)
getSig
    Bool -> ActionT e m Bool
forall (m :: * -> *) a. Monad m => a -> m a
return (Bool -> ActionT e m Bool) -> Bool -> ActionT e m Bool
forall a b. (a -> b) -> a -> b
$
        case Maybe Sig
sigMaybe of
            Maybe Sig
Nothing -> Bool
False
            Just Sig
sig -> Sig -> WebhookSecretKey -> ByteString -> Bool
Stripe.isSigValid Sig
sig WebhookSecretKey
secret ByteString
body

getSigText :: (Monad m, Scotty.ScottyError e) =>
    Scotty.ActionT e m (Maybe Data.Text.Text)
getSigText :: ActionT e m (Maybe Text)
getSigText =
  do
    Maybe Text
x <- Text -> ActionT e m (Maybe Text)
forall e (m :: * -> *).
(ScottyError e, Monad m) =>
Text -> ActionT e m (Maybe Text)
Scotty.header (String -> Text
Data.Text.Lazy.pack String
"Stripe-Signature")
    Maybe Text -> ActionT e m (Maybe Text)
forall (m :: * -> *) a. Monad m => a -> m a
return (Text -> Text
Data.Text.Lazy.toStrict (Text -> Text) -> Maybe Text -> Maybe Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe Text
x)

getSig :: (Monad m, Scotty.ScottyError e) =>
    Scotty.ActionT e m (Maybe Stripe.Sig)
getSig :: ActionT e m (Maybe Sig)
getSig =
  do
    Maybe Text
x <- ActionT e m (Maybe Text)
forall (m :: * -> *) e.
(Monad m, ScottyError e) =>
ActionT e m (Maybe Text)
getSigText
    Maybe Sig -> ActionT e m (Maybe Sig)
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe Text
x Maybe Text -> (Text -> Maybe Sig) -> Maybe Sig
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Text -> Maybe Sig
Stripe.parseSig)

------------------------------------------------------------

-- Internal Aeson decoding functions

aesonAttr :: String -> Data.Aeson.Value -> Maybe Data.Aeson.Value
aesonAttr :: String -> Value -> Maybe Value
aesonAttr String
x = Value -> Maybe Object
aesonObject (Value -> Maybe Object)
-> (Object -> Maybe Value) -> Value -> Maybe Value
forall (m :: * -> *) a b c.
Monad m =>
(a -> m b) -> (b -> m c) -> a -> m c
>=> Text -> Object -> Maybe Value
forall k v. (Eq k, Hashable k) => k -> HashMap k v -> Maybe v
Data.HashMap.Strict.lookup (String -> Text
Data.Text.pack String
x)

aesonObject :: Data.Aeson.Value -> Maybe Data.Aeson.Object
aesonObject :: Value -> Maybe Object
aesonObject (Data.Aeson.Object Object
x) = Object -> Maybe Object
forall a. a -> Maybe a
Just Object
x
aesonObject Value
_ = Maybe Object
forall a. Maybe a
Nothing

aesonBool :: Data.Aeson.Value -> Maybe Bool
aesonBool :: Value -> Maybe Bool
aesonBool (Data.Aeson.Bool Bool
x) = Bool -> Maybe Bool
forall a. a -> Maybe a
Just Bool
x
aesonBool Value
_ = Maybe Bool
forall a. Maybe a
Nothing