diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,85 @@
+# Changelog
+
+## Unreleased
+
+## 0.1.0.1 — 2026-11-24
+
+- Ship the runtime on Hackage with a matching Cloud Storage client and core package.
+
+## 0.1.0.0 — 2026-11-24
+
+- Forked from gogol 1.0.0.0 (mori://brendanhay/gogol, upstream commit 881cd14c9844131b4a8d96ca1bbb2bd9a2409ed9) and renamed the `Gogol` namespace to `Unkai`.
+- Require GHC 9.12 or newer; use the GHC2024 language edition.
+- Use `gcloud auth application-default login` and `newEnv` for local sign-in. This replaces `Unkai.Auth.InstalledApplication`, `FromClient`, and the out-of-band redirect helpers. Explicit credentials can still be passed to `newEnvWith`. An unreadable or invalid file selected by `GOOGLE_APPLICATION_CREDENTIALS` now fails discovery with its path.
+- Match `Left (AuthenticationError cause)` from `sendEither`, `uploadEither`, and `downloadEither` to handle credential problems. Keep a returned download `Stream` inside the `runResourceT` scope that opened it. Read failures after a successful download response occur when you consume the body.
+- Import request functions, `Error`, `PatchField`, `Stream`, and `sinkLBS` from `Unkai`. The generator-facing `Unkai.Prelude` and `Unkai.Types` are available from `unkai-core`.
+- **Breaking change.** `Stream` is now a Streamly stream of strict `ByteString` chunks. Add `streamly-core` and replace Conduit consumers with Streamly folds. Run the request and fold in the same `runResourceT` scope. `sinkLBS` still collects the entire body when you need it in memory.
+
+  ```haskell
+  {-# LANGUAGE OverloadedStrings #-}
+
+  import Control.Monad.IO.Class (liftIO)
+  import Data.ByteString qualified as BS
+  import Streamly.Data.Fold qualified as Fold
+  import Streamly.Data.Stream qualified as Stream
+  import System.IO (IOMode (WriteMode), withBinaryFile)
+  import Unkai (Env, download, runResourceT)
+  import Unkai.Storage qualified as Storage
+
+  downloadFile :: Env '[Storage.Devstorage'ReadOnly] -> FilePath -> IO ()
+  downloadFile env output = withBinaryFile output WriteMode $ \handle ->
+    runResourceT $ do
+      stream <- download env (Storage.newStorageObjectsGet "bucket" "reports/q1.csv")
+      Stream.fold (Fold.drainMapM (liftIO . BS.hPut handle)) stream
+  ```
+
+- Pass raw names such as `reports/q1.csv` to generated constructors. They now encode the name as one path segment. Use `upload` for multipart uploads. It supplies `uploadType=multipart`.
+- Use `newStorageObjectsMove bucket sourceObject destinationObject`, `newStorageObjectsCopy sourceBucket sourceObject destinationBucket destinationObject payload`, and the same source-first order for rewrite and folder rename. Named construction can make the role of each `Text` argument explicit.
+
+  ```haskell
+  {-# LANGUAGE OverloadedStrings #-}
+
+  import Unkai.Storage qualified as Storage
+
+  move =
+    Storage.StorageObjectsMove
+      { bucket = "b",
+        sourceObject = "reports/q1.csv",
+        destinationObject = "archive/q1.csv",
+        ifGenerationMatch = Nothing,
+        ifGenerationNotMatch = Nothing,
+        ifMetagenerationMatch = Nothing,
+        ifMetagenerationNotMatch = Nothing,
+        ifSourceGenerationMatch = Nothing,
+        ifSourceGenerationNotMatch = Nothing,
+        ifSourceMetagenerationMatch = Nothing,
+        ifSourceMetagenerationNotMatch = Nothing,
+        projection = Nothing,
+        userProject = Nothing
+      }
+
+  copy =
+    Storage.StorageObjectsCopy
+      { sourceBucket = "b",
+        sourceObject = "reports/q1.csv",
+        destinationBucket = "archive",
+        destinationObject = "q1.csv",
+        payload = Storage.newObject,
+        destinationKmsKeyName = Nothing,
+        destinationPredefinedAcl = Nothing,
+        ifGenerationMatch = Nothing,
+        ifGenerationNotMatch = Nothing,
+        ifMetagenerationMatch = Nothing,
+        ifMetagenerationNotMatch = Nothing,
+        ifSourceGenerationMatch = Nothing,
+        ifSourceGenerationNotMatch = Nothing,
+        ifSourceMetagenerationMatch = Nothing,
+        ifSourceMetagenerationNotMatch = Nothing,
+        projection = Nothing,
+        sourceGeneration = Nothing,
+        userProject = Nothing
+      }
+  ```
+
+- Build PATCH bodies with constructors such as `newObjectPatch`. Set a field to `Set value` to assign it or `Clear` to send JSON null. `newObjectPatch` starts with all fields set to `Omit`. Use `newObject_MetadataPatch` with a map entry set to `Nothing` to clear one custom metadata key.
+- Use `newBucketInsertInput name` for bucket creation. For compose, use `newComposeRequestInput` with a `NonEmpty` list of values built by `newComposeRequest_SourceObjectsItemInput name`. For an IAM policy replacement, `newPolicySetIamPolicyInput []` sends an empty bindings list.
diff --git a/LICENSE b/LICENSE
new file mode 100644
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,367 @@
+Mozilla Public License Version 2.0
+==================================
+
+1. Definitions
+--------------
+
+1.1. "Contributor"
+    means each individual or legal entity that creates, contributes to
+    the creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+    means the combination of the Contributions of others (if any) used
+    by a Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+    means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+    means Source Code Form to which the initial Contributor has attached
+    the notice in Exhibit A, the Executable Form of such Source Code
+    Form, and Modifications of such Source Code Form, in each case
+    including portions thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+    means
+
+    (a) that the initial Contributor has attached the notice described
+        in Exhibit B to the Covered Software; or
+
+    (b) that the Covered Software was made available under the terms of
+        version 1.1 or earlier of the License, but not also under the
+        terms of a Secondary License.
+
+1.6. "Executable Form"
+    means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+    means a work that combines Covered Software with other material, in
+    a separate file or files, that is not Covered Software.
+
+1.8. "License"
+    means this document.
+
+1.9. "Licensable"
+    means having the right to grant, to the maximum extent possible,
+    whether at the time of the initial grant or subsequently, any and
+    all of the rights conveyed by this License.
+
+1.10. "Modifications"
+    means any of the following:
+
+    (a) any file in Source Code Form that results from an addition to,
+        deletion from, or modification of the contents of Covered
+        Software; or
+
+    (b) any new file in Source Code Form that contains any Covered
+        Software.
+
+1.11. "Patent Claims" of a Contributor
+    means any patent claim(s), including without limitation, method,
+    process, and apparatus claims, in any patent Licensable by such
+    Contributor that would be infringed, but for the grant of the
+    License, by the making, using, selling, offering for sale, having
+    made, import, or transfer of either its Contributions or its
+    Contributor Version.
+
+1.12. "Secondary License"
+    means either the GNU General Public License, Version 2.0, the GNU
+    Lesser General Public License, Version 2.1, the GNU Affero General
+    Public License, Version 3.0, or any later versions of those
+    licenses.
+
+1.13. "Source Code Form"
+    means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+    means an individual or a legal entity exercising rights under this
+    License. For legal entities, "You" includes any entity that
+    controls, is controlled by, or is under common control with You. For
+    purposes of this definition, "control" means (a) the power, direct
+    or indirect, to cause the direction or management of such entity,
+    whether by contract or otherwise, or (b) ownership of more than
+    fifty percent (50%) of the outstanding shares or beneficial
+    ownership of such entity.
+
+2. License Grants and Conditions
+--------------------------------
+
+2.1. Grants
+
+Each Contributor hereby grants You a world-wide, royalty-free,
+non-exclusive license:
+
+(a) under intellectual property rights (other than patent or trademark)
+    Licensable by such Contributor to use, reproduce, make available,
+    modify, display, perform, distribute, and otherwise exploit its
+    Contributions, either on an unmodified basis, with Modifications, or
+    as part of a Larger Work; and
+
+(b) under Patent Claims of such Contributor to make, use, sell, offer
+    for sale, have made, import, and otherwise transfer either its
+    Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+The licenses granted in Section 2.1 with respect to any Contribution
+become effective for each Contribution on the date the Contributor first
+distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+The licenses granted in this Section 2 are the only rights granted under
+this License. No additional rights or licenses will be implied from the
+distribution or licensing of Covered Software under this License.
+Notwithstanding Section 2.1(b) above, no patent license is granted by a
+Contributor:
+
+(a) for any code that a Contributor has removed from Covered Software;
+    or
+
+(b) for infringements caused by: (i) Your and any other third party's
+    modifications of Covered Software, or (ii) the combination of its
+    Contributions with other software (except as part of its Contributor
+    Version); or
+
+(c) under Patent Claims infringed by Covered Software in the absence of
+    its Contributions.
+
+This License does not grant any rights in the trademarks, service marks,
+or logos of any Contributor (except as may be necessary to comply with
+the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+No Contributor makes additional grants as a result of Your choice to
+distribute the Covered Software under a subsequent version of this
+License (see Section 10.2) or under the terms of a Secondary License (if
+permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+Each Contributor represents that the Contributor believes its
+Contributions are its original creation(s) or it has sufficient rights
+to grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+This License is not intended to limit any rights You have under
+applicable copyright doctrines of fair use, fair dealing, or other
+equivalents.
+
+2.7. Conditions
+
+Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
+in Section 2.1.
+
+3. Responsibilities
+-------------------
+
+3.1. Distribution of Source Form
+
+All distribution of Covered Software in Source Code Form, including any
+Modifications that You create or to which You contribute, must be under
+the terms of this License. You must inform recipients that the Source
+Code Form of the Covered Software is governed by the terms of this
+License, and how they can obtain a copy of this License. You may not
+attempt to alter or restrict the recipients' rights in the Source Code
+Form.
+
+3.2. Distribution of Executable Form
+
+If You distribute Covered Software in Executable Form then:
+
+(a) such Covered Software must also be made available in Source Code
+    Form, as described in Section 3.1, and You must inform recipients of
+    the Executable Form how they can obtain a copy of such Source Code
+    Form by reasonable means in a timely manner, at a charge no more
+    than the cost of distribution to the recipient; and
+
+(b) You may distribute such Executable Form under the terms of this
+    License, or sublicense it under different terms, provided that the
+    license for the Executable Form does not attempt to limit or alter
+    the recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+You may create and distribute a Larger Work under terms of Your choice,
+provided that You also comply with the requirements of this License for
+the Covered Software. If the Larger Work is a combination of Covered
+Software with a work governed by one or more Secondary Licenses, and the
+Covered Software is not Incompatible With Secondary Licenses, this
+License permits You to additionally distribute such Covered Software
+under the terms of such Secondary License(s), so that the recipient of
+the Larger Work may, at their option, further distribute the Covered
+Software under the terms of either this License or such Secondary
+License(s).
+
+3.4. Notices
+
+You may not remove or alter the substance of any license notices
+(including copyright notices, patent notices, disclaimers of warranty,
+or limitations of liability) contained within the Source Code Form of
+the Covered Software, except that You may alter any license notices to
+the extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+You may choose to offer, and to charge a fee for, warranty, support,
+indemnity or liability obligations to one or more recipients of Covered
+Software. However, You may do so only on Your own behalf, and not on
+behalf of any Contributor. You must make it absolutely clear that any
+such warranty, support, indemnity, or liability obligation is offered by
+You alone, and You hereby agree to indemnify every Contributor for any
+liability incurred by such Contributor as a result of warranty, support,
+indemnity or liability terms You offer. You may include additional
+disclaimers of warranty and limitations of liability specific to any
+jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+---------------------------------------------------
+
+If it is impossible for You to comply with any of the terms of this
+License with respect to some or all of the Covered Software due to
+statute, judicial order, or regulation then You must: (a) comply with
+the terms of this License to the maximum extent possible; and (b)
+describe the limitations and the code they affect. Such description must
+be placed in a text file included with all distributions of the Covered
+Software under this License. Except to the extent prohibited by statute
+or regulation, such description must be sufficiently detailed for a
+recipient of ordinary skill to be able to understand it.
+
+5. Termination
+--------------
+
+5.1. The rights granted under this License will terminate automatically
+if You fail to comply with any of its terms. However, if You become
+compliant, then the rights granted under this License from a particular
+Contributor are reinstated (a) provisionally, unless and until such
+Contributor explicitly and finally terminates Your grants, and (b) on an
+ongoing basis, if such Contributor fails to notify You of the
+non-compliance by some reasonable means prior to 60 days after You have
+come back into compliance. Moreover, Your grants from a particular
+Contributor are reinstated on an ongoing basis if such Contributor
+notifies You of the non-compliance by some reasonable means, this is the
+first time You have received notice of non-compliance with this License
+from such Contributor, and You become compliant prior to 30 days after
+Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+infringement claim (excluding declaratory judgment actions,
+counter-claims, and cross-claims) alleging that a Contributor Version
+directly or indirectly infringes any patent, then the rights granted to
+You by any and all Contributors for the Covered Software under Section
+2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all
+end user license agreements (excluding distributors and resellers) which
+have been validly granted by You or Your distributors under this License
+prior to termination shall survive termination.
+
+************************************************************************
+*                                                                      *
+*  6. Disclaimer of Warranty                                           *
+*  -------------------------                                           *
+*                                                                      *
+*  Covered Software is provided under this License on an "as is"       *
+*  basis, without warranty of any kind, either expressed, implied, or  *
+*  statutory, including, without limitation, warranties that the       *
+*  Covered Software is free of defects, merchantable, fit for a        *
+*  particular purpose or non-infringing. The entire risk as to the     *
+*  quality and performance of the Covered Software is with You.        *
+*  Should any Covered Software prove defective in any respect, You     *
+*  (not any Contributor) assume the cost of any necessary servicing,   *
+*  repair, or correction. This disclaimer of warranty constitutes an   *
+*  essential part of this License. No use of any Covered Software is   *
+*  authorized under this License except under this disclaimer.         *
+*                                                                      *
+************************************************************************
+
+************************************************************************
+*                                                                      *
+*  7. Limitation of Liability                                          *
+*  --------------------------                                          *
+*                                                                      *
+*  Under no circumstances and under no legal theory, whether tort      *
+*  (including negligence), contract, or otherwise, shall any           *
+*  Contributor, or anyone who distributes Covered Software as          *
+*  permitted above, be liable to You for any direct, indirect,         *
+*  special, incidental, or consequential damages of any character      *
+*  including, without limitation, damages for lost profits, loss of    *
+*  goodwill, work stoppage, computer failure or malfunction, or any    *
+*  and all other commercial damages or losses, even if such party      *
+*  shall have been informed of the possibility of such damages. This   *
+*  limitation of liability shall not apply to liability for death or   *
+*  personal injury resulting from such party's negligence to the       *
+*  extent applicable law prohibits such limitation. Some               *
+*  jurisdictions do not allow the exclusion or limitation of           *
+*  incidental or consequential damages, so this exclusion and          *
+*  limitation may not apply to You.                                    *
+*                                                                      *
+************************************************************************
+
+8. Litigation
+-------------
+
+Any litigation relating to this License may be brought only in the
+courts of a jurisdiction where the defendant maintains its principal
+place of business and such litigation shall be governed by laws of that
+jurisdiction, without reference to its conflict-of-law provisions.
+Nothing in this Section shall prevent a party's ability to bring
+cross-claims or counter-claims.
+
+9. Miscellaneous
+----------------
+
+This License represents the complete agreement concerning the subject
+matter hereof. If any provision of this License is held to be
+unenforceable, such provision shall be reformed only to the extent
+necessary to make it enforceable. Any law or regulation which provides
+that the language of a contract shall be construed against the drafter
+shall not be used to construe this License against a Contributor.
+
+10. Versions of the License
+---------------------------
+
+10.1. New Versions
+
+Mozilla Foundation is the license steward. Except as provided in Section
+10.3, no one other than the license steward has the right to modify or
+publish new versions of this License. Each version will be given a
+distinguishing version number.
+
+10.2. Effect of New Versions
+
+You may distribute the Covered Software under the terms of the version
+of the License under which You originally received the Covered Software,
+or under the terms of any subsequent version published by the license
+steward.
+
+10.3. Modified Versions
+
+If you create software not governed by this License, and you want to
+create a new license for such software, you may create and use a
+modified version of this License if you rename the license and remove
+any references to the name of the license steward (except to note that
+such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+Licenses
+
+If You choose to distribute Source Code Form that is Incompatible With
+Secondary Licenses under the terms of this version of the License, the
+notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+-------------------------------------------
+
+  This Source Code Form is subject to the terms of the Mozilla Public
+  License, v. 2.0. If a copy of the MPL was not distributed with this
+  file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular
+file, then You may include the notice in a location (such as a LICENSE
+file in a relevant directory) where a recipient would be likely to look
+for such a notice.
+
+You may add additional accurate notices of copyright ownership.
diff --git a/README.md b/README.md
new file mode 100644
--- /dev/null
+++ b/README.md
@@ -0,0 +1,11 @@
+# unkai
+
+Runtime for the `unkai-*` Google Cloud service libraries: credential discovery
+(Application Default Credentials, service accounts, authorized users, the GCE
+metadata server), token refresh, the `Env` environment, and request/response
+handling (including streaming and multipart media uploads).
+
+Pair it with a generated service package, for example `unkai-storage`.
+
+Unkai is a maintained fork of [gogol](https://github.com/brendanhay/gogol),
+released under the [Mozilla Public License 2.0](LICENSE).
diff --git a/src/Unkai.hs b/src/Unkai.hs
new file mode 100644
--- /dev/null
+++ b/src/Unkai.hs
@@ -0,0 +1,466 @@
+{-# LANGUAGE DataKinds #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE FunctionalDependencies #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE PolyKinds #-}
+{-# LANGUAGE RankNTypes #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE UndecidableInstances #-}
+{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
+
+-- |
+-- Module      : Unkai
+-- 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)
+--
+-- This module provides a common set of operations which can be performed against
+-- the remote Google Service APIs. Typically you will import this module qualified
+-- along with modules from the various @unkai-*@ libraries for services you wish
+-- to communicate with.
+module Unkai
+  ( -- * Usage
+    -- $usage
+
+    -- * Environment
+    Env,
+    HasEnv (..),
+    newEnv,
+    newEnvWith,
+
+    -- ** Credentials
+    -- $credentials
+    Credentials (..),
+    AuthorizedUser (..),
+    ServiceAccount (..),
+    getApplicationDefault,
+    fromFilePath,
+    saveAuthorizedUser,
+    saveAuthorizedUserToWellKnownPath,
+
+    -- ** Authorization
+    -- $authorization
+    type AllowRequest,
+    KnownScopes,
+    allow,
+    forbid,
+    (!),
+
+    -- * Sending Requests
+    send,
+    sendEither,
+
+    -- ** Streaming Media
+    download,
+    downloadEither,
+    upload,
+    uploadEither,
+    GBody (..),
+    bodyContentType,
+    sourceBody,
+    getMIMEType,
+
+    -- * Service Configuration
+    -- $configuration
+
+    -- ** Overriding Defaults
+    configure,
+    override,
+    timeout,
+
+    -- ** Lenses
+    serviceHost,
+    servicePort,
+    servicePath,
+    serviceSecure,
+    serviceTimeout,
+
+    -- * Handling Errors
+    Error (..),
+    AuthError (..),
+    SerializeError (..),
+    ServiceError (..),
+    AsError (..),
+    AsAuthError (..),
+
+    -- * Logging
+    -- $logging
+    Logger,
+    LogLevel (..),
+
+    -- ** Constructing a Logger
+    newLogger,
+
+    -- * Constructing a HTTP Manager
+    newManager,
+    tlsManagerSettings,
+
+    -- * Running Asynchronous Actions
+    -- $async
+
+    -- * Compute Metadata
+    -- $metadata
+
+    -- * Re-exported Types
+    GoogleRequest (Rs, Scopes),
+    MediaUpload,
+    MediaDownload,
+    ServiceConfig,
+    Stream,
+    sinkLBS,
+    FieldMask (..),
+    PatchField (..),
+    Seconds (..),
+    seconds,
+    microseconds,
+    AccessToken (..),
+    RefreshToken (..),
+    OAuthScope (..),
+    ClientId (..),
+    ServiceId (..),
+    GSecret (..),
+    Base64 (..),
+    DateTime (..),
+    Date (..),
+    Time (..),
+    Duration (..),
+    AsText (..),
+
+    -- * Re-exported Utilities
+    runResourceT,
+  )
+where
+
+import Control.Exception.Lens
+import Control.Monad
+import Control.Monad.IO.Class (MonadIO (..))
+import Control.Monad.Trans.Resource (MonadResource, runResourceT)
+import Network.HTTP.Client (newManager)
+import Network.HTTP.Client.TLS (tlsManagerSettings)
+import Unkai.Auth
+import Unkai.Env
+import Unkai.Internal.Body
+import Unkai.Internal.HTTP
+import Unkai.Internal.Logger
+import Unkai.Prelude
+
+-- | Send a request, returning authentication, transport, serialization and
+-- service failures in 'Left'.
+sendEither ::
+  ( MonadResource m,
+    AllowRequest a scopes
+  ) =>
+  Env scopes ->
+  a ->
+  m (Either Error (Rs a))
+sendEither =
+  unsafeRequest
+
+-- | Send a request, returning the associated response if successful.
+--
+-- Throws 'Error' during request setup and eager response handling.
+send ::
+  ( MonadResource m,
+    AllowRequest a scopes
+  ) =>
+  Env scopes ->
+  a ->
+  m (Rs a)
+send env =
+  sendEither env
+    >=> hoistEither
+
+-- | Send a request returning the associated streaming media response if successful.
+--
+-- Some request data types have two possible responses, the JSON metadata and
+-- a streaming media response. Use 'send' to retrieve the metadata and 'download'
+-- to retrieve the streaming media.
+--
+-- Consume the single-pass Streamly stream inside the same 'runResourceT' scope.
+-- Once this function returns 'Right', subsequent body-read failures are raised
+-- during consumption.
+downloadEither ::
+  ( MonadResource m,
+    AllowRequest (MediaDownload a) scopes
+  ) =>
+  Env scopes ->
+  a ->
+  m (Either Error (Rs (MediaDownload a)))
+downloadEither env =
+  sendEither env
+    . MediaDownload
+
+-- | Send a request returning the associated streaming media response if successful.
+--
+-- Some request data types have two possible responses, the JSON metadata and
+-- a streaming media response. Use 'send' to retrieve the metadata and 'download'
+-- to retrieve the streaming media.
+--
+-- Equivalent to:
+--
+-- @
+-- 'send' . 'MediaDownload'
+-- @
+--
+-- Write each strict byte chunk to a binary file as it arrives.
+--
+-- > {-# LANGUAGE OverloadedStrings #-}
+-- >
+-- > import Control.Monad.IO.Class (liftIO)
+-- > import qualified Data.ByteString as BS
+-- > import qualified Streamly.Data.Fold as Fold
+-- > import qualified Streamly.Data.Stream as Stream
+-- > import System.IO (IOMode (WriteMode), withBinaryFile)
+-- > import Unkai (Env, download, runResourceT)
+-- > import qualified Unkai.Storage as Storage
+-- >
+-- > downloadFile :: Env '[Storage.Devstorage'ReadOnly] -> FilePath -> IO ()
+-- > downloadFile env output = withBinaryFile output WriteMode $ \handle ->
+-- >   runResourceT $ do
+-- >     stream <- download env (Storage.newStorageObjectsGet "bucket" "reports/q1.csv")
+-- >     Stream.fold (Fold.drainMapM (liftIO . BS.hPut handle)) stream
+--
+-- Throws 'Error' during request setup and eager response handling.
+download ::
+  ( MonadResource m,
+    AllowRequest (MediaDownload a) scopes
+  ) =>
+  Env scopes ->
+  a ->
+  m (Rs (MediaDownload a))
+download env =
+  downloadEither env
+    >=> hoistEither
+
+-- | Send a request with an attached <https://tools.ietf.org/html/rfc2387 multipart/related media> upload.
+--
+-- Equivalent to:
+--
+-- @
+-- 'sendEither' . 'MediaUpload'
+-- @
+--
+-- For example:
+--
+-- > {-# LANGUAGE OverloadedLabels #-}
+-- > {-# LANGUAGE OverloadedStrings #-}
+-- >
+-- > import Control.Lens ((&), (?~))
+-- > import Data.Generics.Labels ()
+-- > import Unkai (Env, Error, runResourceT, sourceBody, uploadEither)
+-- > import qualified Unkai.Storage as Storage
+-- >
+-- > uploadFile :: Env '[Storage.Devstorage'ReadWrite] -> FilePath -> IO (Either Error Storage.Object)
+-- > uploadFile env path = do
+-- >   let metadata = Storage.newObject & #name ?~ "reports/q1.csv"
+-- >   body <- sourceBody path
+-- >   runResourceT (uploadEither env (Storage.newStorageObjectsInsert "bucket" metadata) body)
+uploadEither ::
+  ( MonadResource m,
+    AllowRequest (MediaUpload a) scopes
+  ) =>
+  Env scopes ->
+  a ->
+  GBody ->
+  m (Either Error (Rs (MediaUpload a)))
+uploadEither env x =
+  sendEither env
+    . MediaUpload x
+
+-- | Send a request with an attached <https://tools.ietf.org/html/rfc2387 multipart/related media> upload.
+--
+-- Equivalent to:
+--
+-- @
+-- 'send' . 'MediaUpload'
+-- @
+--
+-- Throws 'Error' during request setup and eager response handling.
+upload ::
+  ( MonadResource m,
+    AllowRequest (MediaUpload a) scopes
+  ) =>
+  Env scopes ->
+  a ->
+  GBody ->
+  m (Rs (MediaUpload a))
+upload env x =
+  uploadEither env x
+    >=> hoistEither
+
+hoistEither :: (MonadIO m) => Either Error a -> m a
+hoistEither = either (liftIO . throwingM _Error) pure
+
+-- $usage
+--
+-- The request and response types provided by the various @unkai-*@ libraries can
+-- be used with either 'send', 'upload', or 'download', depending upon the
+-- request's purpose. Namely, 'send' is the function you will most commonly use to
+-- send requests, with 'upload' and 'download' as convenience when dealing with
+-- streaming requests and responses respectively.
+--
+-- To get started we will need to specify our Google Service credentials and
+-- create an 'Env' environment containing configuration which will be used by
+-- calling functions to perform any actions. Your Google 'Credentials' can be supplied
+-- in a number of ways, by having Unkai retrieve
+-- <https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials>
+-- for use on Google App Engine and Google Compute Engine, or by explicitly
+-- supplying your credentials. See the <#credentials Credentials> section for
+-- information about supported credential mechanisms.
+--
+-- The following example demonstrates uploading a file to Google
+-- <https://cloud.google.com/storage/ Cloud Storage> using 'ObjectsInsert' from
+-- <http://hackage.haskell.org/package/unkai-storage unkai-storage>:
+--
+--
+-- > {-# LANGUAGE DataKinds #-}
+-- > {-# LANGUAGE FlexibleContexts #-}
+-- > {-# LANGUAGE OverloadedLabels #-}
+-- > {-# LANGUAGE OverloadedStrings #-}
+-- > {-# LANGUAGE ScopedTypeVariables #-}
+-- >
+-- > import Control.Lens ((.~), (<&>), (?~))
+-- > import Data.Function ((&))
+-- > import Data.Generics.Labels ()
+-- > import Data.Proxy (Proxy (..))
+-- > import System.IO (stdout)
+-- > import Unkai (HasEnv (envLogger, envScopes), LogLevel (Debug), newEnv, newLogger, runResourceT, sourceBody, upload)
+-- > import qualified Unkai.Storage as Storage
+-- >
+-- > example :: IO Storage.Object
+-- > example = do
+-- >   lgr <- newLogger Debug stdout                                                                          -- (1)
+-- >   env <- newEnv <&> (envLogger .~ lgr) . (envScopes .~ (Proxy :: Proxy '[Storage.Devstorage'ReadWrite])) -- (2) (3)
+-- >   body <- sourceBody "/path/to/image.jpg"                                                                -- (4)
+-- >   let key = "image.jpg"
+-- >       bucket = "my-storage-bucket"
+-- >
+-- >   runResourceT $                                                                                         -- (5)
+-- >     upload env (Storage.newStorageObjectsInsert bucket (Storage.newObject & #name ?~ key)) body
+--
+-- Breaking down the above example, we have the following points of interest:
+--
+-- 1. A new 'Logger' to replace the default noop logger is created, set to print
+--    debug information and errors to 'stdout'.
+--
+-- 2. The 'Env' is created using 'newEnv'. This creates a new HTTP 'Manager' and
+--    retrieves the application default 'Credentials'.
+--
+-- 3. The lenses 'envLogger' and 'envScopes' are used to set the newly created
+--    'Logger' and authorised OAuth2 scopes, respectively. Explicitly annotating the
+--    'Env' with the scopes ensures that any mismatch between the remote
+--    operations performed in 'upload' and the credential scopes are raised as
+--    errors at compile time.
+--    See the <#authorization Authorization> section for more information.
+--
+-- 4. The streaming 'body' for the object is retrieved from a 'FilePath', and the
+--    MIME type is calculated from the file extension.
+--    The MIME type is used as the object's @Content-Type@ in Cloud Storage, and
+--    can be overriden using the 'bodyContentType' lens as follows:
+--
+--     > import Network.HTTP.Media ((//))
+--     >
+--     > body <- sourceBody f <&> bodyContentType .~ "application" // "json"
+--
+-- 5. Finally, we run the 'Google' computation using @'runResourceT'@
+--    which serialises the 'StorageObjectsInsert' type to a HTTP request and sets the streaming 'Body'.
+--    The resulting 'Storage.Object' metadata is then parsed from a successful HTTP response.
+-- 1
+-- Additional examples can be found can be found in the
+-- <https://github.com/shinzui/unkai/tree/develop/examples Unkai> project's
+-- source control.
+
+-- $authorization #authorization#
+-- Each request within a particular 'send', 'upload' or 'download' context requires specific
+-- OAuth2 scopes to be have been authorized for the given credentials.
+--
+-- For example, the Google Storage 'StorageObjectsInsert' has the associated scopes of:
+--
+-- > type Scopes ObjectsInsert =
+-- >      '["https://www.googleapis.com/auth/cloud-platform",
+-- >        "https://www.googleapis.com/auth/devstorage.full_control",
+-- >        "https://www.googleapis.com/auth/devstorage.read_write"]
+--
+-- Multiple differing requests within a given function call context will then require
+-- the credentials to have a minimal set of these associated request scopes.
+-- This authorization information is represented as a type-level set,
+-- the 's' type parameter of 'Env'. A mismatch of the sent request scopes and the 'Env' credential scopes results in a informative
+-- compile error.
+--
+-- You can use 'allow' or the 'envScopes' lens to specify the 'Env's set of scopes.
+-- The various @unkai-*@ libraries export their individual scopes from @Unkai.*"
+-- and you can use the '(!)' combinator to combine these into a larger set.
+--
+-- For example:
+--
+-- > import Control.Lens ((<&>), (.~))
+-- > import Unkai
+-- > import Unkai.Monitoring
+-- > import Unkai.Compute
+-- >
+-- > main :: IO ()
+-- > main = do
+-- >     env <- newEnv <&> envScopes .~ (Proxy :: Proxy '[Monitoring'Read, Monitoring'Write, Compute'ReadOnly])
+-- >     ...
+--
+-- >>> :type env
+-- Env '["https://www.googleapis.com/auth/monitoring.read", "https://www.googleapis.com/auth/monitoring.write", "https://www.googleapis.com/auth/compute.readonly"]
+
+-- $configuration
+-- Each service has its own configuration such as host, port, path prefix, and timeout
+-- which can be customized independent of other services.
+-- It can be desirable to customize this when mocking service endpoints or adjusting
+-- HTTP response timeouts for a specific request.
+--
+-- For example, to point all calls to Google Compute to @https://localhost@ instead
+-- of the actual remote endpoint, we can use @Control.Monad.Reader.local@ in conjunction
+-- with 'override':
+--
+-- > import Control.Lens ((&), (.~))
+-- > import Control.Monad.Reader (local)
+-- > import Unkai
+-- > import Unkai.Compute
+-- >
+-- > local (override (computeService & serviceHost .~ "localhost")) $ do
+-- >    _ <- send $ instancesGet "project" "zone" "instance-id"
+-- >    ...
+
+-- $credentials #credentials#
+-- By default 'newEnv' uses 'getApplicationDefault' to discover credentials
+-- from the underlying, following Google's official library behaviour.
+-- If you wish to manually specify 'Credentials' via 'newEnvWith', you can use one
+-- of the following supported credential mechanisms:
+--
+-- * "Unkai.Auth.ServiceAccount" - Applications deployed to custom environments.
+-- * "Unkai.Auth.ApplicationDefault" - Applications deployed to App Engine (GAE) or Compute Engine (GCE).
+--
+-- For local development, run @gcloud auth application-default login@ to
+-- create an authorized-user ADC file. See "Unkai.Auth" for direct credential operations.
+
+-- $async
+-- Requests can be sent asynchronously, but due to guarantees about resource closure
+-- require the use of <http://hackage.haskell.org/package/lifted-async lifted-async>.
+
+-- $metadata
+--
+-- Google Compute metadata can be retrieve when running on GCE instances.
+-- See the documentation in "Unkai.Compute.Metadata" for the available
+-- functions.
+
+-- $logging
+-- The exposed logging interface is a primitive 'Logger' function which gets
+-- threaded through service calls and serialisation routines. This allows the
+-- consuming library to output useful information and diagnostics. Unkai sends
+-- method, status and request summaries to callbacks. Token exchange bodies
+-- and credential-bearing request and response data are omitted at every level.
+--
+-- The 'newLogger' function can be used to construct a simple logger which writes
+-- output to a 'Handle', but in most production code you should probably consider
+-- using a more robust logging library such as
+-- <http://hackage.haskell.org/package/tinylog tinylog> or
+-- <http://hackage.haskell.org/package/fast-logger fast-logger>.
diff --git a/src/Unkai/Auth.hs b/src/Unkai/Auth.hs
new file mode 100644
--- /dev/null
+++ b/src/Unkai/Auth.hs
@@ -0,0 +1,209 @@
+{-# LANGUAGE DataKinds #-}
+{-# LANGUAGE KindSignatures #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+-- |
+-- Module      : Unkai.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)
+--
+-- Explicitly specify your Google credentials, or retrieve them
+-- from the underlying OS.
+module Unkai.Auth
+  ( -- * Credentials
+    Credentials (..),
+    AuthorizedUser (..),
+    ServiceAccount (..),
+
+    -- ** Application Default Credentials
+    getApplicationDefault,
+    fromWellKnownPath,
+    fromFilePath,
+    saveAuthorizedUserToWellKnownPath,
+    saveAuthorizedUser,
+
+    -- ** Service account user impersonation
+    serviceAccountUser,
+
+    -- *** Kubernetes
+    serviceAccountTokenFile,
+
+    -- ** Authorizing Requests
+    authorize,
+
+    -- ** Thread-safe Storage
+    Store,
+    initStore,
+    retrieveAuthFromStore,
+    retrieveTokenFromStore,
+    Auth (..),
+    exchange,
+    refresh,
+
+    -- ** Default Constants
+    checkGCEVar,
+    cloudSDKConfigDir,
+    defaultCredentialsFile,
+
+    -- ** Handling Errors
+    AsAuthError (..),
+    AuthError (..),
+
+    -- * OAuth Types
+    OAuthToken (..),
+    OAuthScope (..),
+
+    -- * Re-exported Types
+    AccessToken (..),
+    RefreshToken (..),
+    GSecret (..),
+    ServiceId (..),
+    ClientId (..),
+
+    -- * Re-exported Modules
+    module Unkai.Auth.Scope,
+  )
+where
+
+import Control.Concurrent
+import Control.Monad.IO.Class (MonadIO (..))
+import Data.Time (getCurrentTime)
+import GHC.TypeLits (Symbol)
+import Network.HTTP.Client (Manager)
+import Network.HTTP.Client qualified as Client
+import Network.HTTP.Types (hAuthorization)
+import Unkai.Auth.ApplicationDefault
+import Unkai.Auth.Scope
+import Unkai.Auth.ServiceAccount
+import Unkai.Auth.TokenFile
+import Unkai.Compute.Metadata (checkGCEVar)
+import Unkai.Internal.Auth
+import Unkai.Internal.Logger (Logger)
+import Unkai.Prelude
+
+-- | An 'OAuthToken' that can potentially be expired, with the original
+-- credentials that can be used to perform a refresh.
+data Auth (s :: [Symbol]) = Auth
+  { _credentials :: !(Credentials s),
+    _token :: !(OAuthToken s)
+  }
+
+-- | Check if the given token is still valid, ie. younger than the projected
+-- expiry time.
+--
+-- This deliberately makes no external calls due to the absolute construction of
+-- the '_tokenExpiry' field, unlike the
+-- <https://developers.google.com/accounts/docs/OAuth2Login#validatingtoken documented>
+-- validation method.
+validate :: (MonadIO m) => Auth s -> m Bool
+validate a = (< _tokenExpiry (_token a)) <$> liftIO getCurrentTime
+
+-- | Data store which ensures thread-safe access of credentials.
+newtype Store (s :: [Symbol]) = Store (MVar (Auth s))
+
+-- | Construct storage containing the credentials which have not yet been
+-- exchanged or refreshed.
+initStore ::
+  (MonadIO m, KnownScopes s) =>
+  Credentials s ->
+  Logger ->
+  Manager ->
+  m (Store s)
+initStore c l m = exchange c l m >>= fmap Store . liftIO . newMVar
+
+-- | Retrieve auth from storage
+retrieveAuthFromStore ::
+  (MonadIO m) =>
+  Store s ->
+  m (Auth s)
+retrieveAuthFromStore (Store s) =
+  liftIO (readMVar s)
+
+-- | Concurrently read the current token, and if expired, then
+-- safely perform a single serial refresh.
+retrieveTokenFromStore ::
+  (MonadIO m, KnownScopes s) =>
+  Store s ->
+  Logger ->
+  Manager ->
+  m (OAuthToken s)
+retrieveTokenFromStore (Store s) l m = do
+  x <- liftIO (readMVar s)
+  mx <- validate x
+  if mx
+    then pure (_token x)
+    else liftIO . modifyMVar s $ \y -> do
+      my <- validate y
+      if my
+        then pure (y, _token y)
+        else do
+          z <- refresh y l m
+          pure (z, _token z)
+
+-- | Perform the initial credentials exchange to obtain a valid 'OAuthToken'
+-- suitable for authorizing requests.
+exchange ::
+  forall m s.
+  (MonadIO m, KnownScopes s) =>
+  Credentials s ->
+  Logger ->
+  Manager ->
+  m (Auth s)
+exchange c l = fmap (Auth c) . action l
+  where
+    action = case c of
+      FromMetadata s -> metadataToken s
+      FromAccount a -> serviceAccountToken a (Proxy :: Proxy s)
+      FromUser u -> authorizedUserToken u Nothing
+      FromTokenFile f -> \_l _m -> readTokenFile f
+
+-- | Refresh an existing 'OAuthToken'.
+refresh ::
+  forall m s.
+  (MonadIO m, KnownScopes s) =>
+  Auth s ->
+  Logger ->
+  Manager ->
+  m (Auth s)
+refresh (Auth c t) l = fmap (Auth c) . action l
+  where
+    action = case c of
+      FromMetadata s -> metadataToken s
+      FromAccount a -> serviceAccountToken a (Proxy :: Proxy s)
+      FromUser u -> authorizedUserToken u (_tokenRefresh t)
+      FromTokenFile f -> \_l _m -> readTokenFile f
+
+-- | Apply the (by way of possible token refresh) a bearer token to the
+-- authentication header of a request.
+authorize ::
+  (MonadIO m, KnownScopes s) =>
+  Client.Request ->
+  Store s ->
+  Logger ->
+  Manager ->
+  m Client.Request
+authorize rq s l m = bearer <$> retrieveTokenFromStore s l m
+  where
+    bearer t =
+      rq
+        { Client.requestHeaders =
+            ( hAuthorization,
+              "Bearer " <> toHeader (_tokenAccess t)
+            )
+              : Client.requestHeaders rq
+        }
+
+-- | Set the user to be impersonated for a service account with domain
+-- wide delegation. See
+-- https://developers.google.com/identity/protocols/OAuth2ServiceAccount
+serviceAccountUser ::
+  forall s.
+  Maybe Text ->
+  Credentials s ->
+  Credentials s
+serviceAccountUser u (FromAccount s) = FromAccount $ s {_serviceAccountUser = u}
+serviceAccountUser _ c = c
diff --git a/src/Unkai/Auth/ApplicationDefault.hs b/src/Unkai/Auth/ApplicationDefault.hs
new file mode 100644
--- /dev/null
+++ b/src/Unkai/Auth/ApplicationDefault.hs
@@ -0,0 +1,213 @@
+{-# 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"
diff --git a/src/Unkai/Auth/Scope.hs b/src/Unkai/Auth/Scope.hs
new file mode 100644
--- /dev/null
+++ b/src/Unkai/Auth/Scope.hs
@@ -0,0 +1,186 @@
+{-# LANGUAGE ConstraintKinds #-}
+{-# LANGUAGE DataKinds #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE PolyKinds #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE TypeOperators #-}
+{-# LANGUAGE UndecidableInstances #-}
+
+-- |
+-- Module      : Unkai.Auth.Scope
+-- Copyright   : (c) 2015 Brendan Hay
+-- License     : Mozilla Public License, v. 2.0.
+-- Maintainer  : Nadeem Bitar <nadeem@gmail.com>
+-- Stability   : provisional
+-- Portability : non-portable (GHC extensions)
+--
+-- Helpers for specifying and using type-level OAuth scopes.
+module Unkai.Auth.Scope
+  ( -- * Scope constraints
+    type AllowRequest,
+    type SatisfyScope,
+
+    -- ** Modifying type-level lists of scopes
+    allow,
+    forbid,
+    (!),
+
+    -- * Manipulating scope values
+    KnownScopes (..),
+    concatScopes,
+    queryEncodeScopes,
+  )
+where
+
+import Data.ByteString (ByteString)
+import Data.ByteString.Char8 qualified as BS8
+import Data.Coerce (coerce)
+import Data.Text (Text)
+import Data.Text qualified as Text
+import Data.Text.Encoding qualified as Text
+import Data.Type.Bool (type If, type (||))
+import Data.Typeable (Proxy (..))
+import GHC.Exts (Constraint)
+import GHC.TypeLits
+import Network.HTTP.Types (urlEncode)
+import Unkai.Internal.Auth (Credentials)
+import Unkai.Types (GoogleRequest (..), OAuthScope (..))
+
+-- | 'Constraint' kind for proving the @scopes@ context contains one of the
+-- scopes necessary for authenticating the request, @a@.
+--
+-- The two constraints below check that the environment can both upload and
+-- download media. The completed download replaces the destination atomically.
+--
+-- > {-# LANGUAGE OverloadedLabels #-}
+-- >
+-- > import Control.Exception (bracketOnError, finally)
+-- > import Control.Lens ((&), (?~))
+-- > import Control.Monad.IO.Class (liftIO)
+-- > import qualified Data.ByteString as BS
+-- > import Data.Generics.Labels ()
+-- > import Data.Text (Text)
+-- > import qualified Streamly.Data.Fold as Fold
+-- > import qualified Streamly.Data.Stream as Stream
+-- > import System.Directory (removeFile, renameFile)
+-- > import System.FilePath (takeDirectory)
+-- > import System.IO (hClose, openBinaryTempFile)
+-- > import Unkai (AllowRequest, Env, MediaDownload, MediaUpload, download, runResourceT, sourceBody, upload)
+-- > import qualified Unkai.Storage as Storage
+-- >
+-- > uploadAndDownloadFile
+-- >   :: ( AllowRequest (MediaUpload Storage.StorageObjectsInsert) scopes
+-- >      , AllowRequest (MediaDownload Storage.StorageObjectsGet) scopes
+-- >      )
+-- >   => Env scopes -> Text -> Text -> FilePath -> FilePath -> IO Storage.Object
+-- > uploadAndDownloadFile env bucket name src dst = do
+-- >   body <- sourceBody src
+-- >   let metadata = Storage.newObject & #name ?~ name
+-- >   bracketOnError
+-- >     (openBinaryTempFile (takeDirectory dst) ".unkai-download")
+-- >     (\(tmp, handle) -> hClose handle `finally` removeFile tmp)
+-- >     $ \(tmp, handle) -> do
+-- >       object <- runResourceT $ do
+-- >         result <- upload env (Storage.newStorageObjectsInsert bucket metadata) body
+-- >         stream <- download env (Storage.newStorageObjectsGet bucket name)
+-- >         Stream.fold (Fold.drainMapM (liftIO . BS.hPut handle)) stream
+-- >         pure result
+-- >       hClose handle
+-- >       renameFile tmp dst
+-- >       pure object
+--
+-- /See:/ 'SatisfyScope'.
+type AllowRequest a scopes = (GoogleRequest a, KnownScopes scopes, SatisfyScope (Scopes a) scopes)
+
+-- | 'Constraint' proving at least _one_ scope from @required@ exists in
+-- the provided context, @scopes@.
+--
+-- That is, the set of possible scopes a request requires are on the left, and
+-- the set of scopes credentials or an environment contain are on the right.
+type family SatisfyScope (required :: [Symbol]) (scopes :: [Symbol]) :: Constraint where
+  SatisfyScope '[] _ = () -- Special case; no scopes are required.
+  SatisfyScope required scopes =
+    If (Intersect scopes required) (() :: Constraint) (TypeError (MissingScopesError required scopes))
+
+type MissingScopesError (required :: [k]) (scopes :: [k]) =
+  'Text "One scope from the following list is required:"
+    ':$$: 'Text "    " ':<>: 'ShowType required
+    ':$$: 'Text "However, none of these scopes are present in the list of scopes you provided:"
+    ':$$: 'Text "    " ':<>: 'ShowType scopes
+
+-- Short-circuiting intersection - does at least one element exist in both lists?
+type family Intersect (as :: [k]) (bs :: [k]) :: Bool where
+  Intersect '[] _ = 'False
+  Intersect _ '[] = 'False
+  Intersect (a ': as) bs = Elem a bs || Intersect as bs
+
+-- Type-level 'Data.List.elem'.
+type family Elem (x :: k) (xs :: [k]) :: Bool where
+  Elem _ '[] = 'False
+  Elem x (x ': xs) = 'True
+  Elem x (y ': xs) = Elem x xs
+
+-- This exists to allow users to choose between using 'newEnv'
+-- with a 'Proxy' constructed by '!', or explicitly
+-- specifying scopes via a type annotation.
+--
+-- /See:/ '!', 'envScopes', and the scopes available for each service.
+allow :: proxy s -> k s -> k s
+allow _ = id
+
+-- | Annotate credentials with no scope authorization.
+forbid :: k '[] -> k '[]
+forbid = id
+
+-- | Append two sets of scopes.
+--
+-- /See:/ 'allow'.
+(!) :: proxy xs -> proxy ys -> Proxy (Nub (xs ++ ys))
+(!) _ _ = Proxy
+
+-- | Append two lists.
+type family (++) xs ys where
+  (++) xs '[] = xs
+  (++) '[] ys = ys
+  (++) (x ': xs) ys = x ': (xs ++ ys)
+
+-- | Remove duplicates from a list.
+type family Nub xs where
+  Nub '[] = '[]
+  Nub (x ': xs) = x ': Nub (Delete x xs)
+
+-- | Remove a specific element from a list.
+type family Delete x xs where
+  Delete x '[] = '[]
+  Delete x (x ': ys) = Delete x ys
+  Delete x (y ': ys) = y ': Delete x ys
+
+class KnownScopes a where
+  -- | Obtain a list of supported 'OAuthScope' values from a proxy.
+  --
+  -- This is used to pass scope _values_ to functions that require them,
+  -- such as 'Unkai.Auth.ServiceAccount.serviceAccountToken'.
+  scopeVals :: proxy a -> [OAuthScope]
+
+instance KnownScopes '[] where
+  scopeVals _ = []
+
+instance (KnownSymbol x, KnownScopes xs) => KnownScopes (x ': xs) where
+  scopeVals _ = scope (Proxy :: Proxy x) : scopeVals (Proxy :: Proxy xs)
+    where
+      scope = OAuthScope . Text.pack . symbolVal
+
+instance (KnownScopes s) => KnownScopes (Credentials s) where
+  scopeVals _ = scopeVals (Proxy :: Proxy s)
+
+-- | Concatenate a list of scopes using spaces.
+concatScopes :: [OAuthScope] -> Text
+concatScopes = Text.intercalate " " . coerce
+
+-- | Encode a list of scopes suitable for embedding in a query string.
+queryEncodeScopes :: [OAuthScope] -> ByteString
+queryEncodeScopes =
+  BS8.intercalate "+"
+    . map (urlEncode True . Text.encodeUtf8)
+    . coerce
diff --git a/src/Unkai/Auth/ServiceAccount.hs b/src/Unkai/Auth/ServiceAccount.hs
new file mode 100644
--- /dev/null
+++ b/src/Unkai/Auth/ServiceAccount.hs
@@ -0,0 +1,159 @@
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE PolyKinds #-}
+
+-- |
+-- Module      : Unkai.Auth.ServiceAccount
+-- 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)
+--
+-- Credentials for Server to Server communication, such as between a deployed web
+-- application and a Google service.
+--
+-- Typically, an application uses a service account when the application uses
+-- Google services to work with its own data rather than a specific user's data.
+--
+-- /See:/ <https://developers.google.com/identity/protocols/OAuth2ServiceAccount Service Account Documentation>.
+module Unkai.Auth.ServiceAccount
+  ( ServiceAccount (..),
+    AuthorizedUser (..),
+    maxTokenLifetime,
+    metadataToken,
+    authorizedUserToken,
+    serviceAccountToken,
+    encodeBearerJWT,
+  )
+where
+
+import Control.Applicative ((<|>))
+import Control.Monad.Catch
+import Control.Monad.IO.Class
+import Crypto.Hash.Algorithms (SHA256 (..))
+import Crypto.PubKey.RSA.PKCS15 (signSafer)
+import Data.Aeson
+import Data.ByteString.Char8 qualified as BS8
+import Data.Text qualified as Text
+import Data.Text.Encoding qualified as Text
+import Data.Time.Clock.POSIX
+import Network.HTTP.Client (Manager, RequestBody (RequestBodyBS))
+import Network.HTTP.Client qualified as Client
+import Unkai.Auth.Scope (KnownScopes (..), concatScopes)
+import Unkai.Compute.Metadata
+import Unkai.Internal.Auth
+import Unkai.Internal.Logger
+import Unkai.Prelude hiding (buildText)
+
+-- | The maximum lifetime of a @service_account@ token which is 1 hour, in seconds.
+maxTokenLifetime :: Seconds
+maxTokenLifetime = 3600
+
+-- | Obtain an 'OAuthToken' from the local instace metadata
+-- using the specific 'ServiceId'.
+--
+-- For example: @http:\/\/metadata.google.internal\/computeMetadata\/v1\/instance\/service-accounts\/default\/token@
+-- will be retrieved if the given 'ServiceId' is @\"default\"@.
+metadataToken ::
+  (MonadIO m) =>
+  ServiceId ->
+  Logger ->
+  Manager ->
+  m (OAuthToken s)
+metadataToken s =
+  refreshRequest $
+    metadataRequest
+      { Client.path =
+          "/computeMetadata/v1/instance/service-accounts/"
+            <> Text.encodeUtf8 (toQueryParam s)
+            <> "/token"
+      }
+
+-- | Use the 'AuthorizedUser' to obtain a new 'OAuthToken'. If the supplied
+-- 'RefreshToken' is 'Nothing', the original 'RefreshToken' from the user will
+-- be used.
+authorizedUserToken ::
+  (MonadIO m) =>
+  AuthorizedUser ->
+  Maybe RefreshToken ->
+  Logger ->
+  Manager ->
+  m (OAuthToken s)
+authorizedUserToken u r logger manager = do
+  token <- refreshRequest request logger manager
+  pure token {_tokenRefresh = _tokenRefresh token <|> Just refresh}
+  where
+    refresh = fromMaybe (_userRefresh u) r
+    request =
+      Client.urlEncodedBody
+        [ ("grant_type", "refresh_token"),
+          ("client_id", toHeader (_userId u)),
+          ("client_secret", toHeader (_userSecret u)),
+          ("refresh_token", toHeader refresh)
+        ]
+        tokenRequest
+
+-- | Obtain an 'OAuthToken' from 'tokenURL'
+-- by signing and sending a JSON Web Token (JWT) using the supplied 'ServiceAccount'.
+serviceAccountToken ::
+  (MonadIO m, KnownScopes s) =>
+  ServiceAccount ->
+  proxy s ->
+  Logger ->
+  Manager ->
+  m (OAuthToken s)
+serviceAccountToken s p l m = do
+  b <- encodeBearerJWT s p
+  let rq =
+        tokenRequest
+          { Client.requestBody =
+              RequestBodyBS $
+                "grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer"
+                  <> "&assertion="
+                  <> b
+          }
+  refreshRequest rq l m
+
+-- | Encode the supplied 'ServiceAccount's key id, email, and scopes using the
+-- private key in the JSON Web Token (JWT) format.
+encodeBearerJWT ::
+  (MonadIO m, KnownScopes s) =>
+  ServiceAccount ->
+  proxy s ->
+  m ByteString
+encodeBearerJWT s p = liftIO $ do
+  i <- input . truncate <$> getPOSIXTime
+  r <- signSafer (Just SHA256) (_servicePrivateKey s) i
+  either failure (pure . concat' i) r
+  where
+    concat' i x = i <> "." <> signature (base64 x)
+
+    failure e =
+      throwM $
+        TokenRefreshError (toEnum 400) (Text.pack (show e)) Nothing
+
+    signature bs =
+      case BS8.unsnoc bs of
+        Nothing -> mempty
+        Just (bs', x)
+          | x == '=' -> bs'
+          | otherwise -> bs
+
+    input n = header <> "." <> payload
+      where
+        header =
+          base64Encode
+            [ "alg" .= ("RS256" :: Text),
+              "typ" .= ("JWT" :: Text),
+              "kid" .= _serviceKeyId s
+            ]
+
+        payload =
+          base64Encode $
+            [ "aud" .= tokenURL,
+              "scope" .= concatScopes (scopeVals p),
+              "iat" .= n,
+              "exp" .= (n + seconds maxTokenLifetime),
+              "iss" .= _serviceEmail s
+            ]
+              <> maybe [] (\sub -> ["sub" .= sub]) (_serviceAccountUser s)
diff --git a/src/Unkai/Auth/TokenFile.hs b/src/Unkai/Auth/TokenFile.hs
new file mode 100644
--- /dev/null
+++ b/src/Unkai/Auth/TokenFile.hs
@@ -0,0 +1,42 @@
+{-# LANGUAGE OverloadedStrings #-}
+
+-- |
+-- Module      : Unkai.Auth.TokenFile
+-- 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)
+module Unkai.Auth.TokenFile
+  ( serviceAccountTokenFile,
+    readTokenFile,
+  )
+where
+
+import Control.Exception (throwIO)
+import Control.Monad.IO.Class (MonadIO (liftIO))
+import Data.Text qualified as Text
+import Data.Text.Encoding qualified as Text.Encoding
+import Data.Time qualified as Time
+import Unkai.Internal.Auth
+import Unkai.Types (AccessToken (..))
+
+serviceAccountTokenFile :: FilePath
+serviceAccountTokenFile = "/var/run/secrets/kubernetes.io/serviceaccount/token"
+
+readTokenFile :: (MonadIO m) => FilePath -> m (OAuthToken s)
+readTokenFile path =
+  liftIO $ do
+    bytes <- readCredentialFile path
+    access <- case Text.Encoding.decodeUtf8' bytes of
+      Left _ -> throwIO (InvalidFileError path "Expected a UTF-8 access token")
+      Right token | not (Text.null (Text.strip token)) -> pure (Text.strip token)
+      Right _ -> throwIO (InvalidFileError path "Expected a nonempty access token")
+    expiry <- Time.addUTCTime 60 <$> Time.getCurrentTime
+
+    pure
+      OAuthToken
+        { _tokenAccess = AccessToken access,
+          _tokenRefresh = Nothing,
+          _tokenExpiry = expiry
+        }
diff --git a/src/Unkai/Compute/Metadata.hs b/src/Unkai/Compute/Metadata.hs
new file mode 100644
--- /dev/null
+++ b/src/Unkai/Compute/Metadata.hs
@@ -0,0 +1,259 @@
+{-# LANGUAGE OverloadedStrings #-}
+
+-- |
+-- Module      : Unkai.Compute.Metadata
+-- 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)
+--
+-- Google Compute Engine defines a set of default metadata entries that provide
+-- information about your instance or project.
+--
+-- This module contains functions for retrieving various Compute metadata from an
+-- instance\'s local metadata endpoint using 'MonadIO', prior to initialisation
+-- of the environment used by the "Unkai" monad.
+module Unkai.Compute.Metadata
+  ( -- * Google Compute Instance Check
+    checkGCEVar,
+    isGCE,
+
+    -- * Retrieving Metadata
+    getProjectAttribute,
+    getSSHKeys,
+    getNumericProjectId,
+    getProjectId,
+    getInstanceAttribute,
+    getDescription,
+    getHostname,
+    getInstanceId,
+    getMachineType,
+    getTags,
+    getZone,
+
+    -- * Raw Metadata Requests
+    metadataFlavorHeader,
+    metadataFlavorDesired,
+    metadataRequest,
+    getMetadata,
+  )
+where
+
+import Control.Exception (throwIO)
+import Control.Monad.Catch
+import Control.Monad.IO.Class (MonadIO (..))
+import Data.Aeson (eitherDecode')
+import Data.ByteString (ByteString)
+import Data.ByteString.Lazy qualified as LBS
+import Data.Char (toLower)
+import Data.Text.Encoding qualified as Text
+import Data.Text.Lazy qualified as LText
+import Data.Text.Lazy.Encoding qualified as LText
+import Network.HTTP.Client (HttpException (..), HttpExceptionContent (..), Manager)
+import Network.HTTP.Client qualified as Client
+import Network.HTTP.Types (HeaderName)
+import System.Environment (lookupEnv)
+import Unkai.Prelude (Text)
+
+-- | The @NO_GCE_CHECK@ environment variable.
+checkGCEVar :: String
+checkGCEVar = "NO_GCE_CHECK"
+
+-- | The @Metadata-Flavor@ header.
+metadataFlavorHeader :: HeaderName
+metadataFlavorHeader = "Metadata-Flavor"
+
+-- | The desired metadata flavor.
+metadataFlavorDesired :: ByteString
+metadataFlavorDesired = "Google"
+
+-- | Detect if the underlying host is running on GCE.
+--
+-- The environment variable @NO_GCE_CHECK@ can be set to @1@, @true@, @yes@, or @on@
+-- to skip this check and always return @False@.
+isGCE :: (MonadIO m) => Manager -> m Bool
+isGCE m = liftIO $ do
+  p <- check <$> lookupEnv checkGCEVar
+  if p
+    then (success <$> Client.httpLbs rq m) `catch` failure
+    else pure False
+  where
+    check Nothing = True
+    check (Just x) = map toLower x `notElem` ["1", "true", "yes", "on"]
+
+    success rs =
+      fromEnum (Client.responseStatus rs) == 200
+        && ( lookup metadataFlavorHeader (Client.responseHeaders rs)
+               == Just metadataFlavorDesired
+           )
+
+    failure :: HttpException -> IO Bool
+    failure = const (pure False)
+
+    rq =
+      metadataRequest
+        { Client.responseTimeout = Client.responseTimeoutMicro 1000000
+        }
+
+-- | A directory of custom metadata values that have been set for this project.
+getProjectAttribute :: (MonadIO m) => Text -> Manager -> m (Maybe LBS.ByteString)
+getProjectAttribute k =
+  getMetadataMaybe ("project/attributes/" <> Text.encodeUtf8 k)
+
+-- | SSH keys that can connect to instances in the project. SSH keys for Compute
+-- Engine use a specialized format where the keys are prepended with a username,
+-- like so: @user1:ssh-rsa my-public-ssh-key user1@host.com@
+getSSHKeys :: (MonadIO m) => Manager -> m [Text]
+getSSHKeys m = do
+  mx <- getMetadataMaybe "project/attributes/sshKeys" m
+  case mx of
+    Nothing -> pure []
+    Just x ->
+      pure
+        . map LText.toStrict
+        . LText.split (== '\n')
+        $ LText.decodeUtf8 x
+
+-- | The numeric project ID of the instance, which is not the same as the project
+-- name visible in the Google Developers Console. This value is different from
+-- the project-id metadata entry value. The project-id value is required for all
+-- requests to the Compute Engine service.
+getNumericProjectId :: (MonadIO m) => Manager -> m Text
+getNumericProjectId = getMetadataText "project/numeric-project-id"
+
+-- | The project ID.
+getProjectId :: (MonadIO m) => Manager -> m Text
+getProjectId = getMetadataText "project/project-id"
+
+-- | A directory of custom metadata values passed to the instance during startup
+-- or shutdown.
+getInstanceAttribute :: (MonadIO m) => Text -> Manager -> m (Maybe LBS.ByteString)
+getInstanceAttribute k =
+  getMetadataMaybe ("instance/attributes/" <> Text.encodeUtf8 k)
+
+-- | The free-text description of an instance, assigned using the
+-- @--description@ flag, or set in the API.
+getDescription :: (MonadIO m) => Manager -> m Text
+getDescription = getMetadataText "instance/description"
+
+-- | The host name of the instance.
+getHostname :: (MonadIO m) => Manager -> m Text
+getHostname = getMetadataText "instance/hostname"
+
+-- | The ID of the instance. This is a unique, numerical ID that is generated by
+-- Google Compute Engine. This is useful for identifying instances if you do not
+-- want to use instance names.
+getInstanceId :: (MonadIO m) => Manager -> m Text
+getInstanceId = getMetadataText "instance/id"
+
+-- | The fully-qualified machine type name of the instance's host machine.
+getMachineType :: (MonadIO m) => Manager -> m Text
+getMachineType = getMetadataText "instance/machine-type"
+
+-- | Any tags associated with the instance.
+getTags :: (MonadIO m) => Manager -> m [Text]
+getTags m = do
+  rs <- getMetadata "instance/tags" [] m
+  case eitherDecode' (Client.responseBody rs) of
+    Left _ -> pure []
+    Right xs -> pure xs
+
+-- | The instance's zone.
+getZone :: (MonadIO m) => Manager -> m Text
+getZone = getMetadataText "instance/zone"
+
+-- -- | A directory of disks attached to this instance.
+-- getDisk ::
+-- "instance/disks/"
+
+-- -- | A directory of service accounts associated with the instance.
+-- getServiceAccount
+-- "instance/service-accounts/"
+
+-- -- | A directory of network interfaces for the instance.
+-- getNetworkInterfaces
+-- "instance/network-interfaces/"
+
+-- -- | A directory of any external IPs that are currently pointing to this virtual
+-- -- machine instance, for the network interface at <index>. Specifically, provides
+-- -- a list of external IPs served by forwarding rules that direct packets to this
+-- -- instance.
+-- getForwardedIPs
+-- "instance/network-interfaces/<index>/forwarded-ips/"
+
+-- -- | A directory with the scheduling options for the instance.
+-- getScheduling
+-- "instance/scheduling/"
+
+-- -- | The instance's transparent maintenance event behavior setting. This value is
+-- -- set with the @--on_host_maintenance@ flag or via the API.
+-- getOnHostMaintenance
+-- "instance/scheduling/on-host-maintenance"
+
+-- -- | The instance's automatic restart setting. This value is set with the
+-- -- @‑‑automatic_restart@ flag or via the API.
+-- getAutomaticRestart
+-- "instance/scheduling/automatic-restart"
+
+-- -- | The path that indicates that a transparent maintenance event is affecting this instance.
+-- -- See Transparent maintenance notice for details.
+-- getMaintenanceEvent
+-- "instance/maintenance-event"
+
+-- Metadata wait for change
+-- curl "http://metadata.google.internal/computeMetadata/v1/instance/tags?wait_for_change=true"
+
+getMetadataMaybe ::
+  (MonadIO m) =>
+  ByteString ->
+  Manager ->
+  m (Maybe LBS.ByteString)
+getMetadataMaybe path m = do
+  rs <- getMetadata path [404] m
+  if fromEnum (Client.responseStatus rs) == 404
+    then pure Nothing
+    else pure $ Just (Client.responseBody rs)
+
+getMetadataText ::
+  (MonadIO m) =>
+  ByteString ->
+  Manager ->
+  m Text
+getMetadataText path m =
+  LText.toStrict . LText.decodeUtf8 . Client.responseBody
+    <$> getMetadata path [] m
+
+getMetadata ::
+  (MonadIO m) =>
+  -- | The request path.
+  ByteString ->
+  -- | Acceptable status code responses.
+  [Int] ->
+  Manager ->
+  m (Client.Response LBS.ByteString)
+getMetadata path statuses m =
+  liftIO . flip Client.httpLbs m $
+    metadataRequest
+      { Client.path = "/computeMetadata/v1/" <> path,
+        Client.checkResponse = \rq rs ->
+          let c = fromEnum (Client.responseStatus rs)
+           in if (200 <= c && c < 300) || c `elem` statuses
+                then return ()
+                else do
+                  bs <- Client.brReadSome (Client.responseBody rs) 4096
+                  throwIO . HttpExceptionRequest rq $
+                    StatusCodeException (() <$ rs) (LBS.toStrict bs)
+      }
+
+-- | A default @http-client@ 'Client.Request' with the host, port, and headers
+-- set appropriately for @metadata.google.internal@ use.
+metadataRequest :: Client.Request
+metadataRequest =
+  Client.defaultRequest
+    { Client.host = "metadata.google.internal",
+      Client.port = 80,
+      Client.secure = False,
+      Client.method = "GET",
+      Client.requestHeaders = [(metadataFlavorHeader, metadataFlavorDesired)]
+    }
diff --git a/src/Unkai/Env.hs b/src/Unkai/Env.hs
new file mode 100644
--- /dev/null
+++ b/src/Unkai/Env.hs
@@ -0,0 +1,164 @@
+{-# LANGUAGE DataKinds #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE FunctionalDependencies #-}
+{-# LANGUAGE KindSignatures #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+-- |
+-- Module      : Unkai.Env
+-- 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)
+--
+-- Environment and Google specific configuration for the "Unkai" monad.
+module Unkai.Env
+  ( Env (..),
+    HasEnv (..),
+    configure,
+    override,
+    timeout,
+    newEnv,
+    newEnvWith,
+  )
+where
+
+import Control.Lens (Lens', lens, (<>~), (?~))
+import Control.Monad.Catch (MonadCatch)
+import Control.Monad.IO.Class (MonadIO (..))
+import Control.Monad.Reader (MonadReader (local))
+import Data.Function (on)
+import Data.Monoid (Dual (..), Endo (..))
+import Data.Proxy (Proxy (..))
+import GHC.TypeLits (Symbol)
+import Network.HTTP.Client (Manager, newManager)
+import Network.HTTP.Client.TLS (tlsManagerSettings)
+import Unkai.Auth
+import Unkai.Internal.Logger (Logger)
+import Unkai.Types
+
+-- | The environment containing the parameters required to make Google requests.
+data Env (scopes :: [Symbol]) = Env
+  { _envOverride :: !(Dual (Endo ServiceConfig)),
+    _envLogger :: !Logger,
+    _envManager :: !Manager,
+    _envStore :: !(Store scopes)
+  }
+
+-- Note: The strictness annotations aobe are applied to ensure
+-- total field initialisation.
+
+class HasEnv scopes a | a -> scopes where
+  environment :: Lens' a (Env scopes)
+  {-# MINIMAL environment #-}
+
+  -- | The currently applied overrides to all 'Service' configuration.
+  envOverride :: Lens' a (Dual (Endo ServiceConfig))
+
+  -- | The function used to output log messages.
+  envLogger :: Lens' a Logger
+
+  -- | The 'Manager' used to create and manage open HTTP connections.
+  envManager :: Lens' a Manager
+
+  -- | The credential store used to sign requests for authentication with Google.
+  envStore :: Lens' a (Store scopes)
+
+  -- | The authorised OAuth2 scopes.
+  --
+  -- /See:/ 'allow', '!', and the related scopes available for each service.
+  envScopes :: Lens' a (Proxy scopes)
+
+  envOverride = environment . lens _envOverride (\s a -> s {_envOverride = a})
+  envLogger = environment . lens _envLogger (\s a -> s {_envLogger = a})
+  envManager = environment . lens _envManager (\s a -> s {_envManager = a})
+  envStore = environment . lens _envStore (\s a -> s {_envStore = a})
+  envScopes = environment . lens (\_ -> Proxy :: Proxy scopes) (flip allow)
+
+instance HasEnv scopes (Env scopes) where
+  environment = id
+
+-- | Provide a function which will be added to the stack
+-- of overrides, which are applied to all service configurations.
+-- This provides a way to configure any request that is sent using the
+-- modified 'Env'.
+--
+-- /See:/ 'override'.
+configure :: (HasEnv scopes a) => (ServiceConfig -> ServiceConfig) -> a -> a
+configure f = envOverride <>~ Dual (Endo f)
+
+-- | Override a specific 'ServiceConfig'. All requests belonging to the
+-- supplied service will use this configuration instead of the default.
+--
+-- Typically you would override a modified version of the default 'ServiceConfig'
+-- for the desired service:
+--
+-- > override (gmailService & serviceHost .~ "localhost") env
+--
+-- Or when using "Unkai" with "Control.Monad.Reader" or "Control.Lens.Zoom"
+-- and the 'ServiceConfig' lenses:
+--
+-- > local (override (computeService & serviceHost .~ "localhost")) $ do
+-- >    ...
+--
+-- /See:/ 'configure'.
+override :: (HasEnv scopes a) => ServiceConfig -> a -> a
+override s = configure f
+  where
+    f x
+      | on (==) _svcId s x = s
+      | otherwise = x
+
+-- | Scope an action such that any HTTP response will use this timeout value.
+--
+-- Default timeouts are chosen by considering:
+--
+-- * This 'timeout', if set.
+--
+-- * The related 'Service' timeout for the sent request if set. (Default 70s)
+--
+-- * The 'envManager' timeout, if set.
+--
+-- * The 'ClientRequest' timeout. (Default 30s)
+timeout :: (MonadReader r m, HasEnv scopes r) => Seconds -> m a -> m a
+timeout s = local (configure (serviceTimeout ?~ s))
+
+-- | Creates a new environment with a newly initialized 'Manager', without logging.
+-- and Credentials that are determined by calling 'getApplicationDefault'.
+-- Use 'newEnvWith' to supply explicit credentials and a custom HTTP manager.
+--
+-- The 'Allow'ed 'OAuthScope's are used to authorize any @service_account@ that is
+-- found with the appropriate scopes. See the top-level module of each individual
+-- @unkai-*@ library for a list of available scopes, such as
+-- @Unkai.Compute.authComputeScope@.
+-- Lenses from 'HasEnv' can be used to further configure the resulting 'Env'.
+--
+-- /See:/ 'newEnvWith', 'getApplicationDefault'.
+newEnv ::
+  forall scopes m.
+  ( MonadIO m,
+    MonadCatch m,
+    KnownScopes scopes
+  ) =>
+  m (Env scopes)
+newEnv = do
+  m <- liftIO (newManager tlsManagerSettings)
+  c <- getApplicationDefault m
+  newEnvWith c (\_ _ -> pure ()) m
+
+-- | Create a new environment.
+--
+-- /See:/ 'newEnv'.
+newEnvWith ::
+  forall scopes m.
+  ( MonadIO m,
+    KnownScopes scopes
+  ) =>
+  Credentials scopes ->
+  Logger ->
+  Manager ->
+  m (Env scopes)
+newEnvWith c l m =
+  Env mempty l m <$> initStore c l m
diff --git a/src/Unkai/Internal/Auth.hs b/src/Unkai/Internal/Auth.hs
new file mode 100644
--- /dev/null
+++ b/src/Unkai/Internal/Auth.hs
@@ -0,0 +1,270 @@
+{-# 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
diff --git a/src/Unkai/Internal/Body.hs b/src/Unkai/Internal/Body.hs
new file mode 100644
--- /dev/null
+++ b/src/Unkai/Internal/Body.hs
@@ -0,0 +1,41 @@
+{-# LANGUAGE OverloadedStrings #-}
+
+-- |
+-- Module      : Unkai.Internal.Body
+-- 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)
+module Unkai.Internal.Body
+  ( getMIMEType,
+    sourceBody,
+  )
+where
+
+import Control.Monad.IO.Class (MonadIO (..))
+import Data.Maybe (fromMaybe)
+import Data.Text qualified as Text
+import Network.HTTP.Client qualified as Client
+import Network.HTTP.Media (MediaType, parseAccept, (//))
+import Network.Mime qualified as MIME
+import Unkai.Types (GBody (..))
+
+-- | Attempt to calculate the MIME type based on file extension.
+--
+-- Defaults to @application/octet-stream@ if no file extension is recognised.
+getMIMEType :: FilePath -> MediaType
+getMIMEType =
+  fromMaybe ("application" // "octet-stream")
+    . parseAccept
+    . MIME.defaultMimeLookup
+    . Text.takeWhileEnd (/= '/')
+    . Text.pack
+
+-- | Construct a 'GBody' from a 'FilePath'.
+--
+-- This uses 'getMIMEType' to calculate the MIME type from the file extension,
+-- you can use 'bodyContentType' to set a MIME type explicitly.
+-- Keep the file size fixed between creating the body and sending it.
+sourceBody :: (MonadIO m) => FilePath -> m GBody
+sourceBody f = GBody (getMIMEType f) <$> liftIO (Client.streamFile f)
diff --git a/src/Unkai/Internal/HTTP.hs b/src/Unkai/Internal/HTTP.hs
new file mode 100644
--- /dev/null
+++ b/src/Unkai/Internal/HTTP.hs
@@ -0,0 +1,171 @@
+{-# LANGUAGE DataKinds #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE RecordWildCards #-}
+{-# LANGUAGE TypeFamilies #-}
+
+-- |
+-- Module      : Unkai.Internal.HTTP
+-- 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)
+module Unkai.Internal.HTTP
+  ( unsafeRequest,
+    getContent,
+  )
+where
+
+import Control.Exception (Exception, Handler (..), SomeException, catch, catches, throwIO)
+import Control.Lens ((%~), (&))
+import Control.Monad.IO.Class (MonadIO (..))
+import Control.Monad.Trans.Resource (MonadResource (..), ReleaseKey, allocate, release, transResourceT)
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as BS
+import Data.Monoid (Dual (..), Endo (..))
+import Data.Text.Encoding qualified as Text
+import Data.Text.Lazy qualified as LText
+import Data.Text.Lazy.Builder qualified as Build
+import GHC.Exts (toList)
+import Network.HTTP.Client (RequestBody, responseBody, responseHeaders, responseStatus)
+import Network.HTTP.Client qualified as Client
+import Network.HTTP.Media (RenderHeader (..))
+import Network.HTTP.Types
+import Streamly.Data.Stream qualified as Stream
+import Unkai.Auth (KnownScopes, authorize)
+import Unkai.Env (Env (..))
+import Unkai.Internal.Logger (ToLog (build), logDebug, logError)
+import Unkai.Internal.Multipart
+import Unkai.Types
+
+-- Keep exceptions from application loggers outside the library error contract,
+-- even when the exception has one of the types we handle below.
+newtype LoggerCallbackException = LoggerCallbackException SomeException
+  deriving stock (Show)
+
+instance Exception LoggerCallbackException
+
+unsafeRequest ::
+  ( MonadResource m,
+    GoogleRequest a,
+    KnownScopes scopes
+  ) =>
+  Env scopes ->
+  a ->
+  m (Either Error (Rs a))
+unsafeRequest Env {..} x =
+  liftResourceT (transResourceT (`catches` handlers) go)
+  where
+    Request {..} = _cliRequest
+
+    ServiceConfig {..} = _cliService
+
+    GClient {..} =
+      requestClient x
+        & clientService %~ appEndo (getDual _envOverride)
+
+    logger level message =
+      _envLogger level message `catch` (throwIO . LoggerCallbackException)
+
+    go = do
+      (ct, b) <- getContent _rqBody
+      rq <- authorize (request ct b) _envStore logger _envManager
+
+      logDebug logger rq -- debug:ClientRequest
+      (key, response) <- allocate (Client.responseOpen rq _envManager) Client.responseClose
+      let rs = fmap (bodyStream key) response
+
+      logDebug logger rs -- debug:ClientResponse
+      statusCheck rs
+
+      r <- _cliResponse (responseBody rs)
+
+      case r of
+        Right y -> pure (Right y)
+        Left (e, bs) -> do
+          logError logger $ "[Client Error] Invalid response at status=" <> build (statusCode (responseStatus rs))
+          pure . Left . SerializeError $
+            SerializeError'
+              { _serializeId = _svcId,
+                _serializeHeaders = responseHeaders rs,
+                _serializeStatus = responseStatus rs,
+                _serializeMessage = e,
+                _serializeBody = Just bs
+              }
+
+    request ct b =
+      Client.defaultRequest
+        { Client.host = _svcHost,
+          Client.port = _svcPort,
+          Client.secure = _svcSecure,
+          Client.responseTimeout = timeout,
+          Client.method = _cliMethod,
+          Client.path = path,
+          Client.queryString = renderQuery True (toList _rqQuery),
+          Client.requestHeaders = accept (ct (toList _rqHeaders)),
+          Client.requestBody = b
+        }
+
+    accept
+      | Just t <- _cliAccept = ((hAccept, renderHeader t) :)
+      | otherwise = id
+
+    path =
+      Text.encodeUtf8
+        . LText.toStrict
+        $ Build.toLazyText (_svcPath <> _rqPath)
+
+    statusCheck rs
+      | _cliCheck (responseStatus rs) = pure ()
+      | otherwise = do
+          logError logger $ "[Client Error] Service status=" <> build (statusCode (responseStatus rs))
+          b <- sinkLBS (responseBody rs)
+
+          liftIO . throwIO . ServiceError $
+            ServiceError'
+              { _serviceId = _svcId,
+                _serviceStatus = responseStatus rs,
+                _serviceHeaders = responseHeaders rs,
+                _serviceBody = Just b
+              }
+
+    timeout =
+      maybe
+        Client.responseTimeoutNone
+        (Client.responseTimeoutMicro . microseconds)
+        _svcTimeout
+
+    handlers =
+      [ Handler $ \(LoggerCallbackException cause) -> throwIO cause,
+        Handler $ err,
+        Handler $ err . AuthenticationError,
+        Handler $ \cause -> do
+          logError _envLogger ("[Client Error] HTTP transport failed" :: ByteString)
+          err (TransportError cause)
+      ]
+      where
+        err e = return (Left e)
+
+bodyStream :: ReleaseKey -> Client.BodyReader -> Stream
+bodyStream key = Stream.unfoldrM step
+  where
+    step reader = do
+      chunk <- liftIO (Client.brRead reader)
+      if BS.null chunk
+        then Nothing <$ release key
+        else pure (Just (chunk, reader))
+
+getContent ::
+  (MonadIO m) =>
+  [GBody] ->
+  m ([Header] -> [Header], RequestBody)
+getContent [] = pure (id, mempty)
+getContent [GBody t s] = pure (((hContentType, renderHeader t) :), s)
+getContent bs = do
+  b <- genBoundary
+  pure
+    ( (multipartHeader b :),
+      renderParts b bs
+    )
diff --git a/src/Unkai/Internal/Logger.hs b/src/Unkai/Internal/Logger.hs
new file mode 100644
--- /dev/null
+++ b/src/Unkai/Internal/Logger.hs
@@ -0,0 +1,101 @@
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE RecordWildCards #-}
+
+-- |
+-- Module      : Unkai.Internal.Logger
+-- 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)
+--
+-- Types and functions for constructing loggers and emitting log messages.
+module Unkai.Internal.Logger
+  ( -- * Constructing a Logger
+    Logger,
+    newLogger,
+
+    -- * Levels
+    LogLevel (..),
+    logError,
+    logDebug,
+
+    -- * Building Messages
+    ToLog (..),
+  )
+where
+
+import Control.Monad (when)
+import Control.Monad.IO.Class (MonadIO (..))
+import Data.ByteString qualified as BS
+import Data.ByteString.Builder (Builder)
+import Data.ByteString.Builder qualified as Build
+import Network.HTTP.Client qualified as HTTP
+import Network.HTTP.Types (parseQuery, statusCode)
+import System.IO
+
+-- | A callback for informational and diagnostic messages.
+type Logger = LogLevel -> Builder -> IO ()
+
+data LogLevel
+  = -- | Informational messages supplied by the application.
+    Info
+  | -- | Error messages.
+    Error
+  | -- | Request and response summaries.
+    Debug
+  | -- | The most verbose log threshold. Library diagnostics omit credentials and payloads.
+    Trace
+  deriving stock (Eq, Ord, Enum, Show)
+
+-- | Write messages at or below the configured threshold to a handle.
+newLogger :: (MonadIO m) => LogLevel -> Handle -> m Logger
+newLogger threshold handle = liftIO $ do
+  hSetBinaryMode handle True
+  hSetBuffering handle LineBuffering
+  return $ \level message ->
+    when (threshold >= level) $
+      Build.hPutBuilder handle (message <> "\n")
+
+logError, logDebug :: (MonadIO m, ToLog a) => Logger -> a -> m ()
+logError callback = liftIO . callback Error . build
+logDebug callback = liftIO . callback Debug . build
+
+class ToLog a where
+  build :: a -> Builder
+
+instance ToLog Builder where build = id
+
+instance ToLog BS.ByteString where build = Build.byteString
+
+instance ToLog Int where build = Build.intDec
+
+-- Headers, path captures, query values and payloads can all carry secrets.
+-- Keep the summary independent of their contents.
+instance ToLog HTTP.Request where
+  build req =
+    "[Client Request] method="
+      <> build (HTTP.method req)
+      <> " headers="
+      <> build (length (HTTP.requestHeaders req))
+      <> " queryParameters="
+      <> build (length (parseQuery (HTTP.queryString req)))
+      <> " body="
+      <> summarizeBody (HTTP.requestBody req)
+    where
+      summarizeBody = \case
+        HTTP.RequestBodyBS bytes -> build (BS.length bytes) <> " bytes"
+        HTTP.RequestBodyLBS _ -> "lazy bytes"
+        HTTP.RequestBodyBuilder size _ -> Build.int64Dec size <> " bytes"
+        HTTP.RequestBodyStream size _ -> Build.int64Dec size <> " streamed bytes"
+        HTTP.RequestBodyStreamChunked _ -> "chunked stream"
+        HTTP.RequestBodyIO _ -> "deferred"
+
+instance ToLog (HTTP.Response a) where
+  build resp =
+    "[Client Response] status="
+      <> build (statusCode (HTTP.responseStatus resp))
+      <> " headers="
+      <> build (length (HTTP.responseHeaders resp))
diff --git a/src/Unkai/Internal/Multipart.hs b/src/Unkai/Internal/Multipart.hs
new file mode 100644
--- /dev/null
+++ b/src/Unkai/Internal/Multipart.hs
@@ -0,0 +1,76 @@
+{-# LANGUAGE OverloadedStrings #-}
+
+-- |
+-- Module      : Unkai.Internal.Multipart
+-- 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)
+module Unkai.Internal.Multipart
+  ( Boundary (..),
+    genBoundary,
+    multipartHeader,
+    start,
+    part,
+    copy,
+    renderParts,
+  )
+where
+
+import Control.Monad.IO.Class (MonadIO (..))
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as BS
+import Data.ByteString.Builder.Extra (byteStringCopy)
+import Network.HTTP.Client
+import Network.HTTP.Client.MultipartFormData (webkitBoundary)
+import Network.HTTP.Media (RenderHeader (..))
+import Network.HTTP.Types (Header, hContentType)
+import Unkai.Types (GBody (..))
+
+-- POST /upload/drive/v2/files?uploadType=multipart HTTP/1.1
+-- Host: www.googleapis.com
+-- Authorization: Bearer your_auth_token
+-- Content-Type: multipart/related; boundary="foo_bar_baz"
+-- Content-Length: number_of_bytes_in_entire_request_body
+
+-- --foo_bar_baz
+-- Content-Type: application/json; charset=UTF-8N
+-- {
+--   "title": "My File"
+-- }
+-- --foo_bar_baz
+-- Content-Type: image/jpeg
+-- JPEG data
+-- --foo_bar_baz--
+
+newtype Boundary = Boundary ByteString
+
+genBoundary :: (MonadIO m) => m Boundary
+genBoundary = Boundary <$> liftIO webkitBoundary
+
+multipartHeader :: Boundary -> Header
+multipartHeader (Boundary bs) =
+  ( hContentType,
+    "multipart/related; boundary=" <> bs
+  )
+
+start :: Boundary -> RequestBody
+start (Boundary bs) = copy "--" <> copy bs <> copy "\r\n"
+
+part :: Boundary -> RequestBody
+part (Boundary bs) = copy "--" <> copy bs <> copy "--\r\n"
+
+copy :: ByteString -> RequestBody
+copy bs = RequestBodyBuilder (fromIntegral (BS.length bs)) (byteStringCopy bs)
+
+renderParts :: Boundary -> [GBody] -> RequestBody
+renderParts b = (<> part b) . foldMap go
+  where
+    go (GBody ct x) =
+      start b
+        <> copy "Content-Type: "
+        <> copy (renderHeader ct)
+        <> copy "\r\n\r\n"
+        <> x
+        <> copy "\r\n"
diff --git a/test/Main.hs b/test/Main.hs
new file mode 100644
--- /dev/null
+++ b/test/Main.hs
@@ -0,0 +1,537 @@
+module Main (main) where
+
+import Control.Concurrent (forkFinally, newEmptyMVar, putMVar, takeMVar)
+import Control.Exception (SomeException, bracket, fromException, throwIO, try)
+import Control.Lens ((&), (.~), (?~))
+import Control.Monad (forM_, replicateM_, void)
+import Control.Monad.IO.Class (liftIO)
+import Data.Aeson (Value, eitherDecode, object, (.=))
+import Data.Aeson qualified as JSON
+import Data.Aeson.KeyMap qualified as KeyMap
+import Data.Bits ((.&.))
+import Data.ByteString qualified as BS
+import Data.ByteString.Builder (toLazyByteString)
+import Data.ByteString.Lazy qualified as LBS
+import Data.Generics.Labels ()
+import Data.HashMap.Strict qualified as HashMap
+import Data.IORef
+import Data.List (partition)
+import Data.List.NonEmpty (NonEmpty (..))
+import Data.Text (Text)
+import Network.HTTP.Client qualified as HTTP
+import Network.HTTP.Types
+import Network.Wai qualified as Wai
+import System.Directory
+import System.Environment (lookupEnv, setEnv, unsetEnv)
+import System.FilePath ((</>))
+import System.IO (IOMode (WriteMode), withBinaryFile)
+import System.Posix.Files (fileMode, getFileStatus, setFileMode)
+import Test.Tasty
+import Test.Tasty.HUnit
+import Test.Unkai.MockServer
+import Test.Unkai.Streaming (streamingTests)
+import Unkai
+import Unkai.Auth
+import Unkai.Auth.ApplicationDefault (fromJSONCredentials)
+import Unkai.Compute.Metadata qualified as Metadata
+import Unkai.Storage qualified as Storage
+
+type StorageEnv = Env '[Storage.Devstorage'ReadWrite]
+
+main :: IO ()
+main =
+  defaultMain $
+    testGroup
+      "runtime"
+      [ testCase "service diagnostics omit authorization, headers and bodies" serviceLogs,
+        testCase "token diagnostics omit form and response data at Debug and Trace" tokenLogs,
+        testCase "explicit ADC errors stop discovery and unset ADC falls back in order" discovery,
+        testCase "ADC save is private, interoperable and replaces atomically" saveCredentials,
+        testCase "ADC no-overwrite publishes exactly one concurrent save" concurrentSave,
+        testCase "failed ADC save preserves the old file and removes its temporary file" failedSave,
+        testCase "rotated refresh token survives omission and a failed refresh" refreshRotation,
+        testCase "all public request entry points report the typed authentication error" authErrors,
+        testCase "token file failures remain typed credential errors" tokenFileErrors,
+        testCase "optional metadata accepts 404 and rejects 500; required metadata rejects 404" metadata,
+        testCase "transport failures, malformed JSON and service errors retain their results" responseErrors,
+        testCase "a truncated download fails during scoped body consumption" truncatedDownload,
+        testCase "caller logger exceptions escape sendEither" loggerException,
+        testCase "download encodes the raw object segment and binds the query separately" wireDownload,
+        testCase "move, copy, rewrite and folder rename bind distinct source and destination names" wireActions,
+        testCase "upload protocol is unique and multipart contains metadata and media" wireUpload,
+        testCase "PATCH distinguishes omitted, assigned, cleared, nested and map-key fields" wirePatch,
+        testCase "operation-specific inputs encode compose, bucket names and empty policy bindings" wireRequired,
+        streamingTests
+      ]
+
+getObject :: Storage.StorageObjectsGet
+getObject = Storage.newStorageObjectsGet "bucket" "reports/q1.csv"
+
+insertObject :: Storage.StorageObjectsInsert
+insertObject = Storage.newStorageObjectsInsert "bucket" Storage.newObject
+
+user :: AuthorizedUser
+user = AuthorizedUser "fixture-client" "original+refresh&marker" "secret+marker&value"
+
+tokenPath :: BS.ByteString
+tokenPath = "/oauth2/v4/token"
+
+isTokenRequest :: RecordedRequest -> Bool
+isTokenRequest = (== tokenPath) . path
+
+quiet :: Logger
+quiet _ _ = pure ()
+
+captureLogs :: IO (Logger, IO LBS.ByteString)
+captureLogs = do
+  logs <- newIORef []
+  pure (\_ message -> modifyIORef' logs (toLazyByteString message :), LBS.concat . reverse <$> readIORef logs)
+
+contains :: LBS.ByteString -> LBS.ByteString -> Assertion
+contains needle haystack =
+  assertBool ("expected " <> show needle <> " in " <> show haystack) $
+    LBS.toStrict needle `BS.isInfixOf` LBS.toStrict haystack
+
+omits :: LBS.ByteString -> LBS.ByteString -> Assertion
+omits needle haystack =
+  assertBool ("unexpected marker " <> show needle) $
+    not (LBS.toStrict needle `BS.isInfixOf` LBS.toStrict haystack)
+
+withVariable :: String -> Maybe String -> IO a -> IO a
+withVariable name value action =
+  bracket (lookupEnv name) set $ \_ -> set value >> action
+  where
+    set = maybe (unsetEnv name) (setEnv name)
+
+newFileEnv :: HTTP.Manager -> FilePath -> Logger -> IO StorageEnv
+newFileEnv manager file logger = newEnvWith (FromTokenFile file) logger manager
+
+newUserEnv :: HTTP.Manager -> Logger -> IO StorageEnv
+newUserEnv manager logger = newEnvWith (FromUser user) logger manager
+
+assertRight :: (Show e) => Either e a -> IO a
+assertRight = either (\e -> assertFailure (show e) >> fail "expected Right") pure
+
+assertAuthError :: (AuthError -> Bool) -> Either AuthError a -> Assertion
+assertAuthError predicate result = case result of
+  Left failure -> assertBool (show failure) (predicate failure)
+  Right _ -> assertFailure "expected an authentication exception"
+
+serviceLogs :: Assertion
+serviceLogs = withTokenFile $ \file ->
+  withServer (const (pure response)) $ \manager requests -> do
+    (logger, logs) <- captureLogs
+    env <- newFileEnv manager file logger
+    _ <- runResourceT (send env getObject)
+    let metadataBody = Storage.newObject & #name ?~ "request-body-marker"
+        request = Storage.newStorageObjectsInsert "bucket" metadataBody & #userProject ?~ "query-value-marker"
+    _ <- runResourceT (send env request)
+    captured <- requests
+    map (lookup hAuthorization . headers) captured @?= replicate 2 (Just "Bearer bearer-fixture-marker")
+    output <- logs
+    contains "method=GET" output
+    contains "status=200" output
+    forM_ ["bearer-fixture-marker", "response-header-marker", "response-body-marker", "request-body-marker", "query-value-marker"] (`omits` output)
+  where
+    response = Wai.responseLBS status200 [("X-Fixture", "response-header-marker")] "{\"name\":\"response-body-marker\"}"
+
+tokenLogs :: Assertion
+tokenLogs = withDirectory $ \dir ->
+  forM_ [Debug, Trace] $ \level -> do
+    next <- newIORef [token "-1" "", invalidGrant, jsonResponse status200 "{\"access_token\":\"malformed-token-marker\",\"expires_in\":false}"]
+    let respond request
+          | isTokenRequest request = atomicModifyIORef' next $ \case
+              response : rest -> (rest, response)
+              [] -> ([], jsonResponse status500 "{}")
+          | otherwise = pure (jsonResponse status200 "{}")
+        logFile = dir </> show level
+    withServer respond $ \manager requests -> do
+      (capture, logs) <- captureLogs
+      withBinaryFile logFile WriteMode $ \handle -> do
+        logger <- newLogger level handle
+        env <- newUserEnv manager (\severity msg -> capture severity msg >> logger severity msg)
+        result <- runResourceT (sendEither env getObject)
+        assertRefreshError result
+        malformed <- runResourceT (sendEither env getObject)
+        case malformed of
+          Left (AuthenticationError (TokenRefreshError status _ _)) -> status @?= status200
+          Left other -> assertFailure (show other)
+          Right _ -> assertFailure "expected a malformed token error"
+      captured <- requests
+      length captured @?= 3
+      forM_ captured $ \request -> do
+        lookup "refresh_token" (form request) @?= Just "original+refresh&marker"
+        lookup "client_secret" (form request) @?= Just "secret+marker&value"
+      output <- logs
+      contains "[Token Request] method=POST" output
+      contains "[Token Response] status=200" output
+      contains "[Token Response] status=400" output
+      contains "[Token Error] Invalid response at status=200" output
+      forM_ secrets (`omits` output)
+      written <- LBS.readFile logFile
+      contains "[Token Response] status=400" written
+      forM_ secrets (`omits` written)
+  where
+    secrets = ["issued-marker", "original", "refresh%26marker", "secret+marker", "secret%2Bmarker", "echoed-credential-marker", "malformed-token-marker"]
+
+form :: RecordedRequest -> SimpleQuery
+form = parseSimpleQuery . LBS.toStrict . body
+
+token :: LBS.ByteString -> LBS.ByteString -> Wai.Response
+token expiry extra =
+  jsonResponse status200 $
+    "{\"access_token\":\"issued-marker\",\"expires_in\":" <> expiry <> extra <> "}"
+
+invalidGrant :: Wai.Response
+invalidGrant =
+  jsonResponse
+    status400
+    "{\"error\":\"invalid_grant\",\"error_description\":\"echoed-credential-marker\"}"
+
+assertRefreshError :: Either Error a -> Assertion
+assertRefreshError result = case result of
+  Left (AuthenticationError (TokenRefreshError status code description)) -> do
+    status @?= status400
+    code @?= "invalid_grant"
+    description @?= Just "echoed-credential-marker"
+  Left other -> assertFailure (show other)
+  Right _ -> assertFailure "expected AuthenticationError"
+
+discovery :: Assertion
+discovery = withDirectory $ \dir ->
+  withVariable cloudSDKConfigDir (Just dir) $
+    withVariable checkGCEVar Nothing $
+      withServer (const (pure gce)) $ \manager requests -> do
+        let wellKnown = dir </> "application_default_credentials.json"
+            missing = dir </> "missing"
+            invalid = dir </> "invalid"
+        LBS.writeFile invalid "invalid JSON"
+        withVariable defaultCredentialsFile Nothing (saveAuthorizedUserToWellKnownPath False user)
+        withVariable defaultCredentialsFile (Just missing) $ do
+          result <- try (getApplicationDefault manager)
+          assertAuthError (\case MissingFileError file -> file == missing; _ -> False) result
+        withVariable defaultCredentialsFile (Just invalid) $ do
+          result <- try (getApplicationDefault manager)
+          assertAuthError (\case InvalidFileError file _ -> file == invalid; _ -> False) result
+        withVariable defaultCredentialsFile (Just dir) $ do
+          result <- try (getApplicationDefault manager)
+          assertAuthError (\case CredentialFileReadError file _ -> file == dir; _ -> False) result
+        withVariable defaultCredentialsFile Nothing $ do
+          getApplicationDefault manager >>= assertUser user
+          length <$> requests >>= (@?= 0)
+          removeFile wellKnown
+          getApplicationDefault manager >>= \case
+            FromMetadata "default" -> pure ()
+            _ -> assertFailure "expected default metadata identity"
+          length <$> requests >>= (@?= 1)
+  where
+    gce = Wai.responseLBS status200 [("Metadata-Flavor", "Google")] ""
+
+assertUser :: AuthorizedUser -> Credentials s -> Assertion
+assertUser expected = \case
+  FromUser actual -> actual @?= expected
+  _ -> assertFailure "expected authorized-user credentials"
+
+assertPrivate :: FilePath -> Assertion
+assertPrivate file = do
+  status <- getFileStatus file
+  fileMode status .&. 0o777 @?= 0o600
+
+saveCredentials :: Assertion
+saveCredentials = withDirectory $ \dir -> do
+  let file = dir </> "adc.json"
+      replacement = user {_userRefresh = "replacement"}
+  saveAuthorizedUser file False user
+  assertPrivate file
+  bytes <- LBS.readFile file
+  let document =
+        object
+          [ "type" .= ("authorized_user" :: Text),
+            "client_id" .= _userId user,
+            "client_secret" .= _userSecret user,
+            "refresh_token" .= _userRefresh user
+          ]
+  (eitherDecode bytes :: Either String Value) @?= Right document
+  fromFilePath file >>= assertUser user
+  legacy <- assertRight (fromJSONCredentials "{\"client_id\":\"fixture-client\",\"client_secret\":\"secret+marker&value\",\"refresh_token\":\"original+refresh&marker\"}")
+  assertUser user legacy
+  setFileMode file 0o644
+  saveAuthorizedUser file True replacement
+  assertPrivate file
+  fromFilePath file >>= assertUser replacement
+
+concurrentSave :: Assertion
+concurrentSave = withDirectory $ \dir -> do
+  let file = dir </> "adc.json"
+      contenders = [user, user {_userRefresh = "contender"}]
+  start <- newEmptyMVar
+  waiters <- mapM (startWriter start file) contenders
+  replicateM_ 2 (putMVar start ())
+  results <- mapM takeMVar waiters
+  case partition (either (const False) (const True) . snd) (zip contenders results) of
+    ([(winner, Right ())], [(_, Left exception)]) -> do
+      case fromException exception of
+        Just (FileExistError target) -> target @?= file
+        _ -> assertFailure (show exception)
+      fromFilePath file >>= assertUser winner
+    _ -> assertFailure ("expected one winner and one existing-file error, got " <> show results)
+  assertPrivate file
+  listDirectory dir >>= (@?= ["adc.json"])
+  where
+    startWriter start file candidate = do
+      result <- newEmptyMVar
+      _ <- forkFinally (takeMVar start >> saveAuthorizedUser file False candidate) (putMVar result)
+      pure result
+
+failedSave :: Assertion
+failedSave = withDirectory $ \dir -> do
+  let file = dir </> "adc.json"
+  saveAuthorizedUser file False user
+  before <- LBS.readFile file
+  result <- try (saveAuthorizedUser file True (error "fixture encoding failure"))
+  case (result :: Either SomeException ()) of
+    Left _ -> pure ()
+    Right _ -> assertFailure "expected failure before publication"
+  LBS.readFile file >>= (@?= before)
+  assertPrivate file
+  listDirectory dir >>= (@?= ["adc.json"])
+
+refreshRotation :: Assertion
+refreshRotation = do
+  responses <- newIORef [token "-1" ",\"refresh_token\":\"rotated+marker&value\"", invalidGrant, token "-1" "", token "3600" ""]
+  let respond request
+        | isTokenRequest request = atomicModifyIORef' responses $ \case
+            response : rest -> (rest, response)
+            [] -> ([], jsonResponse status500 "{}")
+        | otherwise = pure (jsonResponse status200 "{}")
+  withServer respond $ \manager requests -> do
+    env <- newUserEnv manager quiet
+    runResourceT (sendEither env getObject) >>= assertRefreshError
+    replicateM_ 2 (runResourceT (send env getObject))
+    recorded <- requests
+    let (exchanges, calls) = partition isTokenRequest recorded
+    map (lookup "refresh_token" . form) exchanges
+      @?= map Just ["original+refresh&marker", "rotated+marker&value", "rotated+marker&value", "rotated+marker&value"]
+    map (lookup hAuthorization . headers) calls @?= replicate 2 (Just "Bearer issued-marker")
+
+authErrors :: Assertion
+authErrors = do
+  first <- newIORef True
+  let respond _ = do
+        initial <- atomicModifyIORef' first (\x -> (False, x))
+        pure $ if initial then token "-1" "" else invalidGrant
+  withServer respond $ \manager requests -> do
+    env <- newUserEnv manager quiet
+    runResourceT (sendEither env getObject) >>= assertRefreshError
+    runResourceT (uploadEither env insertObject "media") >>= assertRefreshError
+    runResourceT (downloadEither env getObject) >>= assertRefreshError
+    try (runResourceT (send env getObject)) >>= assertRefreshError
+    try (runResourceT (upload env insertObject "media")) >>= assertRefreshError
+    try (runResourceT (download env getObject)) >>= assertRefreshError
+    try (newUserEnv manager quiet) >>= assertAuthError (\case TokenRefreshError _ "invalid_grant" _ -> True; _ -> False)
+    recorded <- requests
+    length recorded @?= 8
+    assertBool "authentication failed before service dispatch" (all isTokenRequest recorded)
+
+tokenFileErrors :: Assertion
+tokenFileErrors = withTokenFile $ \file ->
+  withServer (const (pure (jsonResponse status200 "{}"))) $ \manager _ -> do
+    removeFile file
+    try (newFileEnv manager file quiet) >>= assertAuthError (\case MissingFileError target -> target == file; _ -> False)
+    LBS.writeFile file (LBS.pack [255])
+    try (newFileEnv manager file quiet) >>= assertAuthError (\case InvalidFileError target _ -> target == file; _ -> False)
+
+metadata :: Assertion
+metadata =
+  withServer respond $ \manager _ -> do
+    Metadata.getProjectAttribute "present" manager >>= (@?= Just "attribute")
+    Metadata.getInstanceAttribute "missing" manager >>= (@?= Nothing)
+    expectFailure status500 (Metadata.getInstanceAttribute "error" manager)
+    expectFailure status404 (Metadata.getProjectId manager)
+  where
+    respond request = pure $
+      case path request of
+        "/computeMetadata/v1/project/attributes/present" -> jsonResponse status200 "attribute"
+        "/computeMetadata/v1/instance/attributes/error" -> jsonResponse status500 "error"
+        _ -> jsonResponse status404 "missing"
+    expectFailure status action =
+      try action >>= \case
+        Left (HTTP.HttpExceptionRequest _ (HTTP.StatusCodeException resp _)) -> HTTP.responseStatus resp @?= status
+        Left other -> assertFailure (show other)
+        Right _ -> assertFailure "expected a metadata status exception"
+
+responseErrors :: Assertion
+responseErrors = withTokenFile $ \file ->
+  withServer respond $ \manager _ -> do
+    (logger, logs) <- captureLogs
+    env <- newFileEnv manager file logger
+    runResourceT (sendEither env getObject) >>= \case
+      Left (SerializeError failure) -> do
+        _serializeStatus failure @?= status200
+        _serializeBody failure @?= Just "malformed"
+      _ -> assertFailure "expected SerializeError"
+    runResourceT (sendEither env (Storage.newStorageObjectsGet "bucket" "missing")) >>= \case
+      Left (ServiceError failure) -> do
+        _serviceStatus failure @?= status404
+        _serviceBody failure @?= Just "missing"
+      _ -> assertFailure "expected ServiceError"
+    broken <- HTTP.newManager HTTP.defaultManagerSettings
+    let unreachable = configure ((serviceHost .~ "127.0.0.1") . (servicePort .~ 0) . (serviceSecure .~ False)) env
+    runResourceT (sendEither (envManager .~ broken $ unreachable) getObject) >>= \case
+      Left (TransportError _) -> pure ()
+      _ -> assertFailure "expected TransportError"
+    output <- logs
+    contains "[Client Error] Invalid response at status=200" output
+    contains "[Client Error] Service status=404" output
+    contains "[Client Error] HTTP transport failed" output
+    omits "malformed" output
+  where
+    respond request =
+      pure $
+        if path request == "/storage/v1/b/bucket/o/missing"
+          then jsonResponse status404 "missing"
+          else jsonResponse status200 "malformed"
+
+truncatedDownload :: Assertion
+truncatedDownload = withTokenFile $ \file ->
+  withServer (const (pure response)) $ \manager _ -> do
+    env <- newFileEnv manager file quiet
+    receivedStream <- newIORef False
+    result <- try . runResourceT $ do
+      stream <- downloadEither env getObject >>= liftIO . assertRight
+      liftIO (writeIORef receivedStream True)
+      sinkLBS stream
+    readIORef receivedStream >>= (@?= True)
+    case result of
+      Left (HTTP.HttpExceptionRequest _ (HTTP.ResponseBodyTooShort 10 3)) -> pure ()
+      Left other -> assertFailure (show other)
+      Right _ -> assertFailure "expected body consumption to fail"
+  where
+    response =
+      Wai.responseRaw
+        (\_ write -> write "HTTP/1.1 200 OK\r\nContent-Length: 10\r\nConnection: close\r\n\r\nabc")
+        (jsonResponse status500 "")
+
+loggerException :: Assertion
+loggerException = withTokenFile $ \file ->
+  withServer (const (pure (jsonResponse status200 "{}"))) $ \manager _ -> do
+    env <- newFileEnv manager file (\_ _ -> throwIO (MissingFileError "caller logger"))
+    outcome <- try (runResourceT (sendEither env getObject))
+    case outcome of
+      Left (MissingFileError fileName) -> fileName @?= "caller logger"
+      Left other -> assertFailure (show other)
+      Right _ -> assertFailure "expected caller exception"
+
+wireDownload :: Assertion
+wireDownload = withTokenFile $ \file ->
+  withServer (const (pure (Wai.responseLBS status200 [] "download contents"))) $ \manager requests -> do
+    env <- newFileEnv manager file quiet
+    let specialName = Storage.newStorageObjectsGet "bucket" "reports/q1%2F á?.csv" & #userProject ?~ "billing / +"
+    forM_ [getObject, specialName] $ \request ->
+      runResourceT (download env request >>= sinkLBS) >>= (@?= "download contents")
+    recorded <- requests
+    map path recorded @?= ["/storage/v1/b/bucket/o/reports%2Fq1.csv", "/storage/v1/b/bucket/o/reports%2Fq1%252F%20%C3%A1%3F.csv"]
+    map (lookup "alt" . query) recorded @?= replicate 2 (Just (Just "media"))
+    map (lookup "userProject" . query) recorded @?= [Nothing, Just (Just "billing / +")]
+
+wireActions :: Assertion
+wireActions = withTokenFile $ \file ->
+  withServer (const (pure (jsonResponse status200 "{}"))) $ \manager requests -> do
+    env <- newFileEnv manager file quiet
+    runResourceT $ do
+      void (send env (Storage.newStorageObjectsMove "b" "old" "new"))
+      void (send env (Storage.newStorageObjectsCopy "source-b" "source-o" "target-b" "target-o" Storage.newObject))
+      void (send env (Storage.newStorageObjectsRewrite "rewrite-b" "rewrite-o" "out-b" "out-o" Storage.newObject))
+      void (send env (Storage.newStorageFoldersRename "b" "from/" "to/"))
+    captured <- requests
+    map path captured
+      @?= [ "/storage/v1/b/b/o/old/moveTo/o/new",
+            "/storage/v1/b/source-b/o/source-o/copyTo/b/target-b/o/target-o",
+            "/storage/v1/b/rewrite-b/o/rewrite-o/rewriteTo/b/out-b/o/out-o",
+            "/storage/v1/b/b/folders/from%2F/renameTo/folders/to%2F"
+          ]
+
+wireUpload :: Assertion
+wireUpload = withTokenFile $ \file ->
+  withServer (const (pure (jsonResponse status200 "{}"))) $ \manager requests ->
+    withDirectory $ \directory -> do
+      env <- newFileEnv manager file quiet
+      let metadataBody = Storage.newObject & #name ?~ "upload-file.txt"
+          request = Storage.newStorageObjectsInsert "bucket" metadataBody
+          source = directory </> "upload-file.txt"
+      LBS.writeFile source "media fixture"
+      media <- sourceBody source
+      runResourceT $ do
+        void (send env request)
+        void (upload env request media)
+      requests >>= \case
+        [json, multipart] -> do
+          path json @?= "/storage/v1/b/bucket/o"
+          protocol json @?= []
+          path multipart @?= "/upload/storage/v1/b/bucket/o"
+          method multipart @?= methodPost
+          protocol multipart @?= [("uploadType", Just "multipart")]
+          case lookup hContentType (headers multipart) of
+            Just value -> contains "multipart/related; boundary=" (LBS.fromStrict value)
+            Nothing -> assertFailure "missing multipart content type"
+          forM_
+            ["Content-Type: application/json", "\"name\":\"upload-file.txt\"", "Content-Type: text/plain", "media fixture"]
+            (`contains` body multipart)
+        _ -> assertFailure "expected one JSON request and one upload"
+  where
+    protocol = filter ((== "uploadType") . fst) . query
+
+wirePatch :: Assertion
+wirePatch = withTokenFile $ \file ->
+  withServer (const (pure (jsonResponse status200 "{}"))) $ \manager requests -> do
+    env <- newEnvWith (FromTokenFile file) quiet manager :: IO (Env '[Storage.Devstorage'FullControl])
+    let entries = Storage.newObject_MetadataPatch (HashMap.fromList [("keep", Just "updated"), ("drop", Nothing)])
+        base = Storage.newObjectPatch
+        updated = base & #contentType .~ Set "text/csv" & #metadata .~ Set entries
+        cleared = base & #contentType .~ Clear & #metadata .~ Clear
+        billing = Storage.newBucket_BillingPatch & #requesterPays .~ Set True
+        nested = Storage.newBucketPatch & #billing .~ Set billing
+        integerString = base & #generation .~ Set 42
+    runResourceT $ do
+      forM_ [base, updated, cleared, integerString] $ \patch ->
+        void (send env (Storage.newStorageObjectsPatch "bucket" "reports/q1.csv" patch))
+      void (send env (Storage.newStorageBucketsPatch "bucket" nested))
+    captured <- requests
+    map method captured @?= replicate 5 methodPatch
+    map path captured @?= replicate 4 "/storage/v1/b/bucket/o/reports%2Fq1.csv" ++ ["/storage/v1/b/bucket"]
+    expected <-
+      mapM
+        (assertRight . eitherDecode)
+        [ "{}",
+          "{\"contentType\":\"text/csv\",\"metadata\":{\"keep\":\"updated\",\"drop\":null}}",
+          "{\"contentType\":null,\"metadata\":null}",
+          "{\"generation\":\"42\"}",
+          "{\"billing\":{\"requesterPays\":true}}"
+        ]
+    mapM decodeBody captured >>= (@?= expected)
+
+wireRequired :: Assertion
+wireRequired = withTokenFile $ \file ->
+  withServer (const (pure (jsonResponse status200 "{}"))) $ \manager requests -> do
+    env <- newFileEnv manager file quiet
+    full <- newEnvWith (FromTokenFile file) quiet manager :: IO (Env '[Storage.Devstorage'FullControl])
+    let source = Storage.newComposeRequest_SourceObjectsItemInput
+        compose = Storage.newComposeRequestInput (source "first" :| [source "second"])
+    runResourceT $ do
+      void (send env (Storage.newStorageObjectsCompose "bucket" "result" compose))
+      void (send full (Storage.newStorageBucketsInsert "project" (Storage.newBucketInsertInput "new-bucket")))
+      void (send full (Storage.newStorageBucketsSetIamPolicy "bucket" (Storage.newPolicySetIamPolicyInput [])))
+      void (send full (Storage.newStorageObjectsUpdate "bucket" "object" Storage.newObject))
+    captured <- requests
+    bodies <- mapM decodeBody captured
+    case bodies of
+      [JSON.Object composed, JSON.Object bucket, JSON.Object policy, JSON.Object replacement] -> do
+        let sourceObject name = object ["name" .= (name :: Text)]
+        KeyMap.lookup "sourceObjects" composed @?= Just (JSON.toJSON [sourceObject "first", sourceObject "second"])
+        KeyMap.lookup "name" bucket @?= Just (JSON.String "new-bucket")
+        KeyMap.lookup "bindings" policy @?= Just (JSON.toJSON ([] :: [Value]))
+        KeyMap.lookup "acl" replacement @?= Nothing
+      other -> assertFailure ("expected four JSON objects, received " <> show other)
+
+decodeBody :: RecordedRequest -> IO Value
+decodeBody = assertRight . eitherDecode . body
diff --git a/test/Test/Unkai/MockServer.hs b/test/Test/Unkai/MockServer.hs
new file mode 100644
--- /dev/null
+++ b/test/Test/Unkai/MockServer.hs
@@ -0,0 +1,74 @@
+module Test.Unkai.MockServer
+  ( RecordedRequest (..),
+    withServer,
+    withServerSettings,
+    withDirectory,
+    withTokenFile,
+    jsonResponse,
+  )
+where
+
+import Control.Exception (bracket)
+import Data.ByteString (ByteString)
+import Data.ByteString.Lazy qualified as LBS
+import Data.IORef
+import Network.HTTP.Client qualified as HTTP
+import Network.HTTP.Types
+import Network.Wai qualified as Wai
+import Network.Wai.Handler.Warp qualified as Warp
+import System.Directory (getTemporaryDirectory, removeDirectoryRecursive)
+import System.FilePath ((</>))
+import System.Posix.Temp (mkdtemp)
+
+data RecordedRequest = RecordedRequest
+  { method :: ByteString,
+    path :: ByteString,
+    query :: Query,
+    headers :: RequestHeaders,
+    body :: LBS.ByteString
+  }
+  deriving stock (Show)
+
+withServer ::
+  (RecordedRequest -> IO Wai.Response) ->
+  (HTTP.Manager -> IO [RecordedRequest] -> IO a) ->
+  IO a
+withServer = withServerSettings HTTP.defaultManagerSettings
+
+withServerSettings ::
+  HTTP.ManagerSettings ->
+  (RecordedRequest -> IO Wai.Response) ->
+  (HTTP.Manager -> IO [RecordedRequest] -> IO a) ->
+  IO a
+withServerSettings settings respond run = do
+  requests <- newIORef []
+  let app request sendResponse = do
+        bytes <- Wai.strictRequestBody request
+        let captured =
+              RecordedRequest
+                (Wai.requestMethod request)
+                (Wai.rawPathInfo request)
+                (Wai.queryString request)
+                (Wai.requestHeaders request)
+                bytes
+        atomicModifyIORef' requests (\xs -> (captured : xs, ()))
+        respond captured >>= sendResponse
+  Warp.testWithApplication (pure app) $ \port -> do
+    let route request =
+          pure request {HTTP.host = "127.0.0.1", HTTP.port = port, HTTP.secure = False}
+    manager <- HTTP.newManager (settings {HTTP.managerModifyRequest = route})
+    run manager (reverse <$> readIORef requests)
+
+withDirectory :: (FilePath -> IO a) -> IO a
+withDirectory = bracket create removeDirectoryRecursive
+  where
+    create = getTemporaryDirectory >>= mkdtemp . (</> "unkai-test-")
+
+withTokenFile :: (FilePath -> IO a) -> IO a
+withTokenFile run = withDirectory $ \dir -> do
+  let file = dir </> "access-token"
+  LBS.writeFile file "bearer-fixture-marker\n"
+  run file
+
+jsonResponse :: Status -> LBS.ByteString -> Wai.Response
+jsonResponse status = Wai.responseLBS status [(hContentType, "application/json")]
diff --git a/test/Test/Unkai/Streaming.hs b/test/Test/Unkai/Streaming.hs
new file mode 100644
--- /dev/null
+++ b/test/Test/Unkai/Streaming.hs
@@ -0,0 +1,233 @@
+module Test.Unkai.Streaming (streamingTests) where
+
+import Control.Concurrent (forkFinally, killThread, newEmptyMVar, putMVar, takeMVar)
+import Control.Exception (AsyncException (ThreadKilled), Exception, bracket, fromException, throwIO, try)
+import Control.Lens ((&), (?~), (^.))
+import Control.Monad (void, zipWithM_)
+import Control.Monad.IO.Class (liftIO)
+import Control.Monad.Trans.Resource (ResourceT)
+import Data.Aeson (eitherDecodeStrict)
+import Data.ByteString qualified as BS
+import Data.ByteString.Builder (byteString)
+import Data.ByteString.Char8 qualified as BS8
+import Data.ByteString.Lazy qualified as LBS
+import Data.Generics.Labels ()
+import Data.IORef (modifyIORef', newIORef, readIORef, writeIORef)
+import Network.HTTP.Client qualified as HTTP
+import Network.HTTP.Client.Internal qualified as HTTPInternal
+import Network.HTTP.Types (hContentLength, hContentType, methodPost, status200, status204, status500)
+import Network.Wai qualified as Wai
+import Streamly.Data.Stream qualified as Stream
+import System.FilePath ((</>))
+import System.Timeout (timeout)
+import Test.Tasty (TestTree, testGroup)
+import Test.Tasty.HUnit (Assertion, assertFailure, testCase, (@?=))
+import Test.Unkai.MockServer
+import Unkai (Credentials (FromTokenFile), Env, Stream, download, newEnvWith, runResourceT, send, sinkLBS, sourceBody, upload)
+import Unkai.Storage qualified as Storage
+
+streamingTests :: TestTree
+streamingTests =
+  testGroup
+    "scoped streaming"
+    [ testCase "generated GET yields the prefix before the server writes the suffix" $ bounded delayedDownload,
+      testCase "an empty download releases at EOF" $ bounded emptyDownload,
+      testCase "a short read closes the unfinished response at scope exit" $
+        bounded $
+          withUnfinishedBody runResourceT,
+      testCase "a consumer exception closes the unfinished response" $
+        bounded $
+          withUnfinishedBody $ \readBody -> do
+            result <- try @ConsumerFailure @() (runResourceT (readBody >> liftIO (throwIO ConsumerFailure)))
+            result @?= Left ConsumerFailure,
+      testCase "cancellation closes the unfinished response" $ bounded cancelledDownload,
+      testCase "a JSON response decodes object metadata" $ bounded decodedBody,
+      testCase "a unit response drains its body reader through EOF" $ bounded discardedBody,
+      testCase "multipart sends empty and reusable file bodies with their exact lengths" $ bounded multipartFiles
+    ]
+
+bounded :: Assertion -> Assertion
+bounded action =
+  timeout 10000000 action >>= \case
+    Just () -> pure ()
+    Nothing -> assertFailure "timed out waiting for the streaming response or its cleanup"
+
+type StorageEnv = Env '[Storage.Devstorage'ReadWrite]
+
+objectRequest :: Storage.StorageObjectsGet
+objectRequest = Storage.newStorageObjectsGet "bucket" "reports/q1.csv"
+
+prefix :: BS.ByteString
+prefix = "first bytes"
+
+consumePrefix :: Stream -> ResourceT IO Stream
+consumePrefix = go prefix
+  where
+    go remaining stream
+      | BS.null remaining = pure stream
+      | otherwise =
+          Stream.uncons stream >>= \case
+            Nothing -> liftIO (assertFailure "body ended before the prefix")
+            Just (chunk, rest) ->
+              case BS.stripPrefix chunk remaining of
+                Nothing -> liftIO (assertFailure ("unexpected prefix chunk: " <> show chunk))
+                Just remaining' -> go remaining' rest
+
+withStorageServer ::
+  HTTP.ManagerSettings ->
+  Wai.Response ->
+  (StorageEnv -> IO [RecordedRequest] -> IO a) ->
+  IO a
+withStorageServer settings response run = withTokenFile $ \file ->
+  withServerSettings settings (const (pure response)) $ \manager requests -> do
+    env <- newEnvWith (FromTokenFile file) (\_ _ -> pure ()) manager
+    run env requests
+
+withCloseCount ::
+  Wai.Response ->
+  (StorageEnv -> IO [RecordedRequest] -> IO Int -> IO a) ->
+  IO a
+withCloseCount response run = do
+  closed <- newIORef 0
+  -- Count the adapter's release action independently of HTTP connection pooling.
+  let instrument rs =
+        pure rs {HTTPInternal.responseClose' = HTTPInternal.ResponseClose close}
+        where
+          close = modifyIORef' closed (+ 1) >> HTTP.responseClose rs
+      settings = HTTP.defaultManagerSettings {HTTP.managerModifyResponse = instrument}
+  withStorageServer settings response $ \env requests -> run env requests (readIORef closed)
+
+delayedDownload :: Assertion
+delayedDownload = do
+  sendSuffix <- newEmptyMVar
+  let suffix = "last bytes"
+      response = Wai.responseStream status200 [] $ \write flush -> do
+        write (byteString prefix)
+        flush
+        takeMVar sendSuffix
+        write (byteString suffix)
+  withCloseCount response $ \env requests closed -> do
+    runResourceT $ do
+      stream <- download env objectRequest
+      rest <- consumePrefix stream
+      liftIO $ do
+        map path <$> requests >>= (@?= ["/storage/v1/b/bucket/o/reports%2Fq1.csv"])
+        closed >>= (@?= 0)
+        putMVar sendSuffix ()
+      sinkLBS rest >>= liftIO . (@?= LBS.fromStrict suffix)
+      liftIO (closed >>= (@?= 1))
+    closed >>= (@?= 1)
+
+emptyDownload :: Assertion
+emptyDownload = withCloseCount (Wai.responseLBS status200 [] "") $ \env _ closed -> do
+  runResourceT $ do
+    download env objectRequest >>= sinkLBS >>= liftIO . (@?= "")
+    liftIO (closed >>= (@?= 1))
+  closed >>= (@?= 1)
+
+withUnfinishedBody :: (ResourceT IO () -> Assertion) -> Assertion
+withUnfinishedBody run = do
+  disconnected <- newEmptyMVar
+  let response = Wai.responseRaw raw (jsonResponse status500 "")
+      raw receive write = do
+        write ("HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n" <> prefix)
+        receive >>= putMVar disconnected
+  withCloseCount response $ \env _ closed -> do
+    let readBody = do
+          _ <- download env objectRequest >>= consumePrefix
+          liftIO (closed >>= (@?= 0))
+    run readBody
+    closed >>= (@?= 1)
+    takeMVar disconnected >>= (@?= BS.empty)
+
+data ConsumerFailure = ConsumerFailure
+  deriving stock (Eq, Show)
+
+instance Exception ConsumerFailure
+
+cancelledDownload :: Assertion
+cancelledDownload = withUnfinishedBody $ \readBody -> do
+  ready <- newEmptyMVar
+  block <- newEmptyMVar
+  finished <- newEmptyMVar
+  let consume = runResourceT $ do
+        readBody
+        liftIO (putMVar ready () >> takeMVar block)
+  bracket (forkFinally consume (putMVar finished)) killThread $ \consumer -> do
+    takeMVar ready
+    killThread consumer
+    takeMVar finished >>= \case
+      Left cause -> fromException cause @?= Just ThreadKilled
+      Right () -> assertFailure "expected cancellation to escape"
+
+decodedBody :: Assertion
+decodedBody = withStorageServer HTTP.defaultManagerSettings response $ \env _ -> do
+  metadata <- runResourceT (send env objectRequest)
+  (metadata ^. #name) @?= Just "reports/q1.csv"
+  where
+    response = jsonResponse status200 "{\"name\":\"reports/q1.csv\"}"
+
+discardedBody :: Assertion
+discardedBody = do
+  calls <- newIORef (0 :: Int)
+  -- A real 204 has no body. Supply chunks at the HTTP reader boundary to test
+  -- that the generated unit-response decoder drains rather than returning early.
+  let reader = do
+        n <- readIORef calls
+        writeIORef calls (n + 1)
+        pure $ case n of
+          0 -> "first"
+          1 -> "second"
+          _ -> ""
+      instrument rs = pure rs {HTTPInternal.responseBody = reader}
+      settings = HTTP.defaultManagerSettings {HTTP.managerModifyResponse = instrument}
+  withStorageServer settings (Wai.responseLBS status204 [] "") $ \env _ -> do
+    runResourceT (send env (Storage.newStorageObjectsDelete "bucket" "unused"))
+    readIORef calls >>= (@?= 3)
+
+multipartFiles :: Assertion
+multipartFiles = withDirectory $ \dir ->
+  withStorageServer HTTP.defaultManagerSettings (jsonResponse status200 "{}") $ \env requests -> do
+    let empty = dir </> "empty.bin"
+        nonempty = dir </> "sample.bin"
+        bytes = BS.pack [0, 13, 10, 128, 255] <> BS.replicate 70000 42
+        metadata = Storage.newObject & #name ?~ "reports/q1.csv"
+        request = Storage.newStorageObjectsInsert "bucket" metadata
+    BS.writeFile empty BS.empty
+    BS.writeFile nonempty bytes
+    emptyBody <- sourceBody empty
+    fileBody <- sourceBody nonempty
+    runResourceT $ do
+      void (upload env request emptyBody)
+      void (upload env request fileBody)
+      void (upload env request fileBody)
+    captured <- requests
+    length captured @?= 3
+    zipWithM_ (checkMultipart metadata) [BS.empty, bytes, bytes] captured
+
+checkMultipart :: Storage.Object -> BS.ByteString -> RecordedRequest -> Assertion
+checkMultipart metadata bytes captured = do
+  method captured @?= methodPost
+  path captured @?= "/upload/storage/v1/b/bucket/o"
+  filter ((== "uploadType") . fst) (query captured) @?= [("uploadType", Just "multipart")]
+  lookup hContentLength (headers captured) @?= Just (BS8.pack (show (LBS.length (body captured))))
+  case lookup hContentType (headers captured) >>= BS.stripPrefix "multipart/related; boundary=" of
+    Just boundary | not (BS.null boundary) -> do
+      let marker = "--" <> boundary
+          wire = LBS.toStrict (body captured)
+          (metadataPart, mediaPart) = BS.breakSubstring ("\r\n" <> marker <> "\r\n") wire
+      case BS.stripPrefix (marker <> "\r\nContent-Type: ") metadataPart of
+        Nothing -> assertFailure "missing JSON metadata part"
+        Just payload -> do
+          let (contentType, framedJSON) = BS.breakSubstring "\r\n\r\n" payload
+          BS8.takeWhile (/= ';') contentType @?= "application/json"
+          eitherDecodeStrict (BS.drop 4 framedJSON) @?= Right metadata
+      mediaPart
+        @?= "\r\n"
+          <> marker
+          <> "\r\nContent-Type: application/octet-stream\r\n\r\n"
+          <> bytes
+          <> "\r\n"
+          <> marker
+          <> "--\r\n"
+    contentType -> assertFailure ("invalid multipart boundary: " <> show contentType)
diff --git a/unkai.cabal b/unkai.cabal
new file mode 100644
--- /dev/null
+++ b/unkai.cabal
@@ -0,0 +1,128 @@
+cabal-version: 3.12
+name: unkai
+version: 0.1.0.1
+synopsis: Google Cloud client runtime: authentication, environment and HTTP.
+description:
+  Request, response and authentication logic for communicating with Google
+  Cloud APIs using the types supplied by the generated @unkai-*@ service
+  libraries (for example @unkai-storage@).
+  .
+  Unkai is a maintained fork of <https://github.com/brendanhay/gogol gogol>.
+
+homepage: https://github.com/shinzui/unkai
+bug-reports: https://github.com/shinzui/unkai/issues
+license: MPL-2.0
+license-file: LICENSE
+author: Brendan Hay, Nadeem Bitar
+maintainer: Nadeem Bitar <nadeem@gmail.com>
+copyright: Copyright (c) 2015-2025 Brendan Hay, (c) 2026 Nadeem Bitar
+category: Google
+build-type: Simple
+tested-with: ghc ==9.12.4
+extra-doc-files:
+  CHANGELOG.md
+  README.md
+
+source-repository head
+  type: git
+  location: https://github.com/shinzui/unkai.git
+  subdir: lib/unkai
+
+common common
+  default-language: GHC2024
+  default-extensions:
+    DeriveAnyClass
+    DuplicateRecordFields
+    OverloadedLabels
+    OverloadedStrings
+
+  ghc-options:
+    -Wall
+    -Wcompat
+    -Widentities
+    -Wincomplete-uni-patterns
+    -Wincomplete-record-updates
+    -Wredundant-constraints
+    -Wunused-packages
+    -Wmissing-export-lists
+    -Wpartial-fields
+    -Wmissing-deriving-strategies
+    -fhide-source-paths
+    -funbox-strict-fields
+
+library
+  import: common
+  hs-source-dirs: src
+  exposed-modules:
+    Unkai
+    Unkai.Auth
+    Unkai.Auth.ApplicationDefault
+    Unkai.Auth.Scope
+    Unkai.Auth.ServiceAccount
+    Unkai.Auth.TokenFile
+    Unkai.Compute.Metadata
+    Unkai.Env
+
+  other-modules:
+    Unkai.Internal.Auth
+    Unkai.Internal.Body
+    Unkai.Internal.HTTP
+    Unkai.Internal.Logger
+    Unkai.Internal.Multipart
+
+  build-depends:
+    aeson ^>=2.2,
+    base >=4.21 && <5,
+    bytestring ^>=0.12,
+    crypton >=1.0 && <1.1,
+    crypton-x509 ^>=1.7,
+    crypton-x509-store ^>=1.6,
+    directory ^>=1.3,
+    exceptions ^>=0.10,
+    filepath >=1.5 && <1.6,
+    http-client ^>=0.7,
+    http-client-tls ^>=0.4,
+    http-media ^>=0.8,
+    http-types ^>=0.12,
+    lens ^>=5.3,
+    memory ^>=0.18,
+    mime-types ^>=0.1,
+    mtl ^>=2.3,
+    resourcet ^>=1.3,
+    streamly-core ^>=0.3,
+    text ^>=2.1,
+    time >=1.12 && <1.15,
+    unix,
+    unkai-core ^>=0.1.0.1,
+
+test-suite unkai-test
+  import: common
+  type: exitcode-stdio-1.0
+  hs-source-dirs: test
+  main-is: Main.hs
+  other-modules:
+    Test.Unkai.MockServer
+    Test.Unkai.Streaming
+
+  ghc-options: -threaded
+  build-depends:
+    aeson,
+    base >=4.21 && <5,
+    bytestring,
+    directory,
+    filepath,
+    generic-lens,
+    http-client,
+    http-types,
+    lens,
+    resourcet,
+    streamly-core,
+    tasty,
+    tasty-hunit,
+    text,
+    unix,
+    unkai,
+    unkai-storage,
+    unordered-containers,
+    wai,
+    warp,
