baikai-mcp-0.1.0.0: test/AuthSpec.hs
module AuthSpec (tests) where
import Baikai.Mcp.Auth
import Baikai.Mcp.Client
import Baikai.Mcp.Protocol
import Baikai.Mcp.Tool
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.Async (concurrently)
import Control.Concurrent.MVar
import Control.Exception (SomeException, try)
import Control.Monad (void)
import Data.Aeson (Value (..), object, (.=))
import Data.Aeson.KeyMap qualified as KeyMap
import Data.ByteString (ByteString)
import Data.ByteString.Char8 qualified as BS8
import Data.ByteString.Lazy qualified as LBS
import Data.IORef
import Data.List (isInfixOf)
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 McpStub
import Network.HTTP.Client qualified as HTTP
import Network.HTTP.Client.TLS qualified as TLS
import Network.HTTP.Types (parseQueryText)
import Network.Socket qualified as Net
import System.Timeout (timeout)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (Assertion, assertBool, assertFailure, testCase, (@?=))
tests :: TestTree
tests =
testGroup
"Authentication"
[ static,
oauth,
loopback
]
-- | Every secret in these tests contains SENTINEL, so a leak is easy to
-- spot in any rendered value.
noLeak :: String -> Assertion
noLeak shown = assertBool ("a secret was rendered: " <> take 300 shown) (not ("SENTINEL" `isInfixOf` shown))
-- ---------------------------------------------------------------------------
-- Static credentials
resolverFrom :: IORef (Map.Map Text ByteString) -> CredentialResolver
resolverFrom ref = CredentialResolver $ \r -> do
m <- readIORef ref
pure (maybe (Left "unknown reference") (Right . secret) (Map.lookup r.refName m))
protectedStatic :: IORef ByteString -> ModernHandler -> Stub -> StubRequest -> IO StubReply
protectedStatic expected inner stub r = do
want <- readIORef expected
if header "Authorization" r == Just ("Bearer " <> want) && header "X-Api-Key" r == Just "key-SENTINEL"
then modernServer inner stub r
else pure (ReplyRaw 401 [("WWW-Authenticate", "Bearer realm=\"stub\"")] "")
static :: TestTree
static =
testGroup
"static credentials"
[ testCase "anonymous access is refused; scoped references are accepted and rotate" $ do
expected <- newIORef "bearer-SENTINEL-1"
values <- newIORef (Map.fromList [("api-bearer", "bearer-SENTINEL-1"), ("api-key", "key-SENTINEL")])
withStub (protectedStatic expected (\_ r _ _ -> pure (discover r))) $ \stub -> do
anon <- connectMcp (config stub) >>= expectErr
anon.httpStatus @?= Just 401
hook <-
either (\e -> assertFailure (show e) >> error "unreachable") pure $
staticCredentialHook stub.url (resolverFrom values) StaticCredentials {bearer = Just (CredentialRef "api-bearer"), headers = [("X-Api-Key", CredentialRef "api-key")]}
c <- connectOrFail (config stub) {requestHook = hook}
writeIORef expected "bearer-SENTINEL-2"
modifyIORef' values (Map.insert "api-bearer" "bearer-SENTINEL-2")
r <- callMethod c (mcpCall "server/discover" KeyMap.empty)
assertBool "rotated credential accepted" (either (const False) (const True) r)
closeMcp c
noLeak (show anon),
testCase "credentials are never released to another origin" $ do
values <- newIORef (Map.fromList [("t", "tok-SENTINEL")])
hook <-
either (\e -> assertFailure (show e) >> error "unreachable") pure $
staticCredentialHook "https://mcp.example.com/mcp" (resolverFrom values) StaticCredentials {bearer = Just (CredentialRef "t"), headers = []}
d <- runRequestHook hook (attemptAt "https://evil.example.com:443")
case d of
SendDenied _ -> pure ()
other -> assertFailure (show other)
d2 <- runRequestHook hook (attemptAt "https://mcp.example.com:443")
case d2 of
SendAllowed [h] -> do
sendHeaderName h @?= "Authorization"
noLeak (show h)
other -> assertFailure (show other),
testCase "invalid, reserved and duplicate header names are configuration errors" $ do
let mk hs = staticCredentialHook "https://mcp.example.com/mcp" (CredentialResolver (\_ -> pure (Left "x"))) StaticCredentials {bearer = Nothing, headers = hs}
mapM_
(\hs -> assertBool (show (map fst hs)) (either (const True) (const False) (mk hs)))
[ [("Authorization", CredentialRef "a")],
[("Mcp-Method", CredentialRef "a")],
[("Bad Header", CredentialRef "a")],
[("X-Key", CredentialRef "a"), ("x-key", CredentialRef "b")]
]
assertBool "embedded credentials in the endpoint" . either (const True) (const False) $
staticCredentialHook "https://u:p@mcp.example.com/mcp" (CredentialResolver (\_ -> pure (Left "x"))) noStaticCredentials,
testCase "a value with a line break is refused" $ do
values <- newIORef (Map.fromList [("t", "tok-SENTINEL\r\nX-Injected: 1")])
hook <-
either (\e -> assertFailure (show e) >> error "unreachable") pure $
staticCredentialHook "https://mcp.example.com/mcp" (resolverFrom values) StaticCredentials {bearer = Just (CredentialRef "t"), headers = []}
d <- runRequestHook hook (attemptAt "https://mcp.example.com:443")
case d of
SendDenied why -> noLeak (show why)
other -> assertFailure (show other),
testCase "cancellation before the first send transmits nothing" $ do
gate <- newEmptyMVar
withStub (modernServer (\_ r _ _ -> pure (discover r))) $ \stub -> do
let blocking = CredentialResolver (\_ -> takeMVar gate >> pure (Right (secret "late-SENTINEL")))
hook <-
either (\e -> assertFailure (show e) >> error "unreachable") pure $
staticCredentialHook stub.url blocking StaticCredentials {bearer = Just (CredentialRef "t"), headers = []}
r <- timeout 200000 (connectMcp (config stub) {requestHook = hook})
case r of
Nothing -> pure ()
Just _ -> assertFailure "expected the connect to be cancelled"
length <$> stub.requests >>= (@?= 0)
]
attemptAt :: Text -> SendAttempt
attemptAt o =
SendAttempt
{ serverName = "s",
endpoint = o,
origin = o,
method = "server/discover",
target = Nothing,
cursor = Nothing,
purpose = PurposeDiscovery
}
-- ---------------------------------------------------------------------------
-- OAuth fixture
data AsVariant = AsVariant
{ issuerOverride :: Maybe Text,
pkce :: Bool,
issSupported :: Bool,
cimd :: Bool,
registration :: Bool,
expiresIn :: Int,
prmResourceOverride :: Maybe Text
}
baseVariant :: AsVariant
baseVariant = AsVariant Nothing True True False False 3600 Nothing
data AsState = AsState
{ codes :: IORef (Map.Map Text (Text, Text, Text, Text)),
validAccess :: IORef [ByteString],
validRefresh :: IORef [Text],
tokenRequests :: IORef [[(Text, Text)]],
registrations :: IORef [Value],
serial :: IORef Int,
mcpResource :: IORef Text
}
newAsState :: IO AsState
newAsState = AsState <$> newIORef Map.empty <*> newIORef [] <*> newIORef [] <*> newIORef [] <*> newIORef [] <*> newIORef 0 <*> newIORef ""
baseOf :: Stub -> Text
baseOf stub = fromMaybe stub.url (Text.stripSuffix "/mcp" stub.url)
formOf :: StubRequest -> [(Text, Text)]
formOf r = [(k, fromMaybe "" v) | (k, v) <- parseQueryText (LBS.toStrict r.body)]
asServer :: AsVariant -> AsState -> Stub -> StubRequest -> IO StubReply
asServer v st stub r = case (r.httpMethod, r.path) of
("GET", "/.well-known/oauth-authorization-server") ->
pure . ok . object $
[ "issuer" .= fromMaybe (baseOf stub) v.issuerOverride,
"authorization_endpoint" .= (baseOf stub <> "/authorize"),
"token_endpoint" .= (baseOf stub <> "/token"),
"authorization_response_iss_parameter_supported" .= v.issSupported,
"client_id_metadata_document_supported" .= v.cimd
]
<> ["code_challenge_methods_supported" .= ["S256" :: Text] | v.pkce]
<> ["registration_endpoint" .= (baseOf stub <> "/register") | v.registration]
("POST", "/register") -> do
modifyIORef' st.registrations (<> [fromMaybe Null r.json])
pure (ReplyJson 201 [] (object ["client_id" .= ("dyn-client" :: Text)]))
("POST", "/token") -> do
let form = formOf r
get k = lookup k form
modifyIORef' st.tokenRequests (<> [form])
expectedResource <- readIORef st.mcpResource
case get "grant_type" of
Just "authorization_code" -> do
cs <- readIORef st.codes
case get "code" >>= (`Map.lookup` cs) of
Just (challenge, redirect, resource, client)
| Just (pkceChallenge (fromMaybe "" (get "code_verifier"))) == Just challenge,
get "redirect_uri" == Just redirect,
get "resource" == Just resource,
resource == expectedResource,
get "client_id" == Just client -> do
modifyIORef' st.codes (Map.delete (fromMaybe "" (get "code")))
issue v.expiresIn
_ -> pure (ReplyJson 400 [] (object ["error" .= ("invalid_grant" :: Text)]))
Just "refresh_token" -> do
valid <- readIORef st.validRefresh
case get "refresh_token" of
Just rt
| rt `elem` valid,
get "resource" == Just expectedResource -> do
modifyIORef' st.validRefresh (filter (/= rt))
issue 3600
_ -> pure (ReplyJson 400 [] (object ["error" .= ("invalid_grant" :: Text)]))
_ -> pure (ReplyJson 400 [] (object ["error" .= ("unsupported_grant_type" :: Text)]))
_ -> pure (ReplyRaw 404 [] "")
where
issue lifetime = do
n <- atomicModifyIORef' st.serial (\x -> (x + 1, x + 1))
let at = "AT-SENTINEL-" <> Text.pack (show n)
rt = "RT-SENTINEL-" <> Text.pack (show n)
modifyIORef' st.validAccess (<> [TE.encodeUtf8 at])
modifyIORef' st.validRefresh (<> [rt])
pure (ok (object ["access_token" .= at, "token_type" .= ("Bearer" :: Text), "expires_in" .= (lifetime :: Int), "refresh_token" .= rt, "scope" .= ("files:read" :: Text)]))
-- | A protected modern MCP server. Its tools/call for "write_file" needs a
-- scope the grant lacks.
mcpServer :: AsVariant -> Stub -> AsState -> Stub -> StubRequest -> IO StubReply
mcpServer v as st stub r
| r.httpMethod == "GET" && r.path == "/.well-known/oauth-protected-resource/mcp" =
pure . ok $ object ["resource" .= fromMaybe stub.url v.prmResourceOverride, "authorization_servers" .= [baseOf as], "scopes_supported" .= ["files:read" :: Text]]
| otherwise = do
valid <- readIORef st.validAccess
case header "Authorization" r >>= BS8.stripPrefix "Bearer " of
Just tok | tok `elem` valid -> modernServer inner stub r
_ -> pure (ReplyRaw 401 [("WWW-Authenticate", TE.encodeUtf8 ("Bearer resource_metadata=\"" <> baseOf stub <> "/.well-known/oauth-protected-resource/mcp\", scope=\"files:read\""))] "")
where
inner _ req m p = pure $ case m of
"server/discover" -> discover req
"tools/list" -> okResult req ["tools" .= [object ["name" .= ("write_file" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text)]]]]
"tools/call" | KeyMap.lookup "name" p == Just "write_file" -> ReplyRaw 403 [("WWW-Authenticate", "Bearer error=\"insufficient_scope\", scope=\"files:write\"")] ""
"tools/call" | KeyMap.lookup "name" p == Just "ghost" -> ReplySse 200 [] [Chunk ":\n\n"]
_ -> rpcErrorReply 404 req (-32601) "no" Nothing
-- | Acts as the browser and the authorization server's consent page.
data Consent = Consent {issParam :: Maybe (Maybe Text), stateOverride :: Maybe Text, errorParam :: Maybe Text}
consent :: Consent
consent = Consent Nothing Nothing Nothing
scriptedAuthorizer :: AsState -> Stub -> Consent -> IORef [(Text, Text)] -> InteractiveAuthorizer
scriptedAuthorizer st as c seen = InteractiveAuthorizer $ \req -> do
let query = snd (Text.breakOn "?" req.authorizationUrl)
params = [(k, fromMaybe "" val) | (k, val) <- parseQueryText (TE.encodeUtf8 (Text.drop 1 query))]
get k = fromMaybe "" (lookup k params)
writeIORef seen params
n <- atomicModifyIORef' st.serial (\x -> (x + 1, x + 1))
let code = "CODE-SENTINEL-" <> Text.pack (show n)
modifyIORef' st.codes (Map.insert code (get "code_challenge", get "redirect_uri", get "resource", get "client_id"))
let iss = fromMaybe (Just (baseOf as)) c.issParam
pure . Right . AuthorizationCallback $
maybe [("code", code)] (\e -> [("error", e), ("error_description", "SENTINEL description")]) c.errorParam
<> [("state", fromMaybe (get "state") c.stateOverride)]
<> maybe [] (\i -> [("iss", i)]) iss
data Env = Env {as :: Stub, mcp :: Stub, st :: AsState, mgr :: HTTP.Manager}
withOAuth :: AsVariant -> (Env -> IO a) -> IO a
withOAuth v k = do
st <- newAsState
mgr <- TLS.newTlsManager
withStub (asServer v st) $ \asStub ->
withStub (mcpServer v asStub st) $ \mcpStub -> do
writeIORef st.mcpResource mcpStub.url
k Env {as = asStub, mcp = mcpStub, st = st, mgr = mgr}
providerFor :: Env -> (OAuthConfig -> OAuthConfig) -> IO (OAuthProvider, TokenStore)
providerFor env f = do
store <- newInMemoryTokenStore
let cfg = (oauthConfig env.mcp.url "alice" "http://127.0.0.1:53682/callback") {preRegistered = [ClientRegistration "pre-client" Nothing (baseOf env.as)]}
r <- newOAuthProvider env.mgr store (f cfg)
case r of
Right p -> pure (p, store)
Left e -> assertFailure (show e) >> error "unreachable"
challengeOf :: Env -> IO (Maybe Text)
challengeOf env = do
e <- connectMcp (config env.mcp) >>= expectErr
e.httpStatus @?= Just 401
pure e.challenge
tokenCount :: Env -> IO Int
tokenCount env = length <$> readIORef env.st.tokenRequests
oauth :: TestTree
oauth =
testGroup
"delegated OAuth"
[ testCase "challenge, discovery, consent and token exchange reach the protected resource" $
withOAuth baseVariant $ \env -> do
seen <- newIORef []
(p, store) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent seen)})
ch <- challengeOf env
r <- authorizeFromChallenge p ch []
r @?= Right Authorized
params <- readIORef seen
lookup "response_type" params @?= Just "code"
lookup "code_challenge_method" params @?= Just "S256"
lookup "resource" params @?= Just env.mcp.url
lookup "scope" params @?= Just "files:read"
lookup "client_id" params @?= Just "pre-client"
[form] <- readIORef env.st.tokenRequests
lookup "resource" form @?= Just env.mcp.url
lookup "redirect_uri" form @?= lookup "redirect_uri" params
c <- connectOrFail (config env.mcp) {requestHook = oauthRequestHook p}
closeMcp c
g <- store.loadGrant "alice" env.mcp.url
fmap (.issuer) g @?= Just (baseOf env.as)
noLeak (show g),
testCase "a redirect from another issuer is never redeemed" $
withOAuth baseVariant $ \env -> do
seen <- newIORef []
(p, _) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent {issParam = Just (Just "https://evil.example")} seen)})
ch <- challengeOf env
authorizeFromChallenge p ch [] >>= (@?= Left AuthCallbackIssuerMismatch)
tokenCount env >>= (@?= 0),
testCase "a missing iss is rejected when the server advertises it" $
withOAuth baseVariant $ \env -> do
seen <- newIORef []
(p, _) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent {issParam = Just Nothing} seen)})
ch <- challengeOf env
authorizeFromChallenge p ch [] >>= (@?= Left AuthCallbackIssuerMismatch)
tokenCount env >>= (@?= 0),
testCase "a missing iss is accepted when the server does not advertise it" $
withOAuth baseVariant {issSupported = False} $ \env -> do
seen <- newIORef []
(p, _) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent {issParam = Just Nothing} seen)})
ch <- challengeOf env
authorizeFromChallenge p ch [] >>= (@?= Right Authorized),
testCase "an error response from the wrong issuer is not acted on" $
withOAuth baseVariant $ \env -> do
seen <- newIORef []
(p, _) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent {issParam = Just (Just "https://evil.example"), errorParam = Just "access_denied"} seen)})
ch <- challengeOf env
r <- authorizeFromChallenge p ch []
r @?= Left AuthCallbackIssuerMismatch
noLeak (show r),
testCase "a wrong state is rejected before redemption" $
withOAuth baseVariant $ \env -> do
seen <- newIORef []
(p, _) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent {stateOverride = Just "forged"} seen)})
ch <- challengeOf env
authorizeFromChallenge p ch [] >>= (@?= Left AuthStateMismatch)
tokenCount env >>= (@?= 0),
testCase "metadata naming a different issuer is not used" $
withOAuth baseVariant {issuerOverride = Just "https://honest.example"} $ \env -> do
(p, _) <- providerFor env id
ch <- challengeOf env
r <- authorizeFromChallenge p ch []
case r of
Left (AuthIssuerMismatch _) -> pure ()
other -> assertFailure (show other),
testCase "resource metadata for another resource is refused" $
withOAuth baseVariant {prmResourceOverride = Just "https://other.example/mcp"} $ \env -> do
(p, _) <- providerFor env id
ch <- challengeOf env
r <- authorizeFromChallenge p ch []
case r of
Left (AuthWrongResource _) -> pure ()
other -> assertFailure (show other),
testCase "an authorization server without PKCE S256 is refused" $
withOAuth baseVariant {pkce = False} $ \env -> do
(p, _) <- providerFor env id
ch <- challengeOf env
authorizeFromChallenge p ch [] >>= (@?= Left AuthPkceUnsupported),
testCase "an unattended host gets an interaction-required outcome" $
withOAuth baseVariant $ \env -> do
(p, _) <- providerFor env id
ch <- challengeOf env
r <- authorizeFromChallenge p ch []
case r of
Right (InteractionRequired req) -> do
req.issuer @?= baseOf env.as
assertBool "authorization URL" ("/authorize?" `Text.isInfixOf` req.authorizationUrl)
other -> assertFailure (show other)
tokenCount env >>= (@?= 0),
testCase "the well-known fallback finds metadata without a challenge" $
withOAuth baseVariant $ \env -> do
seen <- newIORef []
(p, _) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent seen)})
authorizeFromChallenge p Nothing [] >>= (@?= Right Authorized),
testCase "two parallel requests with an expired token cause one rotation" $
withOAuth baseVariant {expiresIn = 1} $ \env -> do
seen <- newIORef []
(p, store) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent seen)})
ch <- challengeOf env
authorizeFromChallenge p ch [] >>= (@?= Right Authorized)
let cfg = (config env.mcp) {requestHook = oauthRequestHook p}
(a, b) <- concurrently (connectMcp cfg) (connectMcp cfg)
assertBool "both connected" (either (const False) (const True) a && either (const False) (const True) b)
forms <- readIORef env.st.tokenRequests
length [f | f <- forms, lookup "grant_type" f == Just "refresh_token"] @?= 1
g <- store.loadGrant "alice" env.mcp.url
fmap (fmap revealSecret . (.tokens.refreshToken)) g @?= Just (Just "RT-SENTINEL-3")
mapM_ (either (const (pure ())) closeMcp) [a, b],
testCase "a revoked grant asks for a fresh authorization" $
withOAuth baseVariant {expiresIn = 1} $ \env -> do
seen <- newIORef []
(p, store) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent seen)})
ch <- challengeOf env
authorizeFromChallenge p ch [] >>= (@?= Right Authorized)
writeIORef env.st.validRefresh []
e <- connectMcp (config env.mcp) {requestHook = oauthRequestHook p} >>= expectErr
e.httpStatus @?= Just 401
store.loadGrant "alice" env.mcp.url >>= (@?= Nothing)
r <- recoverFromChallenge p e
case r of
Right (AccessDenied _) -> pure ()
other -> assertFailure (show other),
testCase "a 401 with a refreshable grant recovers by refreshing once" $
withOAuth baseVariant $ \env -> do
seen <- newIORef []
(p, _) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent seen)})
ch <- challengeOf env
authorizeFromChallenge p ch [] >>= (@?= Right Authorized)
writeIORef env.st.validAccess []
e <- connectMcp (config env.mcp) {requestHook = oauthRequestHook p} >>= expectErr
recoverFromChallenge p e >>= (@?= Right Authorized)
c <- connectOrFail (config env.mcp) {requestHook = oauthRequestHook p}
closeMcp c,
testCase "insufficient scope is reported, not silently widened; other 403s stay denied" $
withOAuth baseVariant $ \env -> do
seen <- newIORef []
(p, _) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent seen)})
ch <- challengeOf env
authorizeFromChallenge p ch [] >>= (@?= Right Authorized)
c <- connectOrFail (config env.mcp) {requestHook = oauthRequestHook p}
listing <- listTools c defaultDrainLimits
writer <- case listing of
Right ToolListing {tools = [t]} -> pure t
other -> assertFailure (show other) >> error "unreachable"
before <- tokenCount env
r <- callTool c (mcpToolCall writer KeyMap.empty)
case r of
Left (ToolRequestFailed e) -> do
recoverFromChallenge p e >>= (@?= Right (InsufficientScope ["files:write"]))
recoverFromChallenge p e {challenge = Nothing} >>= \case
Right (AccessDenied _) -> pure ()
other -> assertFailure (show other)
other -> assertFailure (show other)
tokenCount env >>= (@?= before)
closeMcp c,
testCase "a host policy still denies the repeated page of an authenticated client" $
withOAuth baseVariant $ \env -> do
seen <- newIORef []
(p, _) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent seen)})
ch <- challengeOf env
authorizeFromChallenge p ch [] >>= (@?= Right Authorized)
let policy = McpRequestHook (\att -> pure (if att.method == "tools/list" then SendDenied "not in this run" else SendAllowed []))
c <- connectOrFail (config env.mcp) {requestHook = policy <> oauthRequestHook p}
r <- listToolsPage c Nothing
either (\e -> e.kind @?= RequestDenied) (const (assertFailure "expected a denial")) r
length . filter ((== Just "tools/list") . rpcMethod) <$> env.mcp.requests >>= (@?= 0)
closeMcp c,
testCase "registration: dynamic registration declares a native application; a metadata document needs none" $ do
withOAuth baseVariant {registration = True} $ \env -> do
seen <- newIORef []
(p, store) <- providerFor env (\c -> c {preRegistered = [], allowDynamicRegistration = True, authorizer = Just (scriptedAuthorizer env.st env.as consent seen)})
ch <- challengeOf env
authorizeFromChallenge p ch [] >>= (@?= Right Authorized)
regs <- readIORef env.st.registrations
map (\case Object o -> KeyMap.lookup "application_type" o; _ -> Nothing) regs @?= [Just "native"]
store.loadRegistration (baseOf env.as) >>= (@?= Just (ClientRegistration "dyn-client" Nothing (baseOf env.as)))
withOAuth baseVariant {registration = True, cimd = True} $ \env -> do
seen <- newIORef []
(p, _) <- providerFor env (\c -> c {preRegistered = [], clientMetadataDocument = Just "https://client.example/meta.json", allowDynamicRegistration = True, authorizer = Just (scriptedAuthorizer env.st env.as consent seen)})
ch <- challengeOf env
authorizeFromChallenge p ch [] >>= (@?= Right Authorized)
readIORef env.st.registrations >>= (@?= [])
lookup "client_id" <$> readIORef seen >>= (@?= Just "https://client.example/meta.json")
withOAuth baseVariant $ \env -> do
(p, _) <- providerFor env (\c -> c {preRegistered = []})
ch <- challengeOf env
r <- authorizeFromChallenge p ch []
case r of
Left (AuthNoRegistration _) -> pure ()
other -> assertFailure (show other),
testCase "a broken tool response after authentication is one invocation" $
withOAuth baseVariant $ \env -> do
seen <- newIORef []
(p, _) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent seen)})
ch <- challengeOf env
authorizeFromChallenge p ch [] >>= (@?= Right Authorized)
c <- connectOrFail (config env.mcp) {requestHook = oauthRequestHook p}
let t = either (error . show) id (decodeTool True (object ["name" .= ("ghost" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text)]]))
r <- callTool c (mcpToolCall t KeyMap.empty)
case r of
Left (ToolRequestFailed e) -> noLeak (show e)
other -> assertFailure (show other)
length . filter ((== Just "tools/call") . rpcMethod) <$> env.mcp.requests >>= (@?= 1)
closeMcp c
]
-- ---------------------------------------------------------------------------
-- Loopback
freePort :: IO Int
freePort = do
sock <- Net.socket Net.AF_INET Net.Stream Net.defaultProtocol
Net.bind sock (Net.SockAddrInet 0 (Net.tupleToHostAddress (127, 0, 0, 1)))
port <- Net.socketPort sock
Net.close sock
pure (fromIntegral port)
loopback :: TestTree
loopback =
testGroup
"loopback authorizer"
[ testCase "captures one redirect and releases the port" $ do
port <- freePort
mgr <- TLS.newTlsManager
let browse _ = void . forkIO $ do
threadDelay 50000
req <- HTTP.parseRequest ("http://127.0.0.1:" <> show port <> "/callback?code=CODE-SENTINEL&state=s1&iss=https%3A%2F%2Fas.example")
void (try @SomeException (HTTP.httpLbs req mgr))
authz = loopbackAuthorizer LoopbackConfig {port = port, callbackPath = "/callback", present = browse, waitFor = 5}
r <- runAuthorization authz (AuthorizationRequest "https://as.example/authorize" ("http://127.0.0.1:" <> Text.pack (show port) <> "/callback") "https://as.example" [])
case r of
Right (AuthorizationCallback ps) -> do
lookup "state" ps @?= Just "s1"
lookup "iss" ps @?= Just "https://as.example"
noLeak (show (AuthorizationCallback ps))
Left e -> assertFailure (show e)
again <- runAuthorization (loopbackAuthorizer LoopbackConfig {port = port, callbackPath = "/callback", present = const (pure ()), waitFor = 0.2}) (AuthorizationRequest "u" "r" "i" [])
case again of
Left _ -> pure ()
Right _ -> assertFailure "expected the wait to expire"
]