packages feed

shomei-client 0.3.0.1 → 0.4.0.0

raw patch · 4 files changed

+235/−22 lines, 4 filesdep +containersdep +effectfuldep +effectful-coredep ~shomei-clientdep ~shomei-coredep ~shomei-jwtPVP ok

version bump matches the API change (PVP)

Dependencies added: containers, effectful, effectful-core, servant-server, wai

Dependency ranges changed: shomei-client, shomei-core, shomei-jwt, shomei-migrations, shomei-postgres, shomei-servant, shomei-server

API changes (from Hackage documentation)

+ Shomei.Client: OAuthMethodNotAllowed :: !OAuthErrorWithHeaders -> OAuthResult a
+ Shomei.Client: OAuthNotAcceptable :: !OAuthErrorWithHeaders -> OAuthResult a
+ Shomei.Client: OAuthPayloadTooLarge :: !OAuthErrorWithHeaders -> OAuthResult a
+ Shomei.Client: OAuthTooManyRequests :: !OAuthErrorWithHeaders -> OAuthResult a
+ Shomei.Client: OAuthUnsupportedMediaType :: !OAuthErrorWithHeaders -> OAuthResult a
+ Shomei.Client: adminResetMfa :: ClientEnv -> Token -> UserId -> ResetMfaRequest -> IO (Either ClientError ResetMfaResult)

Files

CHANGELOG.md view
@@ -4,6 +4,14 @@ [PVP](https://pvp.haskell.org/) and is versioned independently of the other Shōmei packages. +## 0.4.0.0 — 2026-11-25++- **Breaking:** require the Shōmei 0.4 API series.++- Add adminResetMfa for the typed administrative recovery route. It performs one destructive request without automatic retry or redirect replay, preserving caller transport settings.++- Generated OAuth clients decode routing and operational 405/406/413/415/429 errors as typed results, preserving optional challenges, Retry-After and Allow. **Source compatibility:** downstream exhaustive OAuthResult matches and OAuthErrorWithHeaders construction must account for the added constructors/field.+ ## 0.3.0.1 — 2026-11-17  - Admit `base64` 2.0 and 2.1 (`>=1.0 && <2.2`). No source or API change.
shomei-client.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.0 name: shomei-client-version: 0.3.0.1+version: 0.4.0.0 synopsis: Haskell client for the standalone Shōmei auth service description:   A typed Haskell client derived from the same ShomeiAPI definition that@@ -64,8 +64,8 @@     servant-client >=0.20.3 && <0.21,     servant-client-core >=0.20.3 && <0.21,     servant-health >=0.1 && <0.2,-    shomei-core ^>=0.3.0.0,-    shomei-servant ^>=0.3.0.0,+    shomei-core ^>=0.4.0.0,+    shomei-servant ^>=0.4.0.0,     text >=2.0 && <2.2,  test-suite shomei-client-test@@ -81,18 +81,24 @@   build-depends:     base >=4.18 && <5,     bytestring >=0.11 && <0.13,+    containers >=0.6 && <0.9,+    effectful >=2.5 && <2.8,+    effectful-core >=2.5 && <2.8,     http-client >=0.7 && <0.8,     http-types >=0.12 && <0.13,+    servant >=0.20.3 && <0.21,     servant-client >=0.20.3 && <0.21,     servant-health >=0.1 && <0.2,-    shomei-client ^>=0.3.0.0,-    shomei-core ^>=0.3.0.0,-    shomei-jwt ^>=0.3.0.0,-    shomei-migrations:test-support ^>=0.2.0.1,-    shomei-postgres ^>=0.3.0.0,-    shomei-servant ^>=0.3.0.0,-    shomei-server ^>=0.3.0.0,+    servant-server >=0.20.3 && <0.21,+    shomei-client ^>=0.4.0.0,+    shomei-core ^>=0.4.0.0,+    shomei-jwt ^>=0.4.0.0,+    shomei-migrations:test-support ^>=0.2.0.2,+    shomei-postgres ^>=0.4.0.0,+    shomei-servant ^>=0.4.0.0,+    shomei-server ^>=0.4.0.0,     tasty >=1.4 && <1.6,     tasty-hunit >=0.10 && <0.11,     text >=2.0 && <2.2,+    wai >=3.2 && <3.3,     warp >=3.3 && <3.5,
src/Shomei/Client.hs view
@@ -62,6 +62,7 @@     adminRevokeSessions,     adminRevokeSession,     adminPasswordReset,+    adminResetMfa,     adminGrantRole,     adminRevokeRole,   )@@ -72,6 +73,7 @@ import Data.Text qualified as Text import Data.Text.Encoding qualified as TE import Network.HTTP.Client qualified as HTTP+import Network.HTTP.Client.Internal qualified as HTTPInternal import Network.HTTP.Client.TLS qualified as TLS  -- Explicitly, as a /type/: 'Shomei.Prelude' re-exports lens, whose @(:>)@ snoc pattern synonym@@ -80,7 +82,7 @@ import Servant.API.Experimental.Auth (AuthProtect) import Servant.Client   ( BaseUrl (..),-    ClientEnv,+    ClientEnv (..),     ClientError,     ClientM,     Scheme (..),@@ -98,7 +100,7 @@ import Servant.Client.Generic (genericClient) import Shomei.Account.Admin.Api qualified as AdminAccount import Shomei.Account.Api qualified as Account-import Shomei.Account.Dto (SignupRequest)+import Shomei.Account.Dto (ResetMfaRequest, SignupRequest) import Shomei.Account.Result import Shomei.Account.User.Dto (AdminStatusFilter, UserPageCursor) import Shomei.Authorization.Api qualified as Authorization@@ -426,3 +428,20 @@ adminRevokeRole :: ClientEnv -> Token -> UserId -> Text -> IO (Either ClientError RevokeRoleResult) adminRevokeRole env tok uid role =   runClient env (Authorization.revokeRole authorizationClient (bearer tok) uid role)++-- | Destructive recovery. Do not retry automatically after an ambiguous transport failure.+adminResetMfa :: ClientEnv -> Token -> UserId -> ResetMfaRequest -> IO (Either ClientError ResetMfaResult)+adminResetMfa env tok uid request = runClient noReplayEnv (AdminAccount.resetMfa adminAccountClient (bearer tok) uid request)+  where+    -- http-client 0.7 retries reused-connection failures for every HTTP method and exposes+    -- no per-request switch. Copy the chosen manager, preserving its pool/TLS/proxy/hooks;+    -- never mutate the caller's manager. Redirects must not replay this operation either.+    -- mori://snoyberg/http-client/packages/http-client+    noReplayEnv =+      env+        { makeClientRequest = \base outgoing -> do+            built <- makeClientRequest env base outgoing+            let transportManager = fromMaybe (manager env) (HTTPInternal.requestManagerOverride built)+                oneAttempt = transportManager {HTTPInternal.mRetryableException = const False}+            pure built {HTTPInternal.requestManagerOverride = Just oneAttempt, HTTP.redirectCount = 0}+        }
test/Main.hs view
@@ -4,28 +4,58 @@ -- server agree on the wire format end-to-end, including the Bearer-authenticated @me@ route. module Main (main) where +import Control.Monad (forM_) import Data.ByteString qualified as BS-import Data.IORef (newIORef)+import Data.ByteString.Char8 qualified as BS8+import Data.IORef (atomicModifyIORef', newIORef, readIORef)+import Data.Set qualified as Set import Data.Text (Text)+import Data.Text qualified as Text+import Effectful (runEff)+import Effectful.Error.Static (runErrorNoCallStack) import Network.HTTP.Client (defaultManagerSettings, newManager)+import Network.HTTP.Client qualified as HTTP+import Network.HTTP.Types (mkStatus)+import Network.Wai (responseLBS)+import Network.Wai qualified as Wai import Network.Wai.Handler.Warp (testWithApplication)+import Servant (ServerError (..))+import Servant.API.MultiVerb (AsUnion (..))+import Servant.Client qualified as ServantClient import Servant.Health (ProbeCheck, ProbeVerdict (Healthy))-import Shomei.Account.Dto (SignupRequest (..), SignupResponse (..))-import Shomei.Account.Password.Hash.Postgres (Argon2Params (..), newHashingLimiter)+import Shomei.Account.Dto (ResetMfaRequest (..), SignupRequest (..), SignupResponse (..))+import Shomei.Account.LoginId.Domain (mkLoginId)+import Shomei.Account.Password.Hash.Postgres (Argon2Params (..), defaultArgon2Params, newHashingLimiter)+import Shomei.Account.User.Domain (NewUser (..), User (..)) import Shomei.Account.User.Dto (UserResponse (..))-import Shomei.Authorization.Claims.Domain (Audience (..), Issuer (..))+import Shomei.Account.User.Postgres (runUserStorePostgres)+import Shomei.Account.User.Store (createUser)+import Shomei.Authorization.Claims.Domain (Audience (..), Issuer (..), Scope (..)) import Shomei.Client qualified as C-import Shomei.Config (defaultShomeiConfig)-import Shomei.Id (parseId)+import Shomei.Config (RateLimitConfig (..), ShomeiConfig (..), defaultShomeiConfig)+import Shomei.Error (AuthError)+import Shomei.Id (genServiceAccountDbId, genUserId, idText, parseId) import Shomei.Mfa.Totp.Postgres (TotpEncryptionKey, totpEncryptionKeyFromBytes) import Shomei.Migrations.TestSupport (withShomeiMigratedDatabase) import Shomei.Notify (noNotifierSecrets) import Shomei.Notify.Queue (newNotifierQueue)-import Shomei.Persistence.Database.Postgres (defaultTransactionRetryPolicy)-import Shomei.Persistence.Pool.Postgres (acquirePool)+import Shomei.OAuth.Boundary (oauthBoundaryError)+import Shomei.OAuth.Result (OAuthErrorWithHeaders (..), TokenResponses, TokenResult, oauthServerErrorResult)+import Shomei.Persistence.Database.Postgres (defaultTransactionRetryPolicy, runDatabasePool)+import Shomei.Persistence.Pool.Postgres (Pool, acquirePool)+import Shomei.Servant.Api (shomeiThrottledRoutes)+import Shomei.Servant.OAuth (OAuthErrorResponse (..), oauthError) import Shomei.Server.App (Env (..))-import Shomei.Server.Boot (application)+import Shomei.Server.Boot (application, hostMiddleware)+import Shomei.Server.Config (ProxyProtocolMode (ProxyProtocolOff), ServerSettings (..), SweepSettings (..), defaultSweepSettings) import Shomei.Server.Keys (bootstrapKeys)+import Shomei.Server.Middleware.RateLimit (newRateLimiterFor)+import Shomei.Server.Middleware.TrustedProxy (emptyTrustedProxies)+import Shomei.Server.Observability.Metrics (newMetrics)+import Shomei.ServiceAccount.Domain (NewServiceAccount (..))+import Shomei.ServiceAccount.Postgres (runServiceAccountStorePostgres)+import Shomei.ServiceAccount.Secret (sha256Hex)+import Shomei.ServiceAccount.Store (createServiceAccount) import Shomei.Session.Dto   ( LoginRequest (..),     LoginResponse (..),@@ -34,6 +64,8 @@   ) import Shomei.SigningKey.Domain (SigningAlgorithm (ES256)) import Shomei.SigningKey.Protection.Jwt (KeyEncryptionKey, keyEncryptionKeyFromBase64)+import Shomei.Time.Postgres (runClockIO)+import Shomei.Time.Store (now) import Test.Tasty (TestTree, defaultMain, testGroup) import Test.Tasty.HUnit (assertFailure, testCase, (@?=)) @@ -52,7 +84,11 @@ tests =   testGroup     "shomei-client round-trip against a live server"-    [ testCase "client bearer diagnostics redact the credential" (show (C.Token "sensitive-bearer") @?= "Token <redacted>"),+    [ testCase "recovery never replays after an ambiguous reused-connection close" (recoveryNoReplay False),+      testCase "recovery never follows a redirect with another destructive request" (recoveryNoReplay True),+      testCase "generated token client decodes every error and optional headers" oauthWireResults,+      testCase "OAuth result union round trips every HTTP boundary alternative" oauthUnionRoundTrips,+      testCase "client bearer diagnostics redact the credential" (show (C.Token "sensitive-bearer") @?= "Token <redacted>"),       testCase "signup → login → me → refresh; then every admin wrapper reaches its route" $         withShomeiMigratedDatabase \connStr -> do           pool <- acquirePool 4 10 30000 connStr@@ -62,6 +98,45 @@           notifierQueue <- newNotifierQueue 64           let cfg = defaultShomeiConfig (Issuer "shomei") (Audience "shomei-clients")               env = Env {envPool = pool, envDbRetryPolicy = defaultTransactionRetryPolicy, envConfig = cfg, envKeys = keysRef, envKek = testKek, envHttpManager = envMgr, envNotifierSecrets = noNotifierSecrets, envNotifierQueue = notifierQueue, envArgon2Params = testArgon2Params, envHashingLimiter = limiter, envTotpKey = dummyTotpKey}+          clientId <- seedClient pool+          metrics <- newMetrics+          rl <- newRateLimiterFor shomeiThrottledRoutes cfg.rateLimitConfig+          let fullApp = hostMiddleware cfg testServerSettings rl metrics (application env {envConfig = cfg {maxActiveNonInteractiveSessions = 1}} healthyProbe healthyProbe)+          testWithApplication (pure fullApp) \port -> do+            cenv <- C.shomeiClientEnv ("http://127.0.0.1:" <> show port)+            tooLarge <- C.oauthToken cenv "unknown" "secret" [Text.replicate (1024 * 1024 + 1) "x"]+            case tooLarge of+              Right (C.OAuthPayloadTooLarge err) -> do+                err.oauthErrorBody.oauthErrorCode @?= "invalid_request"+                err.oauthAuthenticate @?= Nothing+                err.oauthRetryAfter @?= Nothing+              _ -> assertFailure ("expected typed 413, got " <> show tooLarge)+            issued <- C.oauthToken cenv clientId "typed-client-secret" []+            case issued of+              Right (C.OAuthSuccess value) -> value.tokenBody.tokenType @?= "Bearer"+              _ -> assertFailure ("expected successful issuance, got " <> show issued)+            badScope <- C.oauthToken cenv clientId "typed-client-secret" ["outside:scope"]+            case badScope of+              Right (C.OAuthBadRequest err) -> err.oauthErrorBody.oauthErrorCode @?= "invalid_scope"+              _ -> assertFailure ("expected typed 400, got " <> show badScope)+            exhausted <- C.oauthToken cenv clientId "typed-client-secret" []+            case exhausted of+              Right (C.OAuthUnavailable err) -> err.oauthErrorBody.oauthErrorCode @?= "temporarily_unavailable"+              _ -> assertFailure ("expected typed 503, got " <> show exhausted)+            badClient <- C.oauthToken cenv "unknown" "secret" []+            case badClient of+              Right (C.OAuthAuthenticationFailed err) -> err.oauthAuthenticate @?= Just "Basic realm=\"shomei\""+              _ -> assertFailure ("expected typed 401, got " <> show badClient)+          emptyRl <- newRateLimiterFor shomeiThrottledRoutes cfg.rateLimitConfig {perIpBurst = 0}+          testWithApplication (pure (hostMiddleware cfg testServerSettings emptyRl metrics (application env healthyProbe healthyProbe))) \port -> do+            cenv <- C.shomeiClientEnv ("http://127.0.0.1:" <> show port)+            throttled <- C.oauthToken cenv "unknown" "secret" []+            case throttled of+              Right (C.OAuthTooManyRequests err) -> do+                err.oauthErrorBody.oauthErrorCode @?= "temporarily_unavailable"+                err.oauthRetryAfter @?= Just 60+                err.oauthAuthenticate @?= Nothing+              _ -> assertFailure ("expected typed 429, got " <> show throttled)           testWithApplication (pure (application env healthyProbe healthyProbe)) \port -> do             cenv <- C.shomeiClientEnv ("http://127.0.0.1:" <> show port) @@ -100,6 +175,7 @@             expect403 "adminRevokeSessions" =<< C.adminRevokeSessions cenv tok uid             expect403 "adminRevokeSession" =<< C.adminRevokeSession cenv tok sid             expect403 "adminPasswordReset" =<< C.adminPasswordReset cenv tok uid+            expect403 "adminResetMfa" =<< C.adminResetMfa cenv tok uid (ResetMfaRequest True "INC-client")             expect403 "adminGrantRole" =<< C.adminGrantRole cenv tok uid "admin"             expect403 "adminRevokeRole" =<< C.adminRevokeRole cenv tok uid "admin"     ]@@ -136,3 +212,107 @@ -- here; only that hashing round-trips. testArgon2Params :: Argon2Params testArgon2Params = Argon2Params {memoryKiB = 8192, iterations = 1, parallelism = 1}++testServerSettings :: ServerSettings+testServerSettings =+  ServerSettings+    { serverPort = 0,+      serverBindHost = "127.0.0.1",+      serverMaxConnections = 1024,+      serverSlowClientTimeoutSeconds = 30,+      serverConnStr = "",+      serverTrustedProxies = emptyTrustedProxies,+      serverProxyProtocol = ProxyProtocolOff,+      serverDbPoolSize = 1,+      serverDbPoolAcquisitionTimeoutMs = 1000,+      serverDbStatementTimeoutMs = 1000,+      serverDbTransactionMaxAttempts = 3,+      serverDbTransactionDeadlineMs = 5000,+      serverNotifierQueueSize = 16,+      serverWarnings = [],+      serverSweep = defaultSweepSettings {sweepEnabled = False},+      serverArgon2 = defaultArgon2Params,+      serverHashingMaxConcurrency = 1+    }++oauthUnionRoundTrips :: IO ()+oauthUnionRoundTrips = forM_ [400, 401, 404, 405, 406, 413, 415, 429, 500, 503] \status ->+  forM_ [[], [("WWW-Authenticate", "Bearer"), ("Retry-After", "60"), ("Allow", "POST")]] \optional -> do+    let err = if status `elem` [405, 406, 413, 415, 429] then oauthBoundaryError status else oauthError (mkStatus status "test") "invalid_request" "test"+        result = oauthServerErrorResult err {errHeaders = err.errHeaders <> optional} :: TokenResult+    (fromUnion @TokenResponses (toUnion @TokenResponses result)) @?= result++oauthWireResults :: IO ()+oauthWireResults = forM_ [400, 401, 404, 405, 406, 413, 415, 429, 500, 503] \status ->+  forM_ [[], [("WWW-Authenticate", "Bearer"), ("Retry-After", "60"), ("Allow", "POST")]] \optional -> do+    let base = oauthError (mkStatus status "test") "invalid_request" "safe test error"+        err = base {errHeaders = base.errHeaders <> optional}+        server _ respond = respond (responseLBS (mkStatus status (BS8.pack err.errReasonPhrase)) err.errHeaders err.errBody)+    testWithApplication (pure server) \port -> do+      cenv <- C.shomeiClientEnv ("http://127.0.0.1:" <> show port)+      result <- C.oauthToken cenv "unknown" "secret" []+      result @?= Right (oauthServerErrorResult err)++seedClient :: Pool -> IO Text+seedClient pool = do+  outcome <-+    runEff+      . runErrorNoCallStack @AuthError+      . runDatabasePool pool+      . runClockIO+      . runServiceAccountStorePostgres+      . runUserStorePostgres+      $ do+        said <- genServiceAccountDbId+        let cid = idText said+        ts <- now+        loginId <- either (const (error "bad login id")) pure (mkLoginId cid)+        User {userId = backingUserId} <- createUser NewUser {loginId, email = Nothing, displayName = Just "e2e connector"}+        _ <-+          createServiceAccount+            NewServiceAccount+              { serviceAccountId = said,+                clientId = cid,+                userId = backingUserId,+                secretHash = sha256Hex "typed-client-secret",+                displayName = "e2e connector",+                allowedScopes = Set.singleton (Scope "kawa:ingest"),+                createdAt = ts+              }+        pure cid+  either (assertFailure . ("could not seed the service account: " <>) . show) pure outcome++-- The first GET deliberately primes a reusable connection. The server then records the+-- destructive request and closes without a response, representing an ambiguous commit.+-- With http-client's default replay policy the request arrives a second time.+recoveryNoReplay :: Bool -> IO ()+recoveryNoReplay redirect = do+  observed <- newIORef []+  let app request respond = do+        let prime = Wai.rawPathInfo request == "/prime"+        atomicModifyIORef' observed (\seen -> (seen <> [(prime, Wai.remoteHost request, lookup "X-Configured" (Wai.requestHeaders request))], ()))+        if prime+          then respond (Wai.responseLBS (mkStatus 200 "OK") [] "primed")+          else+            if redirect+              then respond (Wai.responseLBS (mkStatus 307 "Temporary Redirect") [("Location", "/again")] "")+              else respond (Wai.responseRaw (\_ _ -> pure ()) (Wai.responseLBS (mkStatus 500 "") [] ""))+  testWithApplication (pure app) \port -> do+    let baseText = "http://127.0.0.1:" <> show port+        settings = HTTP.defaultManagerSettings {HTTP.managerModifyRequest = \request -> pure request {HTTP.requestHeaders = ("X-Configured", "preserved") : HTTP.requestHeaders request}}+    manager <- HTTP.newManager settings+    base <- ServantClient.parseBaseUrl baseText+    let env = ServantClient.mkClientEnv manager base+    prime <- HTTP.parseRequest (baseText <> "/prime")+    _ <- HTTP.httpLbs prime manager+    target <- genUserId+    result <- C.adminResetMfa env (C.Token "sentinel-token") target (ResetMfaRequest True "INC-transport")+    case result of+      Left _ -> pure ()+      Right _ -> assertFailure "ambiguous reset should surface a transport/redirect failure"+    seen <- readIORef observed+    case seen of+      [(True, primePeer, _), (False, resetPeer, configured)] -> do+        primePeer @?= resetPeer+        configured @?= Just "preserved"+      other -> assertFailure ("destructive request was replayed: " <> show other)