1 {-# LANGUAGE OverloadedStrings #-}
2 {-# LANGUAGE RankNTypes #-}
4 Module : Crypto.Macaroon.Verifier.Internal
5 Copyright : (c) 2015 Julien Tanguy
8 Maintainer : julien.tanguy@jhome.fr
9 Stability : experimental
10 Portability : portable
15 module Crypto.Macaroon.Verifier.Internal where
18 import Control.Monad.IO.Class
22 import qualified Data.ByteString as BS
24 import Data.Either.Validation
28 import Crypto.Macaroon.Internal
32 data ValidationError = SigMismatch
35 | ValidatorError String
38 instance Monoid ValidationError where
40 NoVerifier `mappend` e = e
41 e `mappend` NoVerifier = e
42 SigMismatch `mappend` _ = SigMismatch
43 _ `mappend` SigMismatch = SigMismatch
44 (ValidatorError e) `mappend` (ParseError _) = ValidatorError e
45 (ParseError _) `mappend` (ValidatorError e) = ValidatorError e
47 -- | Check that the given macaroon has a correct signature
48 verifySig :: Key -> Macaroon -> Either ValidationError Macaroon
49 verifySig k m = bool (Left SigMismatch) (Right m) $
50 signature m == foldl' hash (toBytes (hmac derivedKey (identifier m) :: HMAC SHA256)) (caveats m)
52 hash s c = toBytes (hmac s (vid c `BS.append` cid c) :: HMAC SHA256)
53 derivedKey = toBytes (hmac "macaroons-key-generator" k :: HMAC SHA256)
56 verifyCavs :: MonadIO m
57 => [Caveat -> m (Maybe (Either ValidationError Caveat))]
59 -> m (Either ValidationError Macaroon)
60 verifyCavs verifiers m = gatherEithers <$> mapM validateCaveat (caveats m)
63 - validateCaveat :: Caveat -> m (Validation String Caveat)
64 - We can use fromJust here safely since we use a `Just Failure` as a
65 - starting value for the foldM. We are guaranteed to have a `Just something`
68 validateCaveat c = fromJust <$> foldM (\res v -> mappend res . fmap eitherToValidation <$> v c) (defErr c) verifiers
69 -- defErr :: Caveat -> Maybe (Validation String Caveat)
70 defErr c = Just $ Failure NoVerifier
71 -- gatherEithers :: [Validation String Caveat] -> Either String Caveat
72 gatherEithers vs = case partitionEithers . map validationToEither $ vs of
74 (errs,_) -> Left (mconcat errs)