]> git.immae.eu Git - github/fretlink/hmacaroons.git/blame - src/Crypto/Macaroon/Verifier.hs
Rewrite Verifier with Validation
[github/fretlink/hmacaroons.git] / src / Crypto / Macaroon / Verifier.hs
CommitLineData
b92e3c15 1{-# LANGUAGE OverloadedStrings #-}
c830f7c2 2{-# LANGUAGE RankNTypes #-}
b92e3c15
JT
3{-|
4Module : Crypto.Macaroon.Verifier
5Copyright : (c) 2015 Julien Tanguy
6License : BSD3
7
8Maintainer : julien.tanguy@jhome.fr
9Stability : experimental
10Portability : portable
11
12
13
14-}
6f3c0dca 15module Crypto.Macaroon.Verifier (
c830f7c2 16 Verifier
62576139 17 , verifyMacaroon
6f3c0dca 18 , verifySig
c830f7c2
JT
19 -- , verifyExact
20 -- , verifyFun
6f3c0dca 21 , module Data.Attoparsec.ByteString.Char8
62576139 22 , verifyCavs
6f3c0dca 23) where
b92e3c15
JT
24
25
26import Crypto.Hash
c830f7c2
JT
27import Data.Attoparsec.ByteString
28import Data.Attoparsec.ByteString.Char8
b92e3c15 29import Data.Bool
b92e3c15 30import Data.Byteable
c830f7c2
JT
31import qualified Data.ByteString as BS
32import Data.Either
33import Data.Either.Validation
b92e3c15 34import Data.Foldable
90695615 35import Data.Function
6f3c0dca 36import Data.Maybe
90695615 37import Data.Traversable
b92e3c15
JT
38
39import Crypto.Macaroon.Internal
40
c830f7c2 41type Verifier = Caveat -> Maybe (Either String Caveat)
b92e3c15 42
c830f7c2
JT
43verifySig :: Key -> Macaroon -> Either String Macaroon
44verifySig k m = bool (Left "Signatures do not match") (Right m) $
b92e3c15
JT
45 signature m == foldl' hash (toBytes (hmac derivedKey (identifier m) :: HMAC SHA256)) (caveats m)
46 where
47 hash s c = toBytes (hmac s (vid c `BS.append` cid c) :: HMAC SHA256)
48 derivedKey = toBytes (hmac "macaroons-key-generator" k :: HMAC SHA256)
6f3c0dca 49
c830f7c2
JT
50verifyMacaroon :: Key -> [Verifier] -> Macaroon -> Either String Macaroon
51verifyMacaroon secret verifiers m = verifySig secret m >>= verifyCavs verifiers
62576139 52
c830f7c2
JT
53verifyCavs :: [Verifier] -> Macaroon -> Either String Macaroon
54verifyCavs verifiers m = case partitionEithers verifiedCaveats of
55 ([],_) -> Right m
56 (errs,_) -> Left (mconcat errs)
57 where
58 verifiedCaveats = map (\c -> defaultFail c $ foldMap (fmap eitherToValidation . ($c)) verifiers) $ caveats m
59 defaultFail c = maybe (Left ("No validation for this caveat: " ++ show c)) validationToEither
6f3c0dca 60
857f2f3b 61
c830f7c2 62-- TODO: define API