|
| 1 | +-- See <https://developer.github.com/webhooks/securing/>. |
| 2 | +module GitHub.Data.Webhooks.Secure |
| 3 | + ( isSecurePayload |
| 4 | + , assertSecurePayload |
| 5 | + ) where |
| 6 | + |
| 7 | +import Crypto.Hash.Algorithms (SHA1) |
| 8 | +import Crypto.MAC.HMAC (HMAC(..), hmac) |
| 9 | +import Control.Monad (unless) |
| 10 | +import Control.Exception (Exception, throwIO) |
| 11 | +import Data.ByteArray (convert, constEq) |
| 12 | +import Data.Monoid ((<>)) |
| 13 | +import Data.ByteString (ByteString) |
| 14 | +import Data.Text (Text) |
| 15 | +import qualified Data.ByteString.Base16 as B16 |
| 16 | +import qualified Data.Text.Encoding as E |
| 17 | + |
| 18 | + |
| 19 | +-- The implementation of this module is partially lifted from the @github@ package. |
| 20 | + |
| 21 | + |
| 22 | +-- | Returns 'True' if the given HMAC digest (passed in the @X-Hub-Signature@ header) |
| 23 | +-- agrees with the provided secret and request body. If not, this request may be forged. |
| 24 | +isSecurePayload |
| 25 | + :: Text |
| 26 | + -> Maybe Text |
| 27 | + -> ByteString |
| 28 | + -> Bool |
| 29 | +isSecurePayload secret shaOpt payload = maybe False (constEq ourSig) theirSig |
| 30 | + where |
| 31 | + hexDigest = B16.encode . convert . hmacGetDigest |
| 32 | + theirSig = E.encodeUtf8 <$> shaOpt |
| 33 | + ourSig = "sha1=" <> hexDigest (hmac (E.encodeUtf8 secret) payload :: HMAC SHA1) |
| 34 | + |
| 35 | + |
| 36 | +-- | An exception indicating that the given payload is not secure. |
| 37 | +data PayloadNotSecure = PayloadNotSecure |
| 38 | + |
| 39 | +instance Exception PayloadNotSecure |
| 40 | + |
| 41 | +instance Show PayloadNotSecure where |
| 42 | + showsPrec _ PayloadNotSecure = showString "the origin of this request may not originate from GitHub" |
| 43 | + |
| 44 | +-- | Like 'isSecurePayload', but throws 'PayloadNotSecure' if the payload is not secure. |
| 45 | +assertSecurePayload |
| 46 | + :: Text |
| 47 | + -> Maybe Text |
| 48 | + -> ByteString |
| 49 | + -> IO () |
| 50 | +assertSecurePayload secret shaOpt payload = do |
| 51 | + let secure = isSecurePayload secret shaOpt payload |
| 52 | + unless secure $! throwIO PayloadNotSecure |
0 commit comments