packages feed

baikai-mcp-0.1.0.0: src/Baikai/Mcp/Auth.hs

-- | Credentials for protected MCP endpoints: static header references and
-- delegated OAuth 2.1 (MCP authorization, revision @2026-07-28@).
--
-- Credentials reach the wire only through the client's per-send
-- 'McpRequestHook', and only for the origin they were configured for.
-- Configuration holds /references/; values are resolved at send time, so
-- a secret rotated behind the same reference takes effect on the next
-- request. Every secret is a 'Secret', whose 'Show' never reveals it.
--
-- A server accepting a credential and the host authorizing an agent's
-- action are separate decisions: this module supplies the first, and a
-- host composes its own policy hook in front of it with '<>'.
--
-- The OAuth flow follows the specification: protected resource metadata
-- (RFC 9728) names the authorization server; its metadata (RFC 8414 or
-- OpenID Connect discovery) must carry the exact issuer it was fetched for
-- and advertise PKCE @S256@; the client registers by pre-registration,
-- then a Client ID Metadata Document, then (deprecated) dynamic
-- registration; authorization uses PKCE, @state@, the @resource@
-- indicator and RFC 9207 issuer validation before any code is redeemed.
-- Tokens are stored per principal and resource and bound to the issuer and
-- client that issued them; refresh is serialized so concurrent requests
-- cause one rotation.
module Baikai.Mcp.Auth
  ( -- * Secrets and references
    Secret,
    secret,
    revealSecret,
    CredentialRef (..),
    CredentialResolver (..),

    -- * Static credentials
    StaticCredentials (..),
    noStaticCredentials,
    staticCredentialHook,

    -- * Challenges
    AuthChallenge (..),
    parseChallenge,

    -- * OAuth configuration
    OAuthConfig (..),
    oauthConfig,
    ClientRegistration (..),
    ApplicationType (..),
    InteractiveAuthorizer (..),
    AuthorizationRequest (..),
    AuthorizationCallback (..),

    -- * Token storage
    TokenSet (..),
    StoredGrant (..),
    TokenStore (..),
    newInMemoryTokenStore,

    -- * The provider
    OAuthProvider,
    newOAuthProvider,
    oauthRequestHook,
    AuthError (..),
    AuthOutcome (..),
    authorizeFromChallenge,
    recoverFromChallenge,

    -- * Loopback authorizer
    LoopbackConfig (..),
    loopbackAuthorizer,

    -- * Helpers
    canonicalResource,
    pkceChallenge,
  )
where

import Baikai.Mcp.Client (McpError (..), McpRequestHook (..), SendAttempt (..), SendDecision (..), sendHeader)
import Baikai.Mcp.Internal.Http (HttpEndpoint (..), parseEndpoint, readBounded, rethrowAsync, statusOf)
import Baikai.Mcp.Transport (isProtocolControlledHeader)
import Control.Concurrent.MVar
import Control.Exception (SomeException, bracket, try)
import Control.Monad (forM_, unless, when)
import Crypto.Hash (SHA256 (..), hashWith)
import Crypto.Random (getRandomBytes)
import Data.Aeson (Value (..), object, (.=))
import Data.Aeson qualified as Aeson
import Data.Aeson.KeyMap qualified as KeyMap
import Data.ByteArray qualified as BA
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.ByteString.Base64 qualified as B64
import Data.ByteString.Base64.URL qualified as B64URL
import Data.ByteString.Builder qualified as Builder
import Data.ByteString.Char8 qualified as BS8
import Data.ByteString.Lazy qualified as LBS
import Data.CaseInsensitive qualified as CI
import Data.Char (isAlphaNum, isAscii, isSpace)
import Data.IORef
import Data.List (nub)
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import Data.Text qualified as Text
import Data.Text.Encoding qualified as TE
import Data.Time.Clock (NominalDiffTime, UTCTime, addUTCTime, getCurrentTime)
import GHC.Generics (Generic)
import Network.HTTP.Client qualified as HTTP
import Network.HTTP.Types (HeaderName, hAccept, hAuthorization, hContentType, parseQueryText, renderQueryText)
import Network.Socket qualified as Net
import Network.Socket.ByteString qualified as NetBS
import System.Timeout (timeout)

-- ---------------------------------------------------------------------------
-- Secrets

-- | A secret value. 'Show' prints only that it is redacted.
newtype Secret = Secret ByteString
  deriving stock (Eq)

instance Show Secret where
  show _ = "<redacted>"

secret :: ByteString -> Secret
secret = Secret

-- | The raw value, for the one place that must send it.
revealSecret :: Secret -> ByteString
revealSecret (Secret b) = b

-- | An operator-chosen name for a credential, such as @github-token@. Not
-- secret; resolved at the composition boundary.
newtype CredentialRef = CredentialRef {refName :: Text}
  deriving stock (Eq, Ord, Show, Generic)

newtype CredentialResolver = CredentialResolver {resolveCredential :: CredentialRef -> IO (Either Text Secret)}

-- ---------------------------------------------------------------------------
-- Static credentials

data StaticCredentials = StaticCredentials
  { -- | Sent as @Authorization: Bearer …@.
    bearer :: !(Maybe CredentialRef),
    -- | Custom headers such as an API key header.
    headers :: ![(HeaderName, CredentialRef)]
  }
  deriving stock (Eq, Show, Generic)

noStaticCredentials :: StaticCredentials
noStaticCredentials = StaticCredentials Nothing []

reservedCredentialHeader :: HeaderName -> Bool
reservedCredentialHeader n =
  isProtocolControlledHeader n || n `elem` [hAuthorization, "Proxy-Authorization", "Cookie", "Set-Cookie", "Origin"]

validHeaderName :: HeaderName -> Bool
validHeaderName n = not (BS.null o) && BS8.all tchar o
  where
    o = CI.original n
    tchar c = isAscii c && (isAlphaNum c || c `elem` ("!#$%&'*+-.^_`|~" :: String))

validHeaderValue :: ByteString -> Bool
validHeaderValue = BS.all (\w -> (w >= 0x20 && w /= 0x7f) || w == 0x09)

-- | A hook that adds the configured credentials, resolved on every send,
-- for requests to the endpoint's own origin only. Fails on a header name
-- that is invalid, duplicated, or one the client or the bearer mode owns.
staticCredentialHook :: Text -> CredentialResolver -> StaticCredentials -> Either Text McpRequestHook
staticCredentialHook endpointUrl resolver creds = do
  ep <- parseEndpoint endpointUrl
  forM_ creds.headers $ \(n, _) -> do
    unless (validHeaderName n) (Left ("invalid header name " <> TE.decodeUtf8Lenient (CI.original n)))
    when (reservedCredentialHeader n) (Left ("the header " <> TE.decodeUtf8Lenient (CI.original n) <> " cannot carry a configured credential"))
  let names = map fst creds.headers
  when (length (nub names) /= length names) (Left "a credential header is configured twice")
  Right . McpRequestHook $ \att ->
    if att.origin /= ep.origin
      then pure (SendDenied ("credentials are bound to " <> ep.origin))
      else do
        b <- traverse (resolveFor hAuthorization (\s -> "Bearer " <> s)) creds.bearer
        hs <- traverse (\(n, r) -> resolveFor n id r) creds.headers
        pure $ case sequence (maybe [] pure b <> hs) of
          Left why -> SendDenied why
          Right pairs -> SendAllowed [sendHeader n v | (n, v) <- pairs]
  where
    resolveFor n wrap r = do
      v <- resolver.resolveCredential r
      pure $ case v of
        Left why -> Left ("the credential " <> r.refName <> " could not be resolved: " <> Text.take 120 why)
        Right (Secret s)
          | BS.null s || not (validHeaderValue s) -> Left ("the credential " <> r.refName <> " is not a valid header value")
          | otherwise -> Right (n, wrap s)

-- ---------------------------------------------------------------------------
-- Challenges

-- | The parameters of a @Bearer@ challenge from @WWW-Authenticate@.
data AuthChallenge = AuthChallenge
  { resourceMetadata :: !(Maybe Text),
    scope :: ![Text],
    challengeError :: !(Maybe Text)
  }
  deriving stock (Eq, Show, Generic)

-- | Parse the @Bearer@ challenge. Other schemes are ignored.
parseChallenge :: Text -> Maybe AuthChallenge
parseChallenge raw = case dropWhile (not . isBearer) (schemes (Text.strip raw)) of
  (_ : params) ->
    let ps = takeWhile isParam params
        lookupP k = lookup k [(Text.toLower a, b) | Right (a, b) <- ps]
     in Just
          AuthChallenge
            { resourceMetadata = lookupP "resource_metadata",
              scope = maybe [] Text.words (lookupP "scope"),
              challengeError = lookupP "error"
            }
  [] -> Nothing
  where
    isBearer = \case
      Left s -> Text.toLower s == "bearer"
      Right _ -> False
    isParam = either (const False) (const True)
    schemes = tokenize

-- | Split a challenge list into scheme names (Left) and parameters (Right).
tokenize :: Text -> [Either Text (Text, Text)]
tokenize t0 = go (Text.stripStart t0)
  where
    go t
      | Text.null t = []
      | Just rest <- Text.stripPrefix "," t = go (Text.stripStart rest)
      | otherwise =
          let (word, rest) = Text.span (\c -> not (isSpace c) && c /= '=' && c /= ',') t
              rest' = Text.stripStart rest
           in case Text.uncons rest' of
                Just ('=', afterEq) ->
                  let (val, remaining) = value (Text.stripStart afterEq)
                   in Right (word, val) : go (Text.stripStart remaining)
                _ | Text.null word -> go (Text.drop 1 rest')
                _ -> Left word : go rest'
    value t = case Text.uncons t of
      Just ('"', rest) -> quoted rest ""
      _ -> Text.span (\c -> c /= ',' && not (isSpace c)) t
    quoted t acc = case Text.uncons t of
      Nothing -> (acc, "")
      Just ('\\', rest) -> case Text.uncons rest of
        Just (c, rest') -> quoted rest' (Text.snoc acc c)
        Nothing -> (acc, "")
      Just ('"', rest) -> (acc, rest)
      Just (c, rest) -> quoted rest (Text.snoc acc c)

-- ---------------------------------------------------------------------------
-- OAuth configuration

data ApplicationType = NativeApplication | WebApplication
  deriving stock (Eq, Show, Generic)

-- | Client credentials for one authorization server.
data ClientRegistration = ClientRegistration
  { clientId :: !Text,
    clientSecret :: !(Maybe Secret),
    -- | The issuer this registration belongs to.
    issuer :: !Text
  }
  deriving stock (Eq, Show, Generic)

-- | What the authorizer must present to the user.
data AuthorizationRequest = AuthorizationRequest
  { authorizationUrl :: !Text,
    redirectUri :: !Text,
    issuer :: !Text,
    scopes :: ![Text]
  }
  deriving stock (Eq, Show, Generic)

-- | The query parameters the authorization server redirected back with.
newtype AuthorizationCallback = AuthorizationCallback {callbackParams :: [(Text, Text)]}

instance Show AuthorizationCallback where
  show (AuthorizationCallback ps) = "AuthorizationCallback " <> show (map fst ps)

-- | Owns the user interaction: open the authorization URL and capture the
-- redirect. 'Left' when the user declined or the interaction failed.
newtype InteractiveAuthorizer = InteractiveAuthorizer
  { runAuthorization :: AuthorizationRequest -> IO (Either Text AuthorizationCallback)
  }

data OAuthConfig = OAuthConfig
  { -- | The MCP endpoint the tokens are for.
    endpoint :: !Text,
    -- | Whose grant this is; part of the storage key.
    principal :: !Text,
    -- | Where the authorization server redirects back to.
    redirectUri :: !Text,
    clientName :: !Text,
    applicationType :: !ApplicationType,
    -- | Credentials registered in advance, per issuer.
    preRegistered :: ![ClientRegistration],
    -- | An HTTPS URL of this client's metadata document, used when the
    -- authorization server supports Client ID Metadata Documents.
    clientMetadataDocument :: !(Maybe Text),
    -- | Permit deprecated dynamic client registration as a last resort.
    allowDynamicRegistration :: !Bool,
    -- | 'Nothing' for unattended hosts, which receive 'InteractionRequired'.
    authorizer :: !(Maybe InteractiveAuthorizer),
    -- | Allow plain HTTP for loopback hosts (development and tests).
    allowLoopbackHttp :: !Bool,
    -- | Deadline for each authorization-server request.
    requestTimeout :: !NominalDiffTime,
    -- | Refresh an access token this long before it expires.
    refreshSkew :: !NominalDiffTime
  }

oauthConfig :: Text -> Text -> Text -> OAuthConfig
oauthConfig ep who redirect =
  OAuthConfig
    { endpoint = ep,
      principal = who,
      redirectUri = redirect,
      clientName = "baikai-mcp",
      applicationType = NativeApplication,
      preRegistered = [],
      clientMetadataDocument = Nothing,
      allowDynamicRegistration = False,
      authorizer = Nothing,
      allowLoopbackHttp = True,
      requestTimeout = 30,
      refreshSkew = 30
    }

-- ---------------------------------------------------------------------------
-- Token storage

data TokenSet = TokenSet
  { accessToken :: !Secret,
    refreshToken :: !(Maybe Secret),
    expiresAt :: !(Maybe UTCTime),
    grantedScopes :: ![Text]
  }
  deriving stock (Eq, Show, Generic)

-- | A grant, bound to the authorization server and client that issued it.
data StoredGrant = StoredGrant
  { issuer :: !Text,
    clientId :: !Text,
    resource :: !Text,
    tokens :: !TokenSet
  }
  deriving stock (Eq, Show, Generic)

-- | Pluggable storage. Grants are keyed by principal and resource;
-- registrations by issuer.
data TokenStore = TokenStore
  { loadGrant :: Text -> Text -> IO (Maybe StoredGrant),
    saveGrant :: Text -> Text -> StoredGrant -> IO (),
    deleteGrant :: Text -> Text -> IO (),
    loadRegistration :: Text -> IO (Maybe ClientRegistration),
    saveRegistration :: ClientRegistration -> IO ()
  }

newInMemoryTokenStore :: IO TokenStore
newInMemoryTokenStore = do
  grants <- newIORef (Map.empty :: Map (Text, Text) StoredGrant)
  regs <- newIORef (Map.empty :: Map Text ClientRegistration)
  pure
    TokenStore
      { loadGrant = \p r -> Map.lookup (p, r) <$> readIORef grants,
        saveGrant = \p r g -> atomicModifyIORef' grants (\m -> (Map.insert (p, r) g m, ())),
        deleteGrant = \p r -> atomicModifyIORef' grants (\m -> (Map.delete (p, r) m, ())),
        loadRegistration = \i -> Map.lookup i <$> readIORef regs,
        saveRegistration = \reg -> atomicModifyIORef' regs (\m -> (Map.insert reg.issuer reg m, ()))
      }

-- ---------------------------------------------------------------------------
-- Errors and outcomes

data AuthError
  = AuthConfigInvalid !Text
  | -- | A destination was refused (scheme, origin) before any request.
    AuthDestinationRefused !Text
  | AuthMetadataUnavailable !Text
  | -- | Protected resource metadata names a different resource.
    AuthWrongResource !Text
  | -- | Authorization server metadata does not carry the issuer it was
    -- fetched for.
    AuthIssuerMismatch !Text
  | AuthPkceUnsupported
  | AuthNoRegistration !Text
  | AuthRegistrationFailed !Text
  | -- | The redirect's @state@ is not the one this flow issued.
    AuthStateMismatch
  | -- | The redirect's @iss@ is missing or names another issuer. The
    -- response's error fields were not read.
    AuthCallbackIssuerMismatch
  | -- | The user or the authorization server declined.
    AuthDeclined !Text
  | AuthTokenRequestFailed !Text
  | AuthTransport !Text
  deriving stock (Eq, Show, Generic)

data AuthOutcome
  = -- | Tokens are stored; retry the operation once.
    Authorized
  | -- | A user must authorize, but this host has no authorizer.
    InteractionRequired !AuthorizationRequest
  | -- | The server needs scopes beyond the grant. Granting them requires
    -- explicit consent: call 'authorizeFromChallenge' with the wider set.
    InsufficientScope ![Text]
  | -- | The server refused the credential and no recovery applies.
    AccessDenied !Text
  deriving stock (Eq, Show, Generic)

-- ---------------------------------------------------------------------------
-- The provider

data AsMetadata = AsMetadata
  { issuer :: !Text,
    authorizationEndpoint :: !Text,
    tokenEndpoint :: !Text,
    registrationEndpoint :: !(Maybe Text),
    issParameterSupported :: !Bool,
    cimdSupported :: !Bool,
    tokenAuthMethods :: ![Text]
  }

data OAuthProvider = OAuthProvider
  { config :: !OAuthConfig,
    store :: !TokenStore,
    manager :: !HTTP.Manager,
    resource :: !Text,
    resourceOrigin :: !Text,
    endpoint :: !HttpEndpoint,
    asCache :: !(IORef (Map Text AsMetadata)),
    lock :: !(MVar ())
  }

-- | Build a provider for one endpoint and principal.
newOAuthProvider :: HTTP.Manager -> TokenStore -> OAuthConfig -> IO (Either AuthError OAuthProvider)
newOAuthProvider mgr st cfg = case parseEndpoint cfg.endpoint of
  Left why -> pure (Left (AuthConfigInvalid why))
  Right ep -> case canonicalResource cfg.endpoint of
    Nothing -> pure (Left (AuthConfigInvalid "the endpoint has no canonical resource URI"))
    Just res -> do
      cache <- newIORef Map.empty
      l <- newMVar ()
      pure (Right OAuthProvider {config = cfg, store = st, manager = mgr, resource = res, resourceOrigin = ep.origin, endpoint = ep, asCache = cache, lock = l})

-- | The canonical resource URI (RFC 8707): lower-cased scheme and host,
-- the port only when not the default, the path without a trailing slash,
-- and no query or fragment.
canonicalResource :: Text -> Maybe Text
canonicalResource raw = case parseEndpoint raw of
  Left _ -> Nothing
  Right ep ->
    let defaultPort = if ep.scheme == "https" then 443 else 80
        portPart = if ep.port == defaultPort then "" else ":" <> Text.pack (show ep.port)
        rawPath = Text.takeWhile (\c -> c /= '?' && c /= '#') (snd (Text.breakOn "/" (Text.drop (Text.length ep.scheme + 3) (Text.strip raw))))
        path = if rawPath == "/" then "" else fromMaybe rawPath (Text.stripSuffix "/" rawPath)
     in Just (ep.scheme <> "://" <> ep.host <> portPart <> path)

-- | The client hook: a current access token for the provider's resource
-- origin, refreshed first if it is about to expire. Without a grant the
-- request goes out anonymously so that the server can issue its challenge.
oauthRequestHook :: OAuthProvider -> McpRequestHook
oauthRequestHook p = McpRequestHook $ \att ->
  if att.origin /= p.resourceOrigin
    then pure (SendDenied ("credentials are bound to " <> p.resourceOrigin))
    else do
      r <- currentAccessToken p
      pure $ case r of
        Left why -> SendDenied why
        Right Nothing -> SendAllowed []
        Right (Just (Secret tok)) -> SendAllowed [sendHeader hAuthorization ("Bearer " <> tok)]

-- | The stored access token, refreshing it under the provider's lock.
currentAccessToken :: OAuthProvider -> IO (Either Text (Maybe Secret))
currentAccessToken p = withMVar p.lock $ \_ -> do
  g <- p.store.loadGrant p.config.principal p.resource
  case g of
    Nothing -> pure (Right Nothing)
    Just grant -> do
      now <- getCurrentTime
      let fresh = maybe True (\t -> addUTCTime p.config.refreshSkew now < t) grant.tokens.expiresAt
      if fresh
        then pure (Right (Just grant.tokens.accessToken))
        else case grant.tokens.refreshToken of
          Nothing -> do
            p.store.deleteGrant p.config.principal p.resource
            pure (Right Nothing)
          Just rt -> do
            r <- refreshGrant p grant rt
            case r of
              Right g' -> pure (Right (Just g'.tokens.accessToken))
              Left (AuthTokenRequestFailed "invalid_grant") -> do
                p.store.deleteGrant p.config.principal p.resource
                pure (Right Nothing)
              Left e -> pure (Left ("refreshing the access token failed: " <> renderAuthError e))

renderAuthError :: AuthError -> Text
renderAuthError = Text.take 200 . Text.pack . show

-- | Refresh and store atomically: the new set replaces the old only after
-- a complete, valid response. A rotated refresh token replaces the old.
refreshGrant :: OAuthProvider -> StoredGrant -> Secret -> IO (Either AuthError StoredGrant)
refreshGrant p grant (Secret rt) = do
  md <- asMetadata p grant.issuer
  case md of
    Left e -> pure (Left e)
    Right meta -> do
      reg <- registrationFor p meta
      case reg of
        Left e -> pure (Left e)
        Right client
          | client.clientId /= grant.clientId -> pure (Left (AuthNoRegistration "the stored grant belongs to another client"))
          | otherwise -> do
              r <-
                tokenRequest p meta client $
                  [ ("grant_type", "refresh_token"),
                    ("refresh_token", TE.decodeUtf8 rt),
                    ("resource", p.resource)
                  ]
              case r of
                Left e -> pure (Left e)
                Right ts -> do
                  let ts' = ts {refreshToken = maybe grant.tokens.refreshToken Just ts.refreshToken, grantedScopes = if null ts.grantedScopes then grant.tokens.grantedScopes else ts.grantedScopes}
                      g' = grant {tokens = ts'}
                  p.store.saveGrant p.config.principal p.resource g'
                  pure (Right g')

-- | After a refused MCP request: refresh once if possible (the host then
-- retries once), report an insufficient scope, or report that a fresh
-- authorization is needed.
recoverFromChallenge :: OAuthProvider -> McpError -> IO (Either AuthError AuthOutcome)
recoverFromChallenge p e = case (e.httpStatus, e.challenge >>= parseChallenge) of
  (Just 403, Just ch) | ch.challengeError == Just "insufficient_scope" -> pure (Right (InsufficientScope ch.scope))
  (Just 403, _) -> pure (Right (AccessDenied "the server refused the credential"))
  (Just 401, _) -> withMVar p.lock $ \_ -> do
    g <- p.store.loadGrant p.config.principal p.resource
    case g >>= \grant -> (grant,) <$> grant.tokens.refreshToken of
      Just (grant, rt) -> do
        r <- refreshGrant p grant rt
        case r of
          Right _ -> pure (Right Authorized)
          Left (AuthTokenRequestFailed "invalid_grant") -> do
            p.store.deleteGrant p.config.principal p.resource
            pure (Right (AccessDenied "the grant was revoked; authorize again"))
          Left err -> pure (Left err)
      Nothing -> do
        forM_ g $ \_ -> p.store.deleteGrant p.config.principal p.resource
        pure (Right (AccessDenied "no refreshable grant; authorize again"))
  _ -> pure (Right (AccessDenied "the failure is not an authorization challenge"))

-- | Run the authorization flow for a 401 (or an explicit scope upgrade).
-- Discovers the authorization server from the challenge, registers if
-- needed, asks the authorizer, validates the redirect and redeems the
-- code. Scopes: the challenge's, else the resource's advertised scopes,
-- plus any scopes passed explicitly (for a consented step-up).
authorizeFromChallenge :: OAuthProvider -> Maybe Text -> [Text] -> IO (Either AuthError AuthOutcome)
authorizeFromChallenge p rawChallenge extraScopes = do
  let ch = rawChallenge >>= parseChallenge
  prm <- protectedResourceMetadata p (ch >>= (.resourceMetadata))
  case prm of
    Left e -> pure (Left e)
    Right (servers, supported) -> case servers of
      [] -> pure (Left (AuthMetadataUnavailable "the protected resource names no authorization server"))
      (iss : _) -> do
        md <- asMetadata p iss
        case md of
          Left e -> pure (Left e)
          Right meta -> do
            reg <- registrationFor p meta
            case reg of
              Left e -> pure (Left e)
              Right client -> do
                previous <- p.store.loadGrant p.config.principal p.resource
                let challenged = maybe [] (.scope) ch
                    base = if null challenged then supported else challenged
                    carried = maybe [] (\g -> if g.issuer == meta.issuer then g.tokens.grantedScopes else []) previous
                    scopes = nub (base <> carried <> extraScopes)
                runFlow p meta client scopes

runFlow :: OAuthProvider -> AsMetadata -> ClientRegistration -> [Text] -> IO (Either AuthError AuthOutcome)
runFlow p meta client scopes = do
  verifier <- randomToken
  st <- randomToken
  let challenge = pkceChallenge verifier
      query =
        [ ("response_type", Just "code"),
          ("client_id", Just client.clientId),
          ("redirect_uri", Just p.config.redirectUri),
          ("code_challenge", Just challenge),
          ("code_challenge_method", Just "S256"),
          ("state", Just st),
          ("resource", Just p.resource)
        ]
          <> [("scope", Just (Text.unwords scopes)) | not (null scopes)]
      sep = if Text.isInfixOf "?" meta.authorizationEndpoint then "&" else "?"
      url = meta.authorizationEndpoint <> sep <> TE.decodeUtf8 (BS.drop 1 (toStrictBuilder (renderQueryText True query)))
      req = AuthorizationRequest {authorizationUrl = url, redirectUri = p.config.redirectUri, issuer = meta.issuer, scopes = scopes}
  case p.config.authorizer of
    Nothing -> pure (Right (InteractionRequired req))
    Just authz -> do
      cb <- authz.runAuthorization req
      case cb of
        Left why -> pure (Left (AuthDeclined (Text.take 200 why)))
        Right callback -> case validateCallback meta.issParameterSupported meta.issuer st callback of
          Left e -> pure (Left e)
          Right code -> do
            r <-
              tokenRequest p meta client $
                [ ("grant_type", "authorization_code"),
                  ("code", code),
                  ("redirect_uri", p.config.redirectUri),
                  ("code_verifier", verifier),
                  ("resource", p.resource)
                ]
            case r of
              Left e -> pure (Left e)
              Right ts -> do
                let ts' = ts {grantedScopes = if null ts.grantedScopes then scopes else ts.grantedScopes}
                withMVar p.lock $ \_ ->
                  p.store.saveGrant p.config.principal p.resource StoredGrant {issuer = meta.issuer, clientId = client.clientId, resource = p.resource, tokens = ts'}
                pure (Right Authorized)
  where
    toStrictBuilder = BS.toStrict . builderToLazy

-- | RFC 9207 validation, then state, before anything else is read.
validateCallback :: Bool -> Text -> Text -> AuthorizationCallback -> Either AuthError Text
validateCallback issSupported expectedIssuer expectedState (AuthorizationCallback ps) = do
  let get k = lookup k ps
  case (issSupported, get "iss") of
    (_, Just i) | i /= expectedIssuer -> Left AuthCallbackIssuerMismatch
    (True, Nothing) -> Left AuthCallbackIssuerMismatch
    _ -> Right ()
  unless (get "state" == Just expectedState) (Left AuthStateMismatch)
  case get "error" of
    Just e -> Left (AuthDeclined (Text.take 64 e))
    Nothing -> pure ()
  maybe (Left (AuthDeclined "the redirect carried no authorization code")) Right (get "code")

-- | @BASE64URL(SHA256(verifier))@.
pkceChallenge :: Text -> Text
pkceChallenge v = TE.decodeUtf8 (B64URL.encodeUnpadded (BA.convert (hashWith SHA256 (TE.encodeUtf8 v))))

randomToken :: IO Text
randomToken = TE.decodeUtf8 . B64URL.encodeUnpadded <$> (getRandomBytes 32 :: IO ByteString)

-- ---------------------------------------------------------------------------
-- Discovery

-- | Fetch protected resource metadata: from the challenge's URL, else the
-- path-inserted well-known URL, else the root one. Its @resource@ must be
-- this endpoint's canonical resource.
protectedResourceMetadata :: OAuthProvider -> Maybe Text -> IO (Either AuthError ([Text], [Text]))
protectedResourceMetadata p fromHeader = do
  let base = p.endpoint.origin
      path = case canonicalResource p.config.endpoint >>= Text.stripPrefix (originPrefix p) of
        Just pth | not (Text.null pth) -> pth
        _ -> ""
      candidates = case fromHeader of
        Just u -> [u]
        Nothing -> [wellKnown base ("/.well-known/oauth-protected-resource" <> path) | not (Text.null path)] <> [wellKnown base "/.well-known/oauth-protected-resource"]
  tryEach candidates
  where
    tryEach [] = pure (Left (AuthMetadataUnavailable "no protected resource metadata was found"))
    tryEach (u : us) = do
      r <- getJson p u
      case r of
        Right (Object o) -> pure (validatePrm o)
        Right _ -> pure (Left (AuthMetadataUnavailable "protected resource metadata is not an object"))
        Left (AuthMetadataUnavailable _) -> tryEach us
        Left e -> pure (Left e)
    validatePrm o = do
      res <- case KeyMap.lookup "resource" o of
        Just (String r) -> Right r
        _ -> Left (AuthMetadataUnavailable "protected resource metadata has no resource")
      unless (canonicalResource res == Just p.resource) (Left (AuthWrongResource (Text.take 120 res)))
      servers <- case KeyMap.lookup "authorization_servers" o of
        Just (Array xs) -> Right [s | String s <- foldr (:) [] xs]
        _ -> Left (AuthMetadataUnavailable "protected resource metadata lists no authorization servers")
      let supported = case KeyMap.lookup "scopes_supported" o of
            Just (Array xs) -> [s | String s <- foldr (:) [] xs]
            _ -> []
      Right (servers, supported)

originPrefix :: OAuthProvider -> Text
originPrefix p = p.endpoint.scheme <> "://" <> Text.takeWhile (/= '/') (Text.drop (Text.length p.endpoint.scheme + 3) p.resource)

wellKnown :: Text -> Text -> Text
wellKnown origin path =
  -- origin is scheme://host:port; render without a default port.
  let (sch, rest) = Text.breakOn "://" origin
      hostPort = Text.drop 3 rest
      shown = case Text.stripSuffix (if sch == "https" then ":443" else ":80") hostPort of
        Just h -> h
        Nothing -> hostPort
   in sch <> "://" <> shown <> path

-- | Authorization server metadata, tried at the RFC 8414 and OpenID
-- Connect locations in the specified order, accepted only when its
-- @issuer@ is identical to the one requested and it supports PKCE S256.
asMetadata :: OAuthProvider -> Text -> IO (Either AuthError AsMetadata)
asMetadata p iss = do
  cached <- Map.lookup iss <$> readIORef p.asCache
  case cached of
    Just m -> pure (Right m)
    Nothing -> case parseEndpoint iss of
      Left _ -> pure (Left (AuthConfigInvalid "the authorization server issuer is not a URL"))
      Right iep -> do
        let path = let ip = issuerPath iss in fromMaybe ip (Text.stripSuffix "/" ip)
            root = wellKnown iep.origin
            candidates
              | Text.null path = [root "/.well-known/oauth-authorization-server", root "/.well-known/openid-configuration"]
              | otherwise =
                  [ root ("/.well-known/oauth-authorization-server" <> path),
                    root ("/.well-known/openid-configuration" <> path),
                    root (path <> "/.well-known/openid-configuration")
                  ]
        r <- tryEach candidates
        case r of
          Right m -> atomicModifyIORef' p.asCache (\c -> (Map.insert iss m c, ())) >> pure (Right m)
          Left e -> pure (Left e)
  where
    issuerPath i = let afterScheme = Text.drop 3 (snd (Text.breakOn "://" i)) in snd (Text.breakOn "/" afterScheme)
    tryEach [] = pure (Left (AuthMetadataUnavailable "no authorization server metadata was found"))
    tryEach (u : us) = do
      r <- getJson p u
      case r of
        Right (Object o) -> pure (validate o)
        Right _ -> pure (Left (AuthMetadataUnavailable "authorization server metadata is not an object"))
        Left (AuthMetadataUnavailable _) -> tryEach us
        Left e -> pure (Left e)
    validate o = do
      let str k = case KeyMap.lookup k o of
            Just (String s) -> Just s
            _ -> Nothing
          strs k = case KeyMap.lookup k o of
            Just (Array xs) -> [s | String s <- foldr (:) [] xs]
            _ -> []
          flag k = KeyMap.lookup k o == Just (Bool True)
      unless (str "issuer" == Just iss) (Left (AuthIssuerMismatch (Text.take 120 (fromMaybe "" (str "issuer")))))
      unless ("S256" `elem` strs "code_challenge_methods_supported") (Left AuthPkceUnsupported)
      authz <- maybe (Left (AuthMetadataUnavailable "no authorization_endpoint")) Right (str "authorization_endpoint")
      tok <- maybe (Left (AuthMetadataUnavailable "no token_endpoint")) Right (str "token_endpoint")
      mapM_ (destinationOk p) ([authz, tok] <> maybe [] pure (str "registration_endpoint"))
      Right
        AsMetadata
          { issuer = iss,
            authorizationEndpoint = authz,
            tokenEndpoint = tok,
            registrationEndpoint = str "registration_endpoint",
            issParameterSupported = flag "authorization_response_iss_parameter_supported",
            cimdSupported = flag "client_id_metadata_document_supported",
            tokenAuthMethods = strs "token_endpoint_auth_methods_supported"
          }

-- | HTTPS, or HTTP to a loopback host when allowed.
destinationOk :: OAuthProvider -> Text -> Either AuthError ()
destinationOk p u = case parseEndpoint u of
  Left _ -> Left (AuthDestinationRefused (Text.take 120 u))
  Right ep
    | ep.scheme == "https" -> Right ()
    | p.config.allowLoopbackHttp && ep.host `elem` ["127.0.0.1", "localhost", "[::1]"] -> Right ()
    | otherwise -> Left (AuthDestinationRefused ("authorization endpoints must use HTTPS: " <> ep.rendered))

-- | Pre-registered, then Client ID Metadata Document, then (when allowed)
-- dynamic registration. Registrations are keyed by issuer and never
-- reused for another.
registrationFor :: OAuthProvider -> AsMetadata -> IO (Either AuthError ClientRegistration)
registrationFor p meta = case [r | r <- p.config.preRegistered, r.issuer == meta.issuer] of
  (r : _) -> pure (Right r)
  [] -> case p.config.clientMetadataDocument of
    Just doc | meta.cimdSupported -> pure (Right ClientRegistration {clientId = doc, clientSecret = Nothing, issuer = meta.issuer})
    _ -> do
      stored <- p.store.loadRegistration meta.issuer
      case stored of
        Just r | r.issuer == meta.issuer -> pure (Right r)
        _ -> case meta.registrationEndpoint of
          Just regUrl | p.config.allowDynamicRegistration -> dynamicRegistration p meta regUrl
          _ -> pure (Left (AuthNoRegistration ("no client registration is available for " <> meta.issuer <> "; pre-register a client or host a client metadata document")))

dynamicRegistration :: OAuthProvider -> AsMetadata -> Text -> IO (Either AuthError ClientRegistration)
dynamicRegistration p meta regUrl = do
  let body =
        object
          [ "client_name" .= p.config.clientName,
            "redirect_uris" .= [p.config.redirectUri],
            "grant_types" .= ["authorization_code", "refresh_token" :: Text],
            "response_types" .= ["code" :: Text],
            "token_endpoint_auth_method" .= ("none" :: Text),
            "application_type" .= (case p.config.applicationType of NativeApplication -> "native" :: Text; WebApplication -> "web")
          ]
  r <- sendJson p "POST" regUrl [(hContentType, "application/json")] (BS.toStrict (Aeson.encode body))
  case r of
    Left e -> pure (Left e)
    Right (st, v)
      | st >= 200 && st < 300,
        Object o <- v,
        Just (String cid) <- KeyMap.lookup "client_id" o -> do
          let reg = ClientRegistration {clientId = cid, clientSecret = case KeyMap.lookup "client_secret" o of Just (String s) -> Just (Secret (TE.encodeUtf8 s)); _ -> Nothing, issuer = meta.issuer}
          p.store.saveRegistration reg
          pure (Right reg)
      | otherwise -> pure (Left (AuthRegistrationFailed ("the registration endpoint answered HTTP " <> Text.pack (show st))))

-- ---------------------------------------------------------------------------
-- Token endpoint

tokenRequest :: OAuthProvider -> AsMetadata -> ClientRegistration -> [(Text, Text)] -> IO (Either AuthError TokenSet)
tokenRequest p meta client params = do
  let (authHeaders, clientParams) = case client.clientSecret of
        Nothing -> ([], [("client_id", client.clientId)])
        Just (Secret s)
          | null meta.tokenAuthMethods || "client_secret_basic" `elem` meta.tokenAuthMethods ->
              ([(hAuthorization, "Basic " <> B64.encode (TE.encodeUtf8 (formEncode client.clientId) <> ":" <> TE.encodeUtf8 (formEncode (TE.decodeUtf8 s))))], [])
          | otherwise -> ([], [("client_id", client.clientId), ("client_secret", TE.decodeUtf8 s)])
      form = renderForm (params <> clientParams)
  r <- sendJson p "POST" meta.tokenEndpoint ((hContentType, "application/x-www-form-urlencoded") : authHeaders) form
  now <- getCurrentTime
  pure $ case r of
    Left e -> Left e
    Right (st, Object o)
      | st >= 200 && st < 300 -> do
          tok <- case KeyMap.lookup "access_token" o of
            Just (String t) | not (Text.null t) -> Right t
            _ -> Left (AuthTokenRequestFailed "the token response has no access_token")
          case KeyMap.lookup "token_type" o of
            Just (String t) | Text.toLower t == "bearer" -> Right ()
            _ -> Left (AuthTokenRequestFailed "the token response is not a bearer token")
          let expires = case KeyMap.lookup "expires_in" o of
                Just (Number n) -> Just (addUTCTime (realToFrac n) now)
                _ -> Nothing
              refresh = case KeyMap.lookup "refresh_token" o of
                Just (String t) | not (Text.null t) -> Just (Secret (TE.encodeUtf8 t))
                _ -> Nothing
              granted = case KeyMap.lookup "scope" o of
                Just (String s) -> Text.words s
                _ -> []
          Right TokenSet {accessToken = Secret (TE.encodeUtf8 tok), refreshToken = refresh, expiresAt = expires, grantedScopes = granted}
      | otherwise -> Left (AuthTokenRequestFailed (oauthErrorCode o))
    Right (st, _) -> Left (AuthTokenRequestFailed ("the token endpoint answered HTTP " <> Text.pack (show st)))
  where
    oauthErrorCode o = case KeyMap.lookup "error" o of
      Just (String e) | Text.all (\c -> isAscii c && (isAlphaNum c || c == '_')) e -> Text.take 64 e
      _ -> "token_request_rejected"

formEncode :: Text -> Text
formEncode t = TE.decodeUtf8 (BS.drop 1 (BS.toStrict (builderToLazy (renderQueryText False [("", Just t)]))))

renderForm :: [(Text, Text)] -> ByteString
renderForm ps = BS.toStrict (builderToLazy (renderQueryText False [(k, Just v) | (k, v) <- ps]))

-- ---------------------------------------------------------------------------
-- HTTP to authorization servers

getJson :: OAuthProvider -> Text -> IO (Either AuthError Value)
getJson p u = do
  r <- sendJson p "GET" u [] BS.empty
  pure $ case r of
    Left e -> Left e
    Right (st, v)
      | st >= 200 && st < 300 -> Right v
      | otherwise -> Left (AuthMetadataUnavailable ("HTTP " <> Text.pack (show st) <> " from " <> Text.take 120 u))

-- | One bounded request with no redirects to a validated destination.
sendJson :: OAuthProvider -> ByteString -> Text -> [(HeaderName, ByteString)] -> ByteString -> IO (Either AuthError (Int, Value))
sendJson p method u hdrs body = case destinationOk p u of
  Left e -> pure (Left e)
  Right () -> case HTTP.parseRequest @(Either SomeException) (Text.unpack u) of
    Left _ -> pure (Left (AuthDestinationRefused (Text.take 120 u)))
    Right base -> do
      let req =
            base
              { HTTP.method = method,
                HTTP.redirectCount = 0,
                HTTP.checkResponse = \_ _ -> pure (),
                HTTP.responseTimeout = HTTP.responseTimeoutNone,
                HTTP.requestHeaders = (hAccept, "application/json") : hdrs,
                HTTP.requestBody = HTTP.RequestBodyBS body
              }
          micros = max 1 (floor (realToFrac p.config.requestTimeout * 1000000 :: Double))
      r <- try @SomeException (timeout micros (HTTP.withResponse req p.manager (\resp -> (statusOf resp,) <$> readBounded 1048576 (HTTP.responseBody resp))))
      case r of
        Left e -> rethrowAsync e >> pure (Left (AuthTransport "the authorization server could not be reached"))
        Right Nothing -> pure (Left (AuthTransport "the authorization server did not answer in time"))
        Right (Just (_, Left _)) -> pure (Left (AuthTransport "the authorization server's response is too large"))
        Right (Just (st, Right bytes))
          | BS.null bytes -> pure (Right (st, Null))
          | otherwise -> pure (Right (st, fromMaybe Null (Aeson.decodeStrict bytes)))

-- ---------------------------------------------------------------------------
-- Loopback authorizer

data LoopbackConfig = LoopbackConfig
  { -- | Port on 127.0.0.1 named by the registered redirect URI.
    port :: !Int,
    callbackPath :: !Text,
    -- | Open the authorization URL (in a browser, or by printing it).
    present :: AuthorizationRequest -> IO (),
    -- | How long to wait for the redirect.
    waitFor :: !NominalDiffTime
  }

-- | Present the request, then accept one redirect on @127.0.0.1@ within
-- the deadline. The listener is closed on return, timeout or exception.
loopbackAuthorizer :: LoopbackConfig -> InteractiveAuthorizer
loopbackAuthorizer lc = InteractiveAuthorizer $ \req ->
  bracket openListener Net.close $ \sock -> do
    lc.present req
    r <- timeout (max 1 (floor (realToFrac lc.waitFor * 1000000 :: Double))) (acceptCallback sock)
    pure (fromMaybe (Left "no authorization redirect arrived in time") r)
  where
    openListener = do
      sock <- Net.socket Net.AF_INET Net.Stream Net.defaultProtocol
      Net.setSocketOption sock Net.ReuseAddr 1
      Net.bind sock (Net.SockAddrInet (fromIntegral lc.port) (Net.tupleToHostAddress (127, 0, 0, 1)))
      Net.listen sock 4
      pure sock
    acceptCallback sock = do
      (conn, _) <- Net.accept sock
      bracket (pure conn) Net.close $ \c -> do
        reqLine <- readRequestHead c BS.empty
        let target = case BS8.words (BS8.takeWhile (/= '\r') reqLine) of
              (_ : t : _) -> t
              _ -> ""
            (path, query) = BS8.break (== '?') target
            params = [(k, fromMaybe "" v) | (k, v) <- parseQueryText (BS.drop 1 query)]
        NetBS.sendAll c "HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\nAuthorization received. You can close this window.\n"
        if TE.decodeUtf8Lenient path /= lc.callbackPath
          then acceptCallback sock
          else pure (Right (AuthorizationCallback params))
    readRequestHead c acc
      | BS.length acc > 16384 = pure acc
      | "\r\n\r\n" `BS.isInfixOf` acc = pure acc
      | otherwise = do
          chunk <- NetBS.recv c 4096
          if BS.null chunk then pure acc else readRequestHead c (acc <> chunk)

builderToLazy :: Builder.Builder -> LBS.ByteString
builderToLazy = Builder.toLazyByteString