unkai-0.1.0.1: src/Unkai/Internal/Auth.hs
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- |
-- Module : Unkai.Internal.Auth
-- Copyright : (c) 2015-2022 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Nadeem Bitar <nadeem@gmail.com>
-- Stability : provisional
-- Portability : non-portable (GHC extensions)
--
-- Internal types and helpers for constructing OAuth credentials.
module Unkai.Internal.Auth
( Credentials (..),
ServiceAccount (..),
AuthorizedUser (..),
OAuthToken (..),
AuthError (..),
AsAuthError (..),
RefreshError (..),
tokenURL,
tokenRequest,
refreshRequest,
parseLBS,
readCredentialFile,
base64Encode,
base64,
)
where
import Control.Exception (catch, throwIO)
import Control.Monad.IO.Class (MonadIO (..))
import Crypto.PubKey.RSA.Types (PrivateKey)
import Data.Aeson
import Data.Aeson.Types (Pair)
import Data.ByteArray (ByteArray)
import Data.ByteArray.Encoding
import Data.ByteString qualified as BS
import Data.ByteString.Lazy qualified as LBS
import Data.Text qualified as Text
import Data.Text.Encoding qualified as Text
import Data.Time
import Data.X509 (PrivKey (..))
import Data.X509.Memory (readKeyFileFromMemory)
import GHC.TypeLits (Symbol)
import Network.HTTP.Client (Manager)
import Network.HTTP.Client qualified as Client
import Network.HTTP.Types (Status, hContentType, statusIsSuccessful)
import System.IO.Error (isDoesNotExistError)
import Unkai.Internal.Logger
import Unkai.Prelude
-- | The supported credential mechanisms.
data Credentials (s :: [Symbol])
= -- | Obtain and refresh access tokens from the underlying GCE host metadata
-- at @http:\/\/169.254.169.254@.
FromMetadata !ServiceId
| -- | Use the specified @service_account@ and scopes to sign and request
-- an access token. The 'ServiceAccount' will also be used for subsequent
-- token refreshes.
--
-- A 'ServiceAccount' is typically generated through the
-- Google Developer Console.
FromAccount !ServiceAccount
| -- | Use the specified @authorized_user@ to obtain and refresh access tokens.
--
-- An 'AuthorizedUser' is typically created by @gcloud auth application-default login@
-- of the Google CloudSDK Tools.
FromUser !AuthorizedUser
| FromTokenFile !FilePath
-- | Service Account credentials which are typically generated/download
-- from the Google Developer console of the following form:
--
-- > {
-- > \"type\": \"service_account\",
-- > \"private_key_id\": \"303ad77e5efdf2ce952DFa\",
-- > \"private_key\": \"-----BEGIN PRIVATE KEY-----\n...\n\",
-- > \"client_email\": \"email@serviceaccount.com\",
-- > \"client_id\": \"035-2-310.useraccount.com\"
-- > }
--
-- The private key is used to sign a JSON Web Token (JWT) of the
-- grant_type @urn:ietf:params:oauth:grant-type:jwt-bearer@, which is sent to
-- 'tokenURL' to obtain a valid 'OAuthToken'. This process requires explicitly
-- specifying which 'Scope's the resulting 'OAuthToken' is authorized to access.
--
-- /See:/ <https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority Delegating authority to your service account>.
data ServiceAccount = ServiceAccount
{ _serviceId :: !ClientId,
_serviceEmail :: !Text,
_serviceKeyId :: !Text,
_servicePrivateKey :: !PrivateKey,
_serviceAccountUser :: !(Maybe Text)
}
deriving stock (Eq, Show)
instance FromJSON ServiceAccount where
parseJSON = withObject "service_account" $ \o -> do
bs <- Text.encodeUtf8 <$> o .: "private_key"
k <- case listToMaybe (readKeyFileFromMemory bs) of
Just (PrivKeyRSA k) -> pure k
_ ->
fail "Unable to parse key contents from \"private_key\""
ServiceAccount
<$> o .: "client_id"
<*> o .: "client_email"
<*> o .: "private_key_id"
<*> pure k
<*> pure Nothing
-- | Authorized User credentials which are typically generated by the Cloud SDK
-- Tools such as @gcloud auth application-default login@, of the following form:
--
-- > {
-- > \"type\": \"authorized_user\",
-- > \"client_id\": \"32555940559.apps.googleusercontent.com\",
-- > \"client_secret\": \"Zms2qjJy2998hD4CTg2ejr2\",
-- > \"refresh_token\": \"1/B3gM1x35v.VtqffS1n5w-rSJ\"
-- > }
--
-- The secret and refresh token are used to obtain a valid 'OAuthToken' from
-- 'tokenURL' using grant_type @refresh_token@.
data AuthorizedUser = AuthorizedUser
{ _userId :: !ClientId,
_userRefresh :: !RefreshToken,
_userSecret :: !GSecret
}
deriving stock (Eq, Show)
instance ToJSON AuthorizedUser where
toJSON (AuthorizedUser i r s) =
object
[ "type" .= ("authorized_user" :: Text),
"client_id" .= i,
"refresh_token" .= r,
"client_secret" .= s
]
instance FromJSON AuthorizedUser where
parseJSON = withObject "authorized_user" $ \o ->
AuthorizedUser
<$> o .: "client_id"
<*> o .: "refresh_token"
<*> o .: "client_secret"
-- | An OAuth bearer type token of the following form:
--
-- > {
-- > \"token_type\": \"Bearer\",
-- > \"access_token\": \"eyJhbGci...\",
-- > \"refresh_token\": \"1/B3gq9K...\",
-- > \"expires_in\": 3600,
-- > ...
-- > }
--
-- The '_tokenAccess' field will be inserted verbatim into the
-- @Authorization: Bearer ...@ header for all HTTP requests.
data OAuthToken (s :: [Symbol]) = OAuthToken
{ _tokenAccess :: !AccessToken,
_tokenRefresh :: !(Maybe RefreshToken),
_tokenExpiry :: !UTCTime
}
deriving stock (Eq, Show)
instance FromJSON (UTCTime -> OAuthToken s) where
parseJSON = withObject "bearer" $ \o -> do
t <- o .: "access_token"
r <- o .:? "refresh_token"
e <- o .: "expires_in" <&> fromInteger
pure (OAuthToken t r . addUTCTime e)
data RefreshError = RefreshError
{ _error :: !Text,
_description :: !(Maybe Text)
}
instance FromJSON RefreshError where
parseJSON = withObject "refresh_error" $ \o ->
RefreshError
<$> o .: "error"
<*> o .:? "error_description"
-- | @https://www.googleapis.com/oauth2/v4/token@.
tokenURL :: Text
tokenURL = "https://www.googleapis.com/oauth2/v4/token"
tokenRequest :: Client.Request
tokenRequest =
Client.defaultRequest
{ Client.host = "www.googleapis.com",
Client.port = 443,
Client.secure = True,
Client.method = "POST",
Client.path = "/oauth2/v4/token",
Client.requestHeaders =
[ (hContentType, "application/x-www-form-urlencoded")
]
}
refreshRequest ::
(MonadIO m) =>
Client.Request ->
Logger ->
Manager ->
m (OAuthToken s)
refreshRequest rq l m = do
logDebug l $ "[Token Request] method=" <> build (Client.method rq)
rs <-
liftIO $
Client.httpLbs rq m `catch` \cause -> do
logError l ("[Token Error] HTTP exchange failed" :: ByteString)
throwIO (RetrievalError cause)
let bs = Client.responseBody rs
s = Client.responseStatus rs
logDebug l $ "[Token Response] status=" <> build (fromEnum s)
if statusIsSuccessful s
then success s bs
else failure s bs
where
success s bs = do
f <- parseErr s bs
ts <- liftIO getCurrentTime
pure (f ts)
failure s bs = do
let e = "Token exchange failed"
logError l $ "[Token Error] status=" <> build (fromEnum s)
case parseLBS bs of
Right x -> refreshErr s (_error x) (_description x)
Left _ -> refreshErr s e Nothing
parseErr s bs =
case parseLBS bs of
Right !x -> pure x
Left e -> do
logError l $ "[Token Error] Invalid response at status=" <> build (fromEnum s)
refreshErr s e Nothing
refreshErr :: (MonadIO m) => Status -> Text -> Maybe Text -> m a
refreshErr s e = liftIO . throwIO . TokenRefreshError s e
parseLBS :: (FromJSON a) => LBS.ByteString -> Either Text a
parseLBS = either (Left . Text.pack) Right . eitherDecode'
base64Encode :: [Pair] -> ByteString
base64Encode = base64 . LBS.toStrict . encode . object
base64 :: (ByteArray a) => a -> ByteString
base64 = convertToBase Base64URLUnpadded
-- | Read the complete credential before returning, translating file errors
-- at the provider boundary.
readCredentialFile :: FilePath -> IO ByteString
readCredentialFile file =
BS.readFile file `catch` \cause ->
throwIO $
if isDoesNotExistError cause
then MissingFileError file
else CredentialFileReadError file cause