packages feed

http-env-0.0.0.0: src/Network/HTTP/Env/LogPolicy.hs

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeApplications #-}

-- | What may be written to a log about an HTTP request.
-- Opt-in: an unvouched header is dropped, an unvouched query parameter redacted.
module Network.HTTP.Env.LogPolicy
  ( LogPolicy (..),
    defaultLogPolicy,
    defaultHeadersToRedact,
    defaultHeadersToLog,
    quotaHeaders,
    hIdempotencyKey,
    defaultParamsToRedact,
    defaultParamsToLog,
    HeaderLogPolicy (..),
    headerLogPolicy,
    scrubHeadersForLogging,
    scrubHttpException,
    scrubHttpResponse,
    redactedHeaderValue,
    redactedParamValue,
    QueryParamLogPolicy (..),
    queryParamLogPolicy,
    scrubQueryForLogging,
    scrubUriForLogging,
    renderHttpExceptionForLogging,
    renderResponseForLogging,
    loggedResponseBodyBytes,
    renderBodyForLogging,
    withheldResponseBody,
  )
where

import Data.ByteString (ByteString)
import qualified Data.ByteString as ByteString
import qualified Data.ByteString.Lazy as LB
import Data.Int (Int64)
import Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.Text as Text
import qualified Data.Text.Encoding as TE
import qualified Network.HTTP.Client as HTTP
import qualified Network.HTTP.Client.Internal as HTTP (Response (responseOriginalRequest))
import Network.HTTP.Env.Numeric (int64ToInt)
import Network.HTTP.Types (Query, parseQuery, renderQuery)
import Network.HTTP.Types.Header
import Network.URI (URI (..))
import Text.Show.Pretty (ppShow)

-- | The names a log may show, and the names it must redact.
-- The redaction sets win over the logging sets.
data LogPolicy = LogPolicy
  { -- | Headers logged with 'redactedHeaderValue'.
    logPolicyHeadersToRedact :: !(Set HeaderName),
    -- | Headers logged as they are.
    logPolicyHeadersToLog :: !(Set HeaderName),
    -- | Query parameters known to carry a credential, even if vouched for.
    logPolicyParamsToRedact :: !(Set ByteString),
    -- | Query parameters logged with their values.
    logPolicyParamsToLog :: !(Set ByteString)
  }

-- | The standard names only.
defaultLogPolicy :: LogPolicy
defaultLogPolicy =
  LogPolicy
    { logPolicyHeadersToRedact = defaultHeadersToRedact,
      logPolicyHeadersToLog = defaultHeadersToLog,
      logPolicyParamsToRedact = defaultParamsToRedact,
      logPolicyParamsToLog = defaultParamsToLog
    }

-- | The standard headers that carry credentials.
defaultHeadersToRedact :: Set HeaderName
defaultHeadersToRedact =
  Set.fromList
    [ hAuthorization,
      hCookie,
      hSetCookie,
      hProxyAuthorization
    ]

-- | The standard headers that carry no credential.
defaultHeadersToLog :: Set HeaderName
defaultHeadersToLog =
  Set.fromList
    [ hAccept,
      hAcceptCharset,
      hAcceptEncoding,
      hAcceptLanguage,
      hAcceptRanges,
      hAge,
      hAllow,
      hCacheControl,
      hConnection,
      hContentEncoding,
      hContentLanguage,
      hContentLength,
      hContentLocation,
      hContentMD5,
      hContentRange,
      hContentType,
      hDate,
      hETag,
      hExpect,
      hExpires,
      hFrom,
      hHost,
      hIfMatch,
      hIfModifiedSince,
      hIfNoneMatch,
      hIfRange,
      hIfUnmodifiedSince,
      hLastModified,
      hLocation,
      hMaxForwards,
      hPragma,
      hProxyAuthenticate,
      hRange,
      hReferer,
      hRetryAfter,
      hServer,
      hTE,
      hTrailer,
      hTransferEncoding,
      hUpgrade,
      hUserAgent,
      hVary,
      hVia,
      hWWWAuthenticate,
      hWarning,
      hContentDisposition,
      hMIMEVersion,
      hOrigin,
      hPrefer,
      hPreferenceApplied,
      "X-Request-ID",
      "X-Real-IP",
      "X-Forwarded-For",
      "X-Forwarded-Proto",
      "X-Forwarded-Host",
      "X-Forwarded-Server"
    ]

-- | The headers 'Network.HTTP.Env.RateLimit' reads a spent quota from.
-- Every policy logs them, because a spent quota is read from a scrubbed
-- failure.
quotaHeaders :: Set HeaderName
quotaHeaders =
  Set.fromList
    [ hRetryAfter,
      "X-RateLimit-Limit",
      "X-RateLimit-Remaining",
      "X-RateLimit-Reset",
      "X-RateLimit-Resource",
      "X-RateLimit-Used",
      "RateLimit",
      "RateLimit-Limit",
      "RateLimit-Policy",
      "RateLimit-Remaining",
      "RateLimit-Reset"
    ]

-- | The OAuth2 query parameters that carry a credential (RFC 6749).
defaultParamsToRedact :: Set ByteString
defaultParamsToRedact =
  Set.fromList
    [ "client_secret",
      "refresh_token",
      "access_token",
      "code",
      "state"
    ]

-- | The OAuth2 query parameters that carry no credential (RFC 6749 and 9207).
defaultParamsToLog :: Set ByteString
defaultParamsToLog =
  Set.fromList
    [ "client_id",
      "grant_type",
      "response_type",
      "redirect_uri",
      "scope",
      "iss"
    ]

-- | The header that asks a server to answer a resend as it answered the first.
-- Every policy logs it, because whether a call may be sent again is read from
-- a scrubbed failure.
hIdempotencyKey :: HeaderName
hIdempotencyKey = "Idempotency-Key"

-- | What to do with one header before it reaches a log sink.
data HeaderLogPolicy
  = HeaderLogPolicyLogValue
  | HeaderLogPolicyRedactValue
  | HeaderLogPolicyDrop
  deriving (Show, Eq)

-- | Whether a policy redacts, logs or drops a header.
headerLogPolicy :: LogPolicy -> HeaderName -> HeaderLogPolicy
headerLogPolicy policy name
  | name `Set.member` logPolicyHeadersToRedact policy = HeaderLogPolicyRedactValue
  | name `Set.member` logPolicyHeadersToLog policy = HeaderLogPolicyLogValue
  | name `Set.member` quotaHeaders = HeaderLogPolicyLogValue
  | name == hIdempotencyKey = HeaderLogPolicyLogValue
  | otherwise = HeaderLogPolicyDrop

-- | Apply 'headerLogPolicy' to a whole header list.
scrubHeadersForLogging :: LogPolicy -> [Header] -> [Header]
scrubHeadersForLogging policy headers = do
  (name, value) <- headers
  case headerLogPolicy policy name of
    HeaderLogPolicyLogValue -> pure (name, value)
    HeaderLogPolicyRedactValue -> pure (name, redactedHeaderValue)
    HeaderLogPolicyDrop -> []

-- | What a redacted header's value is logged as.
redactedHeaderValue :: ByteString
redactedHeaderValue = "<REDACTED>"

-- | The stand-in for a redacted query parameter value.
-- Tildes because it goes through URL encoding, which would mangle @<@ and @>@.
redactedParamValue :: ByteString
redactedParamValue = "~REDACTED~"

-- | What to do with one query parameter before it reaches a log sink.
-- Never dropped, because the URI must still match the request it logs.
data QueryParamLogPolicy
  = QueryParamLogPolicyLogValue
  | QueryParamLogPolicyRedactValue
  deriving (Show, Eq)

-- | The deny list is consulted first.
queryParamLogPolicy :: LogPolicy -> ByteString -> QueryParamLogPolicy
queryParamLogPolicy policy name
  | name `Set.member` logPolicyParamsToRedact policy = QueryParamLogPolicyRedactValue
  | name `Set.member` logPolicyParamsToLog policy = QueryParamLogPolicyLogValue
  | otherwise = QueryParamLogPolicyRedactValue

-- | Apply 'queryParamLogPolicy' to a whole query string.
scrubQueryForLogging :: LogPolicy -> Query -> Query
scrubQueryForLogging policy query = do
  (name, mValue) <- query
  case queryParamLogPolicy policy name of
    QueryParamLogPolicyLogValue -> pure (name, mValue)
    QueryParamLogPolicyRedactValue -> pure (name, redactedParamValue <$ mValue)

-- | A URI with its query string put through 'queryParamLogPolicy'.
-- Render it with 'show', which redacts the userinfo that this leaves alone.
scrubUriForLogging :: LogPolicy -> URI -> URI
scrubUriForLogging policy uri =
  let query :: Query
      query = parseQuery (TE.encodeUtf8 (Text.pack (uriQuery uri)))
   in uri {uriQuery = Text.unpack (TE.decodeUtf8Lenient (renderQuery True (scrubQueryForLogging policy query)))}

-- | An 'HTTP.HttpException' with its request and response scrubbed.
-- http-client's own 'Show' redacts only @Authorization@ by default.
scrubHttpException :: LogPolicy -> HTTP.HttpException -> HTTP.HttpException
scrubHttpException policy = \case
  HTTP.HttpExceptionRequest request content ->
    HTTP.HttpExceptionRequest (scrubHttpRequest policy request) (scrubHttpExceptionContent policy content)
  e@(HTTP.InvalidUrlException _ _) -> e

-- | A request with its headers and query string put through the policy.
scrubHttpRequest :: LogPolicy -> HTTP.Request -> HTTP.Request
scrubHttpRequest policy request =
  let query :: Query
      query = parseQuery (HTTP.queryString request)
   in request
        { HTTP.requestHeaders = scrubHeadersForLogging policy (HTTP.requestHeaders request),
          HTTP.queryString = renderQuery True (scrubQueryForLogging policy query)
        }

-- | The responses an exception carries, put through the policy.
-- A catch-all because 'HTTP.HttpExceptionContent' is http-client's type.
scrubHttpExceptionContent :: LogPolicy -> HTTP.HttpExceptionContent -> HTTP.HttpExceptionContent
scrubHttpExceptionContent policy = \case
  HTTP.StatusCodeException response body ->
    HTTP.StatusCodeException (scrubHttpResponse policy response) body
  HTTP.TooManyRedirects responses ->
    HTTP.TooManyRedirects (map (scrubHttpResponse policy) responses)
  content -> content

-- | A response with its headers and the request it answered put through the
-- policy, because http-client's 'Show' prints that request, and with no cookie
-- jar, which holds the cookies its headers set.
-- The body is left alone.
scrubHttpResponse :: LogPolicy -> HTTP.Response body -> HTTP.Response body
scrubHttpResponse policy response =
  response
    { HTTP.responseHeaders = scrubHeadersForLogging policy (HTTP.responseHeaders response),
      HTTP.responseCookieJar = mempty,
      HTTP.responseOriginalRequest = scrubHttpRequest policy (HTTP.getOriginalRequest response)
    }

-- | An 'HTTP.HttpException' scrubbed and rendered for a log line, with the
-- response body cut to 'loggedResponseBodyBytes'.
renderHttpExceptionForLogging :: LogPolicy -> HTTP.HttpException -> String
renderHttpExceptionForLogging policy =
  ppShow @HTTP.HttpException . cutExceptionBody . scrubHttpException policy

-- | Cut the response body an exception carries to 'loggedResponseBodyBytes'.
-- A catch-all because 'HTTP.HttpExceptionContent' is http-client's type.
cutExceptionBody :: HTTP.HttpException -> HTTP.HttpException
cutExceptionBody = \case
  HTTP.HttpExceptionRequest request (HTTP.StatusCodeException response body) ->
    HTTP.HttpExceptionRequest
      request
      (HTTP.StatusCodeException response (ByteString.take loggedResponseBodyInt body))
  e -> e

-- | 'loggedResponseBodyBytes' as an 'Int'.
loggedResponseBodyInt :: Int
loggedResponseBodyInt = int64ToInt loggedResponseBodyBytes

-- | A response scrubbed and rendered for a log line, with its body cut to
-- 'loggedResponseBodyBytes'.
renderResponseForLogging :: LogPolicy -> HTTP.Response LB.ByteString -> String
renderResponseForLogging policy response =
  ppShow @(HTTP.Response LB.ByteString) $
    LB.take loggedResponseBodyBytes <$> scrubHttpResponse policy response

-- | A body cut to 'loggedResponseBodyBytes' and rendered.
renderBodyForLogging :: LB.ByteString -> String
renderBodyForLogging = show @LB.ByteString . LB.take loggedResponseBodyBytes

-- | How much of a response body a log line may carry.
-- The same as http-client keeps in a 'HTTP.StatusCodeException'.
loggedResponseBodyBytes :: Int64
loggedResponseBodyBytes = 1024

-- | Stands in for a response body that must not be logged at all.
-- A token endpoint's 200 starts with the credential, so cutting is not enough.
withheldResponseBody :: String
withheldResponseBody = "<WITHHELD: may contain a credential>"