-- Copyright (c) 2009, Diego Souza
-- All rights reserved.
-- 
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
-- 
--   * Redistributions of source code must retain the above copyright notice,
--     this list of conditions and the following disclaimer.
--   * Redistributions in binary form must reproduce the above copyright notice,
--     this list of conditions and the following disclaimer in the documentation
--     and/or other materials provided with the distribution.
--   * Neither the name of the <ORGANIZATION> nor the names of its contributors
--     may be used to endorse or promote products derived from this software
--     without specific prior written permission.
-- 
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

-- | Implements PLAINTEXT and HMAC-SHA1 signatures of oauth spec <http://oauth.net/core/1.0a#signing_process>
module Network.Protocol.OAuth.Signature (Method(..),Signer(sign)) where

import qualified Network.Protocol.OAuth.Request as R
import qualified Data.Digest.Pure.SHA  as S
import qualified Data.Char as C
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString.Lazy.Char8 as B1
import qualified Codec.Binary.Base64.String as B2
import qualified Codec.Crypto.RSA as R1

-- | The signature method which will be used to sign requests.
data Method =   
    {-| The 'PLAINTEXT' /consumer_key/ /token_secret/ method does not provide
        any security protection and SHOULD only be used over a secure channel
        such as /HTTPS/. It does not use the Signature Base String.
    -}
    PLAINTEXT String (Maybe String)
    {-| The 'HMAC_SHA1' /consumer_key/ /token_secret/ signature method uses the
        /HMAC-SHA1/ signature algorithm as defined in
        <http://tools.ietf.org/html/rfc2104> where the Signature Base String is
        the text and the key is the concatenated values (each first encoded per
        Parameter Encoding) of the Consumer Secret and Token Secret, separated
        by an /&/ character (ASCII code 38) even if empty.
    -}
  | HMAC_SHA1 String (Maybe String) 
    {-| The 'RSA_SHA1' /rsa_privkey/ signature method uses the
        RSASSA-PKCS1-v1_5 signature algorithm as defined in [RFC3447] section
        8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for
        EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA
        public key in a verified way to the Service Provider.
    -}
  | RSA_SHA1 R1.PrivateKey

-- | Functions to sign requests according oauth spec.
class Signer a where
  {-| For a given request, this function is able sign it using the method
      specified. The full description of this process is described in depth
      at <http://oauth.net/core/1.0a#signing_process>.
  -}
  sign :: a                -- ^ The signature method to use
          -> R.Request 
          -> String        -- ^ The signature

instance Signer Method where
  sign (PLAINTEXT k (Just s)) _ = k ++ "&" ++ s
  sign (PLAINTEXT k Nothing)  _ = k ++ "&"

  sign (HMAC_SHA1 k Nothing)  r = let secret = B.concat [R.encodes k, _froms "&"]
                                  in (B2.encode . B1.unpack . S.bytestringDigest . S.hmacSha1 secret . _basestr) r
  sign (HMAC_SHA1 k (Just s)) r = let secret = B.concat [R.encodes k, _froms "&", R.encodes s]
                                  in (B2.encode . B1.unpack . S.bytestringDigest . S.hmacSha1 secret . _basestr) r

  sign (RSA_SHA1 k) r           = (B2.encode . B1.unpack . R1.rsassa_pkcs1_v1_5_sign R1.ha_SHA1 k . _basestr) r

instance Show Method where
  showsPrec _ (PLAINTEXT _ _) = showString "PLAINTEXT"

  showsPrec _ (HMAC_SHA1 _ _) = showString "HMAC-SHA1"

  showsPrec _ (RSA_SHA1 _)    = showString "RSA-SHA1"

_basestr :: R.Request -> B.ByteString
_basestr r = let endpoint' = (R.encodes . _endpoint) r
                 params'   = (R.encodes . _params) r
                 method'   = (R.encodes . show . R.method) r
             in B.concat [method', _froms "&", endpoint', _froms "&", params']

_endpoint :: R.Request -> String
_endpoint r | R.ssl r   = ssl_endpoint'
            | otherwise = endpoint'
  where
    host' = (map C.toLower . R.host) r

    port' = ((':':) . show . R.port) r

    ssl_endpoint' | R.port r == 443 = "https://" ++ host' ++ (R.path r)
                  | otherwise       = "https://" ++ host' ++ port' ++ (R.path r)

    endpoint'     | R.port r == 80  = "http://" ++ host' ++ (R.path r)
                  | otherwise       = "http://" ++ host' ++ port' ++ (R.path r)

_params :: R.Request -> String
_params = map (C.chr . fromIntegral) . B.unpack . R.show_urlencoded . R.params

_froms :: String -> B.ByteString
_froms = B.pack . map (fromIntegral . C.ord)