packages feed

unkai-0.1.0.1: src/Unkai/Auth/ApplicationDefault.hs

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}

-- |
-- Module      : Unkai.Auth.ApplicationDefaultCredentials
-- 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)
--
-- Application Default Credentials are suited for cases when access to a Google service
-- needs to have the same identity and authorization level for the application
-- independent of the user. This is Google\'s the recommended approach to authorize
-- calls to Google Cloud APIs, particularly when you're building an application
-- that is deployed to Google App Engine or Google Compute Engine virtual machines.
--
-- /See:/ <https://developers.google.com/identity/protocols/application-default-credentials Application Default Documentation>.
module Unkai.Auth.ApplicationDefault
  ( cloudSDKConfigDir,
    cloudSDKConfigPath,
    defaultCredentialsFile,
    defaultCredentialsPath,
    getApplicationDefault,
    fromWellKnownPath,
    fromFilePath,
    saveAuthorizedUserToWellKnownPath,
    saveAuthorizedUser,
    fromJSONCredentials,
    getConfigDirectory,
  )
where

import Control.Applicative ((<|>))
import Control.Exception qualified as IO
import Control.Exception.Lens (catching, throwingM)
import Control.Monad (unless)
import Control.Monad.Catch (MonadCatch, throwM)
import Control.Monad.IO.Class (MonadIO (..))
import Data.Aeson
import Data.Aeson.KeyMap qualified as KeyMap
import Data.Aeson.Types (parseEither)
import Data.ByteString.Lazy qualified as LBS
import Data.Text qualified as Text
import Network.HTTP.Client (Manager)
import System.Directory (createDirectoryIfMissing, getHomeDirectory, removeFile, renameFile)
import System.Environment (lookupEnv)
import System.FilePath (takeDirectory, (</>))
import System.IO (hClose, openBinaryTempFile)
import System.IO.Error (isAlreadyExistsError, isDoesNotExistError)
import System.Info (os)
import System.Posix.Files (createLink)
import Unkai.Compute.Metadata (isGCE)
import Unkai.Internal.Auth

-- | The environment variable name which is used to specify the directory
-- containing the @application_default_credentials.json@ generated by @gcloud auth application-default login@.
cloudSDKConfigDir :: String
cloudSDKConfigDir = "CLOUDSDK_CONFIG"

-- | Return the filepath to the Cloud SDK well known file location such as
-- @~\/.config\/gcloud\/application_default_credentials.json@.
cloudSDKConfigPath :: (MonadIO m) => m FilePath
cloudSDKConfigPath = do
  m <- liftIO (lookupEnv cloudSDKConfigDir)
  case m of
    Just d -> pure $! d </> "application_default_credentials.json"
    Nothing -> do
      d <- getConfigDirectory
      pure $! d </> "gcloud/application_default_credentials.json"

-- | The environment variable pointing the file with local
-- Application Default Credentials.
defaultCredentialsFile :: String
defaultCredentialsFile = "GOOGLE_APPLICATION_CREDENTIALS"

-- | Lookup the @GOOGLE_APPLICATION_CREDENTIALS@ environment variable for the
-- default application credentials filepath.
defaultCredentialsPath :: (MonadIO m) => m (Maybe FilePath)
defaultCredentialsPath = liftIO (lookupEnv defaultCredentialsFile)

-- | Performs credentials discovery in the following order:
--
-- 1. Read the default credentials from a file specified by
-- the environment variable @GOOGLE_APPLICATION_CREDENTIALS@ whenever it is set.
-- A failure reading or parsing that file is reported to the caller.
--
-- 2. Read the platform equivalent of @~\/.config\/gcloud\/application_default_credentials.json@ if it exists.
-- The @~/.config@ component of the path can be overriden by the environment
-- variable @CLOUDSDK_CONFIG@ if it exists.
--
-- 3. Retrieve the default service account application credentials if
-- running on GCE. The environment variable @NO_GCE_CHECK@ can be used to
-- skip this check if set to a truthy value such as @1@ or @true@.
--
-- The specified 'Scope's are used to authorize any @service_account@ that is
-- found with the appropriate OAuth2 scopes, otherwise they are not used. See the
-- top-level module of each individual @unkai-*@ library for a list of available
-- scopes, such as @Unkai.Compute.computeScope@.
--
-- /See:/ <https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials>
getApplicationDefault ::
  (MonadIO m, MonadCatch m) =>
  Manager ->
  m (Credentials s)
getApplicationDefault m = do
  selected <- defaultCredentialsPath
  case selected of
    Just file -> fromFilePath file
    Nothing -> do
      file <- cloudSDKConfigPath
      catching _MissingFileError (fromFilePath file) $ \missing -> do
        found <- isGCE m
        unless found $
          throwingM _MissingFileError missing
        pure (FromMetadata "default")

-- | Attempt to load either a @service_account@ or @authorized_user@ formatted
-- file to obtain the credentials neccessary to perform a token refresh.
--
-- The specified 'Scope's are used to authorize any @service_account@ that is
-- found with the appropriate scopes, otherwise they are not used. See the
-- top-level module of each individual @unkai-*@ library for a list of available
-- scopes, such as @Unkai.Compute.computeScope@.
--
-- /See:/ 'cloudSDKConfigPath', 'defaultCredentialsPath'.
fromWellKnownPath :: (MonadIO m, MonadCatch m) => m (Credentials s)
fromWellKnownPath = do
  f <- defaultCredentialsPath
  case f of
    Just x -> fromFilePath x
    Nothing -> do
      x <- cloudSDKConfigPath
      fromFilePath x

-- | Attempt to load either a @service_account@ or @authorized_user@ formatted
-- file to obtain the credentials neccessary to perform a token refresh from
-- the specified file.
--
-- The specified 'Scope's are used to authorize any @service_account@ that is
-- found with the appropriate scopes, otherwise they are not used. See the
-- top-level module of each individual @unkai-*@ library for a list of available
-- scopes, such as @Unkai.Compute.computeScope@.
fromFilePath :: (MonadIO m, MonadCatch m) => FilePath -> m (Credentials s)
fromFilePath f = do
  bytes <- liftIO (readCredentialFile f)
  either
    (throwM . InvalidFileError f . Text.pack)
    pure
    (fromJSONCredentials (LBS.fromStrict bytes))

-- | Save 'AuthorizedUser'
-- /See:/ 'cloudSDKConfigPath', 'defaultCredentialsPath'.
saveAuthorizedUserToWellKnownPath ::
  (MonadIO m) =>
  -- | Force to save if True
  Bool ->
  AuthorizedUser ->
  m ()
saveAuthorizedUserToWellKnownPath b a = do
  d <- defaultCredentialsPath
  f <- maybe cloudSDKConfigPath pure d
  liftIO $ createDirectoryIfMissing True $ takeDirectory f
  saveAuthorizedUser f b a

-- | Atomically publish an owner-only ADC file. When force is false, an
-- existing destination raises 'FileExistError'.
saveAuthorizedUser ::
  (MonadIO m) =>
  FilePath ->
  -- | Force to save if True
  Bool ->
  AuthorizedUser ->
  m ()
saveAuthorizedUser destination force credential =
  liftIO $
    IO.bracket
      (openBinaryTempFile (takeDirectory destination) ".unkai-adc")
      (\(temporary, handle) -> hClose handle `IO.finally` removeIfPresent temporary)
      ( \(temporary, handle) -> do
          LBS.hPut handle (encode credential)
          hClose handle
          if force
            then renameFile temporary destination
            else
              createLink temporary destination `IO.catch` \cause ->
                if isAlreadyExistsError cause
                  then IO.throwIO (FileExistError destination)
                  else IO.throwIO cause
      )
  where
    removeIfPresent file =
      removeFile file `IO.catch` \cause ->
        unless (isDoesNotExistError cause) (IO.throwIO cause)

-- | Parse explicitly typed ADC and legacy Unkai files that omit the type.
fromJSONCredentials :: LBS.ByteString -> Either String (Credentials s)
fromJSONCredentials bytes = eitherDecode' bytes >>= parseEither parseCredential
  where
    parseCredential = withObject "application default credentials" $ \fields ->
      let value = Object fields
       in case KeyMap.lookup "type" fields of
            Just (String "service_account") -> FromAccount <$> parseJSON value
            Just (String "authorized_user") -> FromUser <$> parseJSON value
            Nothing -> (FromAccount <$> parseJSON value) <|> (FromUser <$> parseJSON value)
            _ -> fail "Unsupported credential type"

getConfigDirectory :: (MonadIO m) => m FilePath
getConfigDirectory = do
  h <- liftIO getHomeDirectory
  if os == "windows"
    then pure h
    else pure $! h </> ".config"