store: limit checkouts per provider and network, bound provider calls (#8092)

* store: limit each BTCPay and Stripe call to 10 seconds

* store: limit checkouts per provider and per client network

* store: skip a timed-out provider for the rest of a poller pass

* store: cancel a BTCPay invoice whose address cannot be read

* store: take a checkout's network and provider tokens together

* store: share the stall switch of the fake providers in tests

* store: drop provider timeout checks that cannot fail

* store: rename a test binding shadowing an import

* store: keep a pass's reads after a timed-out provider list

* store: log a failed checkout at the provider in true terms

* store: document the host-name lookup outside the provider bound

* store: test a created BTCPay invoice whose cancel fails

---------

Co-authored-by: sh-agents <350651734+sh-agents@users.noreply.github.com>
This commit is contained in:
sh-agentsandsh-agents authored and GitHub committed 2026-11-13 08:20:11 +00:00
1 parent 38e5ad3577
commit 6ccabfbfbe
19 files changed
+391 -107

No files matched your search

+5 -2
View File
@@ -181,8 +181,11 @@ proxy appends.
An IPv6 client is counted by its /64, since one host gets a whole /64, and an IPv4-mapped address
by its IPv4 address.
Checkouts that reach the provider (`POST /api/invoice` and `POST /api/registration/:id/spend` with a
difference to pay, each a provider invoice or card PaymentIntent) are also capped at 30 a minute for
all clients together.
difference to pay, each a provider invoice or card PaymentIntent) are also capped at 5 a minute for
each IPv4 /24 or IPv6 /48, and at 60 card and 30 BTCPay checkouts a minute for all clients together.
A call to BTCPay or Stripe, its body read included, fails as a provider error after 10 seconds; the
lookup of the provider's host name is outside that bound. After a timed-out read, cancel or rate
call, the poller asks that provider nothing more in the same pass; a timed-out list stops nothing.
Searches read the chain at most 16 at a time and long polls hold at most 500 at a time, for all clients
together; past that they answer `429 rate_limited` with a short `Retry-After` at once.
Registration views of committed orders read the chain at most 16 at a time as well, each with its
+4 -4
View File
@@ -93,7 +93,7 @@ How a request flows:
| Part | Role | Source |
|---|---|---|
| Startup | `store_service.ini` is parsed, the database lock taken, and the node's chain id and the issuer key checked; then the chat core is started. In its callback the providers, the names environment and the web environment are built, the sites exported, the managed group resolved, and all lanes started together. Without `--service-config` only the chat side and the badge request lanes run. | [`Main.hs:15-28`](../Main.hs#L15-L28), [`Service.hs:280-370`](../src/StoreService/Service.hs#L280-L370) |
| Web API | Warp listeners on `[listener] host`: `badges_port` (8080) always, `names_port` (8081) with `[names]` and `serve_webapp = on`. `/api/*` and both webhooks are answered on every port. Per-client limits a minute: read 60, search 30, preview 20, code 10, records 10, create 5, find 5. At most 500 long polls are held at once, each up to 30 s. | [`Web/Server.hs:121-151`](../src/StoreService/Web/Server.hs#L121-L151), [`Web/Server.hs:562-585`](../src/StoreService/Web/Server.hs#L562-L585), [`Config.hs:505-514`](../src/StoreService/Config.hs#L505-L514), [`Web/Names.hs:28-51`](../src/StoreService/Web/Names.hs#L28-L51), [`Web/Http.hs:109-154`](../src/StoreService/Web/Http.hs#L109-L154) |
| Web API | Warp listeners on `[listener] host`: `badges_port` (8080) always, `names_port` (8081) with `[names]` and `serve_webapp = on`. `/api/*` and both webhooks are answered on every port. Per-client limits a minute: read 60, search 30, preview 20, code 10, records 10, create 5, find 5. Checkouts that reach a provider: 5 a minute per IPv4 /24 or IPv6 /48, and 60 card and 30 BTCPay a minute for all clients together. At most 500 long polls are held at once, each up to 30 s. | [`Web/Server.hs:121-151`](../src/StoreService/Web/Server.hs#L121-L151), [`Web/Server.hs:563-586`](../src/StoreService/Web/Server.hs#L563-L586), [`Config.hs:511-520`](../src/StoreService/Config.hs#L511-L520), [`Web/Names.hs:28-51`](../src/StoreService/Web/Names.hs#L28-L51), [`Web/Http.hs:111-161`](../src/StoreService/Web/Http.hs#L111-L161), [`Web/Http.hs:227-230`](../src/StoreService/Web/Http.hs#L227-L230) |
| Order handlers | An order is placed in one of three ways: a paid invoice, a prepaid code, a spend of another order's balance. The owner's signature, the timestamp, the duration, the terms and an available name are checked, then the chain price for a paid or spent order and the balance for a spend. The order is written in one transaction, in which the same wallet's overdue orders for that name are closed. | [`Web/Names/Orders.hs:86-306`](../src/StoreService/Web/Names/Orders.hs#L86-L306), [`Names/Orders.hs:201-310`](../src/StoreService/Names/Orders.hs#L201-L310), [`Names/Balances.hs:79-106`](../src/StoreService/Names/Balances.hs#L79-L106) |
| Registration and owner handlers | The registration view, held on its version; the reveal; Try again; find by the owner's signature; a move to another name. | [`Web/Names/Registration.hs:45-140`](../src/StoreService/Web/Names/Registration.hs#L45-L140), [`Web/Names/Owner.hs:44-152`](../src/StoreService/Web/Names/Owner.hs#L44-L152), [`Names/Reveal.hs:103-145`](../src/StoreService/Names/Reveal.hs#L103-L145), [`Names/View.hs:52-112`](../src/StoreService/Names/View.hs#L52-L112) |
| Search handlers | Name status, price, terms, and records with link profiles; the terms text; the link preview. These handlers only read, except that a terms text fetched for the first time is stored. | [`Web/Names/Search.hs:53-154`](../src/StoreService/Web/Names/Search.hs#L53-L154), [`Names/Profiles.hs:236-274`](../src/StoreService/Names/Profiles.hs#L236-L274) |
@@ -109,8 +109,8 @@ How a request flows:
| Console | The same binary under `--run-cli`, while the service is stopped: the terminal chat and the badge request lanes only, with `//issue`, `//issue name`, `//revoke`, `//balance`, `//record_refund` and `//close`. `//close` reads the chain through a client of its own, made at start with `[names]`. | [`Main.hs:25-28`](../Main.hs#L25-L28), [`Service.hs:385-576`](../src/StoreService/Service.hs#L385-L576) |
| PostgreSQL | One database (`BADGE_DB_CONN`) with the chat core's schema and the `sx_badge_service_` tables. Names tables: prepaid codes, registrations, balances, name invoices, late credits, record edits and their changes, transactions, terms texts. Partial unique indexes admit one active order (`live = 1`) per commitment and per owner and label hash. | [`Store/Postgres/Migrations.hs:276-479`](../src/StoreService/Store/Postgres/Migrations.hs#L276-L479), [`compose.yml:16`](../../../scripts/store-service/compose.yml#L16) |
| Names page | simplex.domains, in the submodule `apps/simplex-domains`, outside this checkout. `/api/*` is called on its own origin, and the owner's EIP-191 and EIP-712 signatures are sent from it. | [`.gitmodules:4-7`](../../../.gitmodules#L4-L7), [`Web/Names.hs:28-44`](../src/StoreService/Web/Names.hs#L28-L44) |
| BTCPay | Bitcoin and Monero invoices through Greenfield: create, read, list, cancel (status `Invalid`), store rates; webhooks signed with `BTCPay-Sig`. | [`Providers/BTCPay.hs:267-367`](../src/StoreService/Providers/BTCPay.hs#L267-L367), [`Providers/BTCPay.hs:524-538`](../src/StoreService/Providers/BTCPay.hs#L524-L538), [`Providers/BTCPay.hs:555-578`](../src/StoreService/Providers/BTCPay.hs#L555-L578) |
| Stripe | Card PaymentIntents: create with an `Idempotency-Key`, read, list, cancel, also after 3 declined charges; webhooks signed with `Stripe-Signature`, within 15 minutes. | [`Providers/Stripe.hs:101-302`](../src/StoreService/Providers/Stripe.hs#L101-L302) |
| BTCPay | Bitcoin and Monero invoices through Greenfield: create, read, list, cancel (status `Invalid`), store rates; webhooks signed with `BTCPay-Sig`. Each call, its body read included, fails after 10 s; the host-name lookup is outside that bound. An invoice whose address cannot be read after it was created is cancelled. | [`Providers/BTCPay.hs:269-371`](../src/StoreService/Providers/BTCPay.hs#L269-L371), [`Providers/BTCPay.hs:529-543`](../src/StoreService/Providers/BTCPay.hs#L529-L543), [`Providers/BTCPay.hs:560-583`](../src/StoreService/Providers/BTCPay.hs#L560-L583), [`Providers/BTCPay.hs:585-623`](../src/StoreService/Providers/BTCPay.hs#L585-L623) |
| Stripe | Card PaymentIntents: create with an `Idempotency-Key`, read, list, cancel, also after 3 declined charges; webhooks signed with `Stripe-Signature`, within 15 minutes. Each call, its body read included, fails after 10 s; the host-name lookup is outside that bound. | [`Providers/Stripe.hs:103-304`](../src/StoreService/Providers/Stripe.hs#L103-L304), [`Providers/Stripe.hs:378-424`](../src/StoreService/Providers/Stripe.hs#L378-L424) |
| Ethereum node and names contracts | `[chain] rpc_url`: https, or http to a node on loopback. Controller, sponsor, base registrar and resolver are set in `[chain]`; the registry is read from `ens()`, the name policy from `namePolicy()`. The registrar key's USD allowance on the sponsor is raised outside the service with `setRegistrarAllowance`; on an `InsufficientAllowance` revert the order waits and an error is logged. | [`Config.hs:186-198`](../src/StoreService/Config.hs#L186-L198), [`Config.hs:698-703`](../src/StoreService/Config.hs#L698-L703), [`Names/Contracts.hs:150-220`](../src/StoreService/Names/Contracts.hs#L150-L220), [`Names/Worker.hs:341`](../src/StoreService/Names/Worker.hs#L341) |
| SMP servers and proxy | Hold the bot address, the group's queues and the data of buyers' short links. Private routing for unknown servers, with a protected fallback, is preset by `terminalChatConfig`. | [`Chat/Terminal.hs:41-63`](../../../src/Simplex/Chat/Terminal.hs#L41-L63), [`Chat/Library/Internal.hs:1723-1726`](../../../src/Simplex/Chat/Library/Internal.hs#L1723-L1726) |
| git.simplex.chat or raw.githubusercontent.com | Hosts the terms files the name policy links to, at a fixed commit, optionally with the sha256 in the link. A loopback link, always with the sha256, is taken only on chain 31337. | [`Names/Contracts.hs:292-324`](../src/StoreService/Names/Contracts.hs#L292-L324) |
@@ -188,7 +188,7 @@ Notes:
- The checks are run in the contract's order: timestamp within 600 s, duration (paid years plus the free days until `term_start`), current terms, a name available on chain and not in `registering` here, then the chain price, at least `min_price_cents_per_year` times the paid years and equal to the order's ([`Web/Names/Orders.hs:104-118`](../src/StoreService/Web/Names/Orders.hs#L104-L118), [`Names/Orders.hs:266-310`](../src/StoreService/Names/Orders.hs#L266-L310), [`Names/Contracts.hs:190-202`](../src/StoreService/Names/Contracts.hs#L190-L202)). Refusals are listed in [`Web/Names/Orders.hs:344-357`](../src/StoreService/Web/Names/Orders.hs#L344-L357).
- The terms text is read from the database, or fetched from git.simplex.chat or GitHub on the first use of its hash and stored; either is checked against the sha256 in its link when the link has one. While it cannot be read, the order is answered `503 terms_unavailable` ([`Names/Orders.hs:284-291`](../src/StoreService/Names/Orders.hs#L284-L291), [`Names/Contracts.hs:239-290`](../src/StoreService/Names/Contracts.hs#L239-L290), [`Web/Names/Orders.hs:356`](../src/StoreService/Web/Names/Orders.hs#L356)).
- The name lock is held across the provider call, and the answer is sent after it. Overdue unpaid orders of the same wallet and name are closed in the order's transaction ([`Web/Names/Orders.hs:76-100`](../src/StoreService/Web/Names/Orders.hs#L76-L100), [`Names/Orders.hs:207-243`](../src/StoreService/Names/Orders.hs#L207-L243)).
- When the order is not written, its provider invoice is cancelled. Provider checkouts are capped at 30 a minute for all clients together ([`Web/Names/Orders.hs:139-173`](../src/StoreService/Web/Names/Orders.hs#L139-L173), [`Web/Http.hs:151-154`](../src/StoreService/Web/Http.hs#L151-L154)).
- When the order is not written, its provider invoice is cancelled. Provider checkouts are capped at 5 a minute for each IPv4 /24 or IPv6 /48, and at 60 card and 30 BTCPay checkouts a minute for all clients together ([`Web/Names/Orders.hs:139-173`](../src/StoreService/Web/Names/Orders.hs#L139-L173), [`Web/Http.hs:153-161`](../src/StoreService/Web/Http.hs#L153-L161), [`Web/Http.hs:227-230`](../src/StoreService/Web/Http.hs#L227-L230)).
- Stripe is sent `metadata[order]` = `name:0x<order hash>` and an `Idempotency-Key`; BTCPay is sent the amount, the currency and the checkout settings ([`Providers/Stripe.hs:240-269`](../src/StoreService/Providers/Stripe.hs#L240-L269), [`Providers/BTCPay.hs:303-339`](../src/StoreService/Providers/BTCPay.hs#L303-L339)).
- On a webhook only a read is queued, and 200 is answered ([`Web/Server.hs:500-554`](../src/StoreService/Web/Server.hs#L500-L554)).
- An open invoice without money can be cancelled with `POST /api/invoice/ID/cancel`: the provider is told first, then the row is expired and the order closed ([`Web/Server.hs:358-381`](../src/StoreService/Web/Server.hs#L358-L381), [`Orders.hs:244-263`](../src/StoreService/Orders.hs#L244-L263)).
@@ -20,6 +20,7 @@ module StoreService.Config
ServiceConfig (..),
defaultExpiryMinutes,
defaultSessionMinutes,
providerTimeoutMicros,
defaultLogLevel,
minNameYears,
localChainId,
@@ -102,7 +103,8 @@ data BTCPayConfig = BTCPayConfig
bWebhookSecret :: Text,
bExpiryMinutes :: Int,
bSpeedPolicy :: SpeedPolicy,
bPaymentTolerance :: Double
bPaymentTolerance :: Double,
bTimeoutMicros :: Int
}
deriving (Eq)
@@ -115,7 +117,8 @@ data StripeConfig = StripeConfig
sPublishableKey :: Text,
sWebhookSecret :: Text,
sSessionMinutes :: Int,
sHost :: Text
sHost :: Text,
sTimeoutMicros :: Int
}
deriving (Eq)
@@ -234,6 +237,9 @@ defaultStripeHost = "https://api.stripe.com"
defaultSessionMinutes :: Int
defaultSessionMinutes = 60
providerTimeoutMicros :: Int
providerTimeoutMicros = 10 * 1000000
defaultLogLevel :: LogLevel
defaultLogLevel = LogNote
@@ -583,7 +589,7 @@ parseConfig ini = do
bExpiryMinutes <- expiryMinutes
bSpeedPolicy <- speedPolicy
bPaymentTolerance <- tolerance
pure (Just BTCPayConfig {bHost, bApiKey, bStoreId, bWebhookSecret, bExpiryMinutes, bSpeedPolicy, bPaymentTolerance})
pure (Just BTCPayConfig {bHost, bApiKey, bStoreId, bWebhookSecret, bExpiryMinutes, bSpeedPolicy, bPaymentTolerance, bTimeoutMicros = providerTimeoutMicros})
-- A negative window puts BTCPay's startDate in the future, so every poll comes back empty.
expiryMinutes = do
v <- num "btcpay" "expiry_minutes" defaultExpiryMinutes
@@ -633,7 +639,7 @@ parseConfig ini = do
sWebhookSecret <- required "stripe" "webhook_secret"
sSessionMinutes <- sessionMinutes
let sHost = defaultStripeHost
pure (Just StripeConfig {sSecretKey, sPublishableKey, sWebhookSecret, sSessionMinutes, sHost})
pure (Just StripeConfig {sSecretKey, sPublishableKey, sWebhookSecret, sSessionMinutes, sHost, sTimeoutMicros = providerTimeoutMicros})
appleSection
| not (hasSection "apple") = Right Nothing
| otherwise = do
@@ -40,7 +40,7 @@ import StoreService.Names.LateCredits (CreditOutcome (..), LateMoney (..), credi
import StoreService.Names.Phases (Phases, RegistrationId (..))
import StoreService.Names.Store (CleanupKept (..), LateAlert (..), LateCredit (..), LateCreditState (..), LatePending (..), LateSupport (..), claimLateAlert, deleteUnpaidRegistration, lateAlertDue, latePending, uncreditedLateInvoices, unpaidCleanupCandidates)
import StoreService.Orders (decide, expireOverdue, settleOrder, signalReceived)
import StoreService.Providers (ListPass (..), PaymentSignal (..), Provider (..), ProviderError (..), Rate (..), Received (..), expiresItself, settleWindow, unitName)
import StoreService.Providers (ListPass (..), PaymentSignal (..), Provider (..), ProviderError (..), Rate (..), Received (..), expiresItself, isTimeout, settleWindow, unitName)
import StoreService.Safely (safely, safelyWith)
import StoreService.Store.Invoices (InvoicePayment (..), InvoiceProduct (..), InvoiceRow (..), OverdueInvoice (..), cryptoCurrencyText, getInvoice, getInvoiceByProviderRef, overdueInvoices, unpaidRefs)
import StoreService.Waiters (Waiters, waitingCount, waitingCountSTM)
@@ -154,7 +154,12 @@ newPollerEnv peStore peWaiters pePhases peHints peProviders pePoll = do
-- so an invoice with money in it is never expired. After a list that cannot account for every invoice, only overdue
-- invoices read one by one are swept, so a flood of orders past the list's cap cannot stop the sweep.
runOnePass :: PollerEnv -> IO ()
runOnePass env@PollerEnv {peStore, peProviders} = do
runOnePass env@PollerEnv {peProviders} = do
providers <- mapM passProvider peProviders
runPass env {peProviders = providers}
runPass :: PollerEnv -> IO ()
runPass env@PollerEnv {peStore, peProviders} = do
now <- getCurrentTime
forgetRates env
rows <- unpaidRefs peStore (addUTCTime (negate settleWindow) now)
@@ -177,6 +182,20 @@ runOnePass env@PollerEnv {peStore, peProviders} = do
void $ safely "names: the late credit pass" (creditPass env now)
cleanupUnpaid env now
passProvider :: Provider -> IO Provider
passProvider p@Provider {pProvider, pReadInvoice, pCancelInvoice, pListOpen, pCurrentRate} = do
timedOut <- newTVarIO False
let unlessTimedOut :: IO (Either ProviderError a) -> IO (Either ProviderError a)
unlessTimedOut call =
readTVarIO timedOut >>= \case
True -> pure $ Left $ ProviderError $ tshow pProvider <> " is not asked again in this pass, as a call to it timed out"
False -> call
skipping :: IO (Either ProviderError a) -> IO (Either ProviderError a)
skipping call = unlessTimedOut $ do
r <- call
r <$ when (either isTimeout (const False) r) (atomically $ writeTVar timedOut True)
pure p {pReadInvoice = skipping . pReadInvoice, pCancelInvoice = skipping . pCancelInvoice, pListOpen = unlessTimedOut pListOpen, pCurrentRate = (skipping .) <$> pCurrentRate}
-- | The cases the stray list catches are rare and not urgent, so minutes, not the pass cadence.
strayListInterval :: NominalDiffTime
strayListInterval = 60
@@ -4,6 +4,8 @@
module StoreService.Providers
( ProviderError (..),
timeoutError,
isTimeout,
WebhookError (..),
Received (..),
Confirmed (..),
@@ -26,12 +28,22 @@ import Data.ByteString (ByteString)
import Data.Int (Int64)
import Data.Scientific (Scientific)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time.Clock (NominalDiffTime, UTCTime)
import Network.HTTP.Types.Header (Header)
import Simplex.Chat.PaymentService.Types (CryptoCurrency (..), CurrencyAmount, PaymentProvider (..), ServicePaymentDestination, ServicePaymentMethod)
newtype ProviderError = ProviderError Text deriving (Eq, Show)
timeoutError :: Text -> ProviderError
timeoutError what = ProviderError (what <> timeoutReason)
isTimeout :: ProviderError -> Bool
isTimeout (ProviderError e) = timeoutReason `T.isSuffixOf` e
timeoutReason :: Text
timeoutReason = " failed: timed out"
-- | WebhookStale is a valid signature with a timestamp too far from our clock.
data WebhookError = WebhookError Text | WebhookStale Text deriving (Eq, Show)
@@ -31,6 +31,7 @@ import StoreService.Providers
Received (..),
Uncreditable (..),
settleWindow,
timeoutError,
unitDecimals,
WebhookError (..),
)
@@ -78,6 +79,7 @@ import Simplex.Chat.PaymentService.Types
ServicePaymentMethod (..),
)
import Simplex.Messaging.Util (safeDecodeUtf8, tshow)
import System.Timeout (timeout)
-- Shapes cited from BTCPay Server v2.4.5 (https://github.com/btcpayserver/btcpayserver/tree/v2.4.5):
-- - payment methods, GET stores/{storeId}/invoices/{invoiceId}/payment-methods: BTCPayServer.Client/Models/InvoicePaymentMethodDataModel.cs,
@@ -308,13 +310,16 @@ createInvoice env@BTCPayEnv {beCfg} spm OrderDraft {odAmount, odCurrency} =
created <- greenfield env what methodPost ["invoices"] [] (Just (body methodId))
case created >>= decodeGreenfield what of
Left e@(ProviderError m) -> do
logWarn ("btcpay: the refused request was " <> safeDecodeUtf8 (LB.toStrict (J.encode (body methodId))) <> " -- " <> m)
logWarn ("btcpay: the failed request was " <> safeDecodeUtf8 (LB.toStrict (J.encode (body methodId))) <> " -- " <> m)
pure (Left e)
Right GCreated {gcId} -> do
ms <- greenfield env what methodGet ["invoices", gcId, "payment-methods"] [] Nothing
pure (ms >>= destination methodId cc gcId)
either (cancelCreated gcId) (pure . Right) (ms >>= destination methodId cc gcId)
where
what = "create invoice"
cancelCreated ref (ProviderError e) = do
cancelled <- cancelInvoice env ref
pure $ Left $ ProviderError $ e <> "; invoice " <> ref <> either (\(ProviderError c) -> " is left open, as its cancel failed: " <> c) (const " is cancelled") cancelled
body methodId =
J.object
[ "amount" J..= minorToDecimal odAmount,
@@ -579,7 +584,7 @@ verifyBTCPaySig secret hdrs body = do
greenfield :: BTCPayEnv -> Text -> Method -> [Text] -> Query -> Maybe J.Value -> IO (Either ProviderError LB.ByteString)
greenfield BTCPayEnv {beCfg, beManager} what verb segments query body = do
r <- try $ do
r <- timeout (bTimeoutMicros beCfg) $ try $ do
req <- parseRequest (T.unpack url)
let asked =
req
@@ -596,9 +601,10 @@ greenfield BTCPayEnv {beCfg, beManager} what verb segments query body = do
taken <- brReadSome (responseBody resp) (fromIntegral maxProviderBytes + 1)
pure (statusCode (responseStatus resp), taken)
pure $ case r of
Nothing -> Left (timeoutError what)
-- http-client hides the Authorization header when showing a Request
Left (e :: HttpException) -> Left (ProviderError (what <> " failed: " <> tshow e))
Right (code, taken)
Just (Left (e :: HttpException)) -> Left (ProviderError (what <> " failed: " <> tshow e))
Just (Right (code, taken))
| LB.length taken > maxProviderBytes ->
Left . ProviderError $
what <> " failed: HTTP " <> tshow code <> ", and the answer is over " <> tshow maxProviderBytes <> " bytes"
@@ -22,6 +22,7 @@ import StoreService.Providers
ProviderInvoice (..),
Received (..),
settleWindow,
timeoutError,
WebhookError (..),
)
import Control.Exception (try)
@@ -68,6 +69,7 @@ import Simplex.Chat.PaymentService.Types
ServicePaymentMethod (..),
)
import Simplex.Messaging.Util (safeDecodeUtf8, tshow)
import System.Timeout (timeout)
maxErrorBytes :: Int64
maxErrorBytes = 4000
@@ -383,7 +385,7 @@ stripeSend ::
Maybe [(ByteString, ByteString)] ->
IO (Bool, Either ProviderError LB.ByteString)
stripeSend StripeEnv {seCfg, seManager} what verb segments query headers form = do
r <- try $ do
r <- timeout (sTimeoutMicros seCfg) $ try $ do
req0 <- parseRequest (T.unpack url)
-- applyBasicAuth must wrap the record update, because updating requestHeaders after it would drop the header it adds.
let req =
@@ -401,9 +403,10 @@ stripeSend StripeEnv {seCfg, seManager} what verb segments query headers form =
taken <- brReadSome (responseBody resp) (fromIntegral maxProviderBytes + 1)
pure (lookup "Idempotent-Replayed" (responseHeaders resp) == Just "true", statusCode (responseStatus resp), taken)
pure $ case r of
Nothing -> (False, Left (timeoutError what))
-- http-client hides the Authorization header when showing a Request
Left (e :: HttpException) -> (False, Left (ProviderError (what <> " failed: " <> tshow e)))
Right (replayed, code, taken) -> (replayed, answer code taken)
Just (Left (e :: HttpException)) -> (False, Left (ProviderError (what <> " failed: " <> tshow e)))
Just (Right (replayed, code, taken)) -> (replayed, answer code taken)
where
answer code taken
| LB.length taken > maxProviderBytes =
@@ -12,7 +12,8 @@ module StoreService.Web.Http
takeToken,
limited,
only,
clientKey,
CheckoutClient,
checkoutClient,
maxBuckets,
readLimit,
createLimit,
@@ -21,8 +22,9 @@ module StoreService.Web.Http
codeLimit,
findLimit,
recordsLimit,
checkoutLimit,
invoicesLimit,
limitedForAll,
limitedCheckout,
holdMicros,
maxHolds,
withHoldSlot,
@@ -59,7 +61,7 @@ where
import Control.Concurrent.STM
import Control.Exception (bracket)
import Control.Monad (when)
import Control.Monad (foldM, when)
import Data.Aeson ((.=))
import qualified Data.Aeson as J
import Data.Aeson.Types (Pair)
@@ -82,7 +84,7 @@ import Network.Socket (SockAddr (..), hostAddress6ToTuple, hostAddressToTuple)
import Network.Wai
import Numeric (readHex, showHex)
import Simplex.Chat.PaymentService.Types (CardProvider (..), CurrencyAmount (..), InvoiceStatus (..), PaymentProvider (..), ServicePaymentDestination (..), ServicePaymentMethod (..))
import Simplex.Messaging.Util (safeDecodeUtf8)
import Simplex.Messaging.Util (safeDecodeUtf8, tshow)
import StoreService.Config (BTCPayConfig (..), ListenerConfig (..), ServiceConfig (..), SpeedPolicy (..), StripeConfig (..), defaultExpiryMinutes, defaultSessionMinutes)
import StoreService.Providers (Provider (..))
import StoreService.Store.Invoices (InvoicePayment (..), InvoiceRow (..), cryptoCurrencyText, invoiceStatusText, paymentHolds)
@@ -148,10 +150,15 @@ codeLimit = Limit {lmName = "code", lmPerMinute = 10}
findLimit = Limit {lmName = "find", lmPerMinute = 5}
recordsLimit = Limit {lmName = "records", lmPerMinute = 10}
checkoutLimit :: Limit
checkoutLimit = Limit {lmName = "checkout", lmPerMinute = 5}
-- | Checkouts of every client together, each a provider invoice or card PaymentIntent, so a flood from many addresses
-- still meets a ceiling.
invoicesLimit :: Limit
invoicesLimit = Limit {lmName = "invoices", lmPerMinute = 30}
invoicesLimit :: ServicePaymentMethod -> Limit
invoicesLimit = \case
SPMCard CPStripe -> Limit {lmName = "card invoices", lmPerMinute = 60}
SPMCrypto _ -> Limit {lmName = "crypto invoices", lmPerMinute = 30}
maxBodyBytes :: Int
maxBodyBytes = 8192
@@ -196,42 +203,62 @@ takeFrom limit now = \case
_ -> Right Bucket {bkCount = 1, bkStarted = now}
takeToken :: HttpEnv -> Limit -> Text -> IO (Maybe Int)
takeToken HttpEnv {heBuckets} Limit {lmName, lmPerMinute} client = do
takeToken env limit client = takeTokens env [(limit, client)]
takeTokens :: HttpEnv -> [(Limit, Text)] -> IO (Maybe Int)
takeTokens HttpEnv {heBuckets} limits = do
now <- getCurrentTime
atomically $ do
buckets <- reclaim now <$> readTVar heBuckets
let key = lmName <> "\t" <> client
count bucket = writeTVar heBuckets (Map.insert key bucket buckets) >> pure Nothing
let takeOne taken (Limit {lmName, lmPerMinute}, client) =
let key = lmName <> "\t" <> client
in (\bucket -> Map.insert key bucket taken) <$> takeFrom lmPerMinute now (Map.lookup key taken)
count taken = writeTVar heBuckets taken >> pure Nothing
-- write the reclaimed map back here too, or a refused request redoes the filtering every time and the map stays at the limit
refuse seconds = writeTVar heBuckets buckets >> pure (Just seconds)
either (refuse . max 1 . ceiling) count (takeFrom lmPerMinute now (Map.lookup key buckets))
either (refuse . max 1 . ceiling) count (foldM takeOne buckets limits)
limited :: HttpEnv -> Limit -> Request -> Respond -> IO ResponseReceived -> IO ResponseReceived
limited env limit req respond action =
takeToken env limit (clientKey env req) >>= \case
takeToken env limit (clientKey hostPrefix env req) >>= \case
Nothing -> action
Just seconds -> respond (rateLimited seconds)
-- | A limit every client shares, taken just before the provider is asked, so refused requests do not use it.
limitedForAll :: HttpEnv -> Limit -> (Response -> IO a) -> IO a -> IO a
limitedForAll env limit refuse action = takeToken env limit "" >>= maybe action (refuse . rateLimited)
-- | The client network's limit and the one every client shares, taken just before the provider is asked, so refused requests do not use them.
limitedCheckout :: HttpEnv -> CheckoutClient -> ServicePaymentMethod -> (Response -> IO a) -> IO a -> IO a
limitedCheckout env (CheckoutClient client) method refuse action =
takeTokens env [(checkoutLimit, client), (invoicesLimit method, "")] >>= maybe action (refuse . rateLimited)
only :: Method -> Request -> Respond -> IO ResponseReceived -> IO ResponseReceived
only method req respond action
| requestMethod req == method = action
| otherwise = respond (methodNotAllowed method)
data KeyPrefix = KeyPrefix {kpOctets :: Int, kpGroups :: Int}
-- | An IPv6 client is keyed by its /64, as one host holds a whole /64.
hostPrefix :: KeyPrefix
hostPrefix = KeyPrefix {kpOctets = 4, kpGroups = 4}
networkPrefix :: KeyPrefix
networkPrefix = KeyPrefix {kpOctets = 3, kpGroups = 3}
newtype CheckoutClient = CheckoutClient Text
deriving (Eq, Show)
checkoutClient :: HttpEnv -> Request -> CheckoutClient
checkoutClient env = CheckoutClient . clientKey networkPrefix env
-- | Every line is joined first, so a second header line a caller adds cannot leave its own line the one we read.
-- An IPv6 client is keyed by its /64, as one host holds a whole /64.
clientKey :: HttpEnv -> Request -> Text
clientKey HttpEnv {heTrustForwardedFor} req = fromMaybe (peerText (remoteHost req)) forwarded
clientKey :: KeyPrefix -> HttpEnv -> Request -> Text
clientKey prefix HttpEnv {heTrustForwardedFor} req = fromMaybe (peerText prefix (remoteHost req)) forwarded
where
forwarded
| not heTrustForwardedFor = Nothing
| otherwise = case reverse (concatMap entries (requestHeaders req)) of
(ip : _)
| isIPv4 ip -> Just ip
| isIPv6 ip -> v6Key <$> v6Groups ip
| isIPv4 ip -> Just (v4Key prefix (T.splitOn "." ip))
| isIPv6 ip -> v6Key prefix <$> v6Groups ip
_ -> Nothing
entries (name, raw)
| name /= "x-forwarded-for" = []
@@ -278,14 +305,14 @@ groupCount endsAddress gs
plainGroups ps = if all hexGroup ps then Just (length ps) else Nothing
hexGroup g = not (T.null g) && T.length g <= 4 && T.all asciiHexDigit g
peerText :: SockAddr -> Text
peerText = \case
peerText :: KeyPrefix -> SockAddr -> Text
peerText prefix = \case
SockAddrInet _ addr ->
let (a, b, c, d) = hostAddressToTuple addr
in v4Text [a, b, c, d]
in v4Key prefix (map tshow [a, b, c, d])
SockAddrInet6 _ _ addr _ ->
let (a, b, c, d, e, f, g, h) = hostAddress6ToTuple addr
in v6Key [a, b, c, d, e, f, g, h]
in v6Key prefix [a, b, c, d, e, f, g, h]
SockAddrUnix p -> "unix:" <> T.pack p
-- | The eight groups of an address isIPv6 accepts.
@@ -306,14 +333,14 @@ v6Groups t = case T.splitOn "::" t of
| otherwise = (: []) . fst <$> listToMaybe (readHex $ T.unpack g)
exactly n gs = gs >>= \xs -> if length xs == n then Just xs else Nothing
-- | The /64 an address is in, or the IPv4 address an IPv4-mapped one carries.
v6Key :: [Word16] -> Text
v6Key gs = case splitAt 6 gs of
([0, 0, 0, 0, 0, 0xffff], [ab, cd]) -> v4Text [ab `div` 256, ab `mod` 256, cd `div` 256, cd `mod` 256]
_ -> T.intercalate ":" (map (T.pack . (`showHex` "")) (take 4 gs)) <> "::/64"
-- | The prefix of an address, or of the IPv4 address in an IPv4-mapped one.
v6Key :: KeyPrefix -> [Word16] -> Text
v6Key prefix@KeyPrefix {kpGroups} gs = case splitAt 6 gs of
([0, 0, 0, 0, 0, 0xffff], [ab, cd]) -> v4Key prefix (map tshow [ab `div` 256, ab `mod` 256, cd `div` 256, cd `mod` 256])
_ -> T.intercalate ":" (map (T.pack . (`showHex` "")) (take kpGroups gs)) <> "::"
v4Text :: Show a => [a] -> Text
v4Text = T.intercalate "." . map (T.pack . show)
v4Key :: KeyPrefix -> [Text] -> Text
v4Key KeyPrefix {kpOctets} = T.intercalate "." . take kpOctets
apiHeaders :: [Header]
apiHeaders = [(hContentType, "application/json"), (hCacheControl, "no-store")]
@@ -53,7 +53,7 @@ import StoreService.Orders (publishRegistration)
import StoreService.Providers (OrderDraft (..), Provider (..), ProviderError (..), ProviderInvoice (..), expiresItself)
import StoreService.Store.Invoices (InvoiceRow (..), NewNameInvoice (..), getInvoice, insertNameInvoice, newInvoiceId, truncateToSecond)
import StoreService.Waiters (Waiters, publish)
import StoreService.Web.Http (HttpEnv, Respond, badRequest, confirmationsFor, internalError, invalidName, invoiceAt, invoicesLimit, invoicePairs, invoiceWindow, jsonError, jsonResponse, limitedForAll, nameBodyBytes, notFound, providerFor, providerNamed, providerUnavailable, readBoundedBody, termsUnavailable)
import StoreService.Web.Http (CheckoutClient, HttpEnv, Respond, badRequest, checkoutClient, confirmationsFor, internalError, invalidName, invoiceAt, invoicePairs, invoiceWindow, jsonError, jsonResponse, limitedCheckout, nameBodyBytes, notFound, providerFor, providerNamed, providerUnavailable, readBoundedBody, termsUnavailable)
import StoreService.Web.Names.Codes (codeRefusalResponse)
data InvoiceOrder = InvoiceOrder
@@ -83,8 +83,8 @@ sendAnswer :: Respond -> Answer -> IO ResponseReceived
sendAnswer respond Answer {aResponse, aAfter} = aAfter >> respond aResponse
-- | POST /api/invoice for a name, its body already read and its kind checked.
nameInvoiceHandler :: OrdersEnv -> HttpEnv -> ServiceConfig -> [Provider] -> Waiters -> J.Object -> Respond -> IO ResponseReceived
nameInvoiceHandler env@OrdersEnv {oeStore, oeTurns, oeNow} http cfg providers waiters body respond
nameInvoiceHandler :: OrdersEnv -> HttpEnv -> CheckoutClient -> ServiceConfig -> [Provider] -> Waiters -> J.Object -> Respond -> IO ResponseReceived
nameInvoiceHandler env@OrdersEnv {oeStore, oeTurns, oeNow} http client cfg providers waiters body respond
| nCodesOnly (oeConfig env) = sendAnswer respond =<< refuse ORCodesOnly
| otherwise = sendAnswer respond =<< case parseInvoiceOrder body of
Left refusal -> refuse refusal
@@ -115,7 +115,7 @@ nameInvoiceHandler env@OrdersEnv {oeStore, oeTurns, oeNow} http cfg providers wa
insert new paid db at = first (const OROrderExists) <$> createPaidRegistration db new (OTInvoice ioMethod price) paid at
firstRefusal checks >>= \case
Just refusal -> refuse refusal
Nothing -> createAtProvider env http cfg providers waiters what InvoicedOrder {ivRequest = req, ivOrderHash = orderHash orOwner fields (OTInvoice ioMethod price), ivHolders = [], ivMethod = ioMethod, ivPrice = price, ivAmount = ioPrice, ivInsert = insert}
Nothing -> createAtProvider env http client cfg providers waiters what InvoicedOrder {ivRequest = req, ivOrderHash = orderHash orOwner fields (OTInvoice ioMethod price), ivHolders = [], ivMethod = ioMethod, ivPrice = price, ivAmount = ioPrice, ivInsert = insert}
-- | An order paid by invoice: its order hash, the holders its transaction closes, the order's price, what its invoice asks
-- (less than the price when a balance paid the rest), and its insert after the invoice row's.
@@ -130,19 +130,19 @@ data InvoicedOrder = InvoicedOrder
}
-- | The invoice is made at the provider first, then the order is written with its invoice row; an order not written has its invoice cancelled there.
createAtProvider :: OrdersEnv -> HttpEnv -> ServiceConfig -> [Provider] -> Waiters -> Text -> InvoicedOrder -> IO Answer
createAtProvider env@OrdersEnv {oeStore, oeConfig, oeNow} http cfg providers waiters what InvoicedOrder {ivRequest = req@OrderRequest {orOwner, orFields}, ivOrderHash, ivHolders, ivMethod, ivPrice, ivAmount, ivInsert} =
createAtProvider :: OrdersEnv -> HttpEnv -> CheckoutClient -> ServiceConfig -> [Provider] -> Waiters -> Text -> InvoicedOrder -> IO Answer
createAtProvider env@OrdersEnv {oeStore, oeConfig, oeNow} http client cfg providers waiters what InvoicedOrder {ivRequest = req@OrderRequest {orOwner, orFields}, ivOrderHash, ivHolders, ivMethod, ivPrice, ivAmount, ivInsert} =
case providerFor providers ivMethod of
Nothing -> do
logNote (what <> " refused: no provider configured for " <> tshow ivMethod)
pure $ answerNow providerUnavailable
Just provider -> limitedForAll http invoicesLimit (pure . answerNow) $ do
Just provider -> limitedCheckout http client ivMethod (pure . answerNow) $ do
invId <- newInvoiceId
now <- truncateToSecond <$> oeNow
let amount = CurrencyAmount ivAmount
pCreateInvoice provider ivMethod OrderDraft {odAmount = amount, odCurrency = catalogCurrency, odReference = "name:" <> hex ivOrderHash} >>= \case
Left (ProviderError e) -> do
logError (what <> " failed: provider refused to create an invoice: " <> e)
logError (what <> " failed at the provider: " <> e)
pure $ answerNow providerUnavailable
Right ProviderInvoice {piProviderRef, piDestination} -> do
rid <- newRegistrationId
@@ -280,7 +280,7 @@ spendHandler env@OrdersEnv {oeStore, oeConfig, oeContracts, oeTurns, oeNow} http
Just (SPMCard _)
| spPrice - spBalance < minCardChargeCents -> refuse ORBadRequest
Just method ->
createAtProvider env http cfg providers waiters what $
createAtProvider env http (checkoutClient http req) cfg providers waiters what $
InvoicedOrder {ivRequest = order, ivOrderHash = orderHash orOwner orFields (spendTerms spend), ivHolders = maybeToList holder, ivMethod = method, ivPrice = spPrice, ivAmount = fromIntegral (spPrice - spBalance), ivInsert = differenceOrderInsert spend}
-- | Stripe refuses a USD charge under 50 cents, so the page offers only crypto for a smaller difference.
@@ -413,10 +413,11 @@ createInvoiceHandler env@WebEnv {weStore, weConfig, weProviders, weWaiters} req
Nothing
| LB.length body > fromIntegral maxBodyBytes -> refuse "body over the size limit" badRequest
| otherwise -> maybe (refuse "malformed body" badRequest) badgeInvoice (parseCreateRequest o)
Just (J.String "name") | Just orders <- weOrders env -> nameInvoiceHandler orders (weHttp env) weConfig weProviders weWaiters o respond
Just (J.String "name") | Just orders <- weOrders env -> nameInvoiceHandler orders (weHttp env) client weConfig weProviders weWaiters o respond
Just kind -> refuse ("no order of kind " <> tshow kind) badRequest
_ -> refuse "malformed body" badRequest
where
client = checkoutClient (weHttp env) req
refuse :: Text -> Response -> IO ResponseReceived
refuse why response = logNote ("POST /api/invoice refused: " <> why) >> respond response
badgeInvoice cr@CreateRequest {crPriceId, crOfferId, crMethod, crCodeHash} = do
@@ -428,19 +429,19 @@ createInvoiceHandler env@WebEnv {weStore, weConfig, weProviders, weWaiters} req
True -> refuse "code hash already sold" codeConflict
False -> case providerFor weProviders crMethod of
Nothing -> refuse ("no provider configured for " <> tshow crMethod) providerUnavailable
Just provider -> createAtProvider env provider cr priced respond
Just provider -> createAtProvider env client provider cr priced respond
-- | Once the provider call succeeds an invoice exists at BTCPay, and any path below that does not write our rows leaves it stranded.
createAtProvider :: WebEnv -> Provider -> CreateRequest -> PricedOffer -> Respond -> IO ResponseReceived
createAtProvider WebEnv {weStore, weConfig, weHttp} provider CreateRequest {crPriceId, crOfferId, crMethod, crCodeHash} priced respond =
limitedForAll weHttp invoicesLimit respond $ do
createAtProvider :: WebEnv -> CheckoutClient -> Provider -> CreateRequest -> PricedOffer -> Respond -> IO ResponseReceived
createAtProvider WebEnv {weStore, weConfig, weHttp} client provider CreateRequest {crPriceId, crOfferId, crMethod, crCodeHash} priced respond =
limitedCheckout weHttp client crMethod respond $ do
invId@(InvoiceId orderId) <- newInvoiceId
-- truncate once, so the response, the row and the provider get the same value
now <- truncateToSecond <$> getCurrentTime
let expiresAt = addUTCTime (invoiceWindow weConfig crMethod) now
draft = OrderDraft {odAmount = poAmount priced, odCurrency = poCurrency priced, odReference = orderId}
pCreateInvoice provider crMethod draft >>= \case
Left (ProviderError e) -> failed ("provider refused to create an invoice: " <> e) providerUnavailable
Left (ProviderError e) -> failed ("at the provider: " <> e) providerUnavailable
Right ProviderInvoice {piProviderRef, piDestination} -> do
let atProvider = "providerRef " <> piProviderRef
ni =
+1
View File
@@ -795,6 +795,7 @@ test-suite simplex-chat-test
Bots.StoreService.FakeAppStore
Bots.StoreService.FakeBTCPay
Bots.StoreService.FakeEthNode
Bots.StoreService.FakeHttp
Bots.StoreService.FakePlay
Bots.StoreService.FakeStore
Bots.StoreService.FakeStripe
+29 -5
View File
@@ -39,7 +39,7 @@ import Data.Scientific (Scientific, scientific)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Data.Time.Clock (UTCTime, getCurrentTime)
import Data.Time.Clock (UTCTime, diffUTCTime, getCurrentTime)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime, utcTimeToPOSIXSeconds)
import Network.HTTP.Types.Header (Header, hAuthorization)
import Simplex.Chat.PaymentService.Types
@@ -116,11 +116,13 @@ badgeBTCPayTests = describe "badge btcpay adapter" $ do
it "names a status the provider invented" testFakeUnknownStatus
it "reads paymentMethodPaid over the wire, never totalPaid" testFakePaymentMethodPaid
it "makes a 500 at checkout a ProviderError" testFakeCreate500
it "abandons an invoice it created but could not learn the address of" testFakeCreatePostFailure
it "cancels an invoice it created but could not learn the address of, naming it" testFakeCreatePostFailure
it "names an invoice it created, could not learn the address of and could not cancel" testFakeCreatePostFailureUncancelled
it "names the payment method a created invoice does not offer" testFakeCreateWrongMethod
it "names a payment method with no destination, and writes nothing" testFakeCreateNoDestination
it "names a payment method with no amount, and writes nothing" testFakeCreateNoAmount
it "refuses an answer past the size it will hold, and reads again after" testFakeOversizeAnswer
it "ends a call whose answer stalls in its body after the configured timeout, and reads again after" testFakeStalledAnswer
it "makes a 500 on a read a ProviderError the next read recovers from" testFakeRead500
it "verifies a webhook with the secret it was configured with" testFakeWebhookSecretWiring
it "keeps totalPaid distinguishable in every fixture an amount is asserted from" testFixturesGuardTotalPaid
@@ -818,9 +820,17 @@ testFakeCreatePostFailure = withProvider $ \fake p -> do
failAfterCalls 1 fake 1 500
r <- pCreateInvoice p (SPMCrypto CCBtc) fiftyFourDollars
r `shouldSatisfy` namesInError "500"
ids <- fakeInvoiceIds fake
length ids `shouldBe` 1
r `shouldSatisfy` \case Right _ -> False; Left _ -> True
[created] <- fakeInvoiceIds fake
r `shouldSatisfy` namesInError ("; invoice " <> created <> " is cancelled")
map frBody <$> apiRequests fake "POST" ["invoices", created, "status"] `shouldReturn` [J.encode (J.object ["status" .= ("Invalid" :: Text)])]
testFakeCreatePostFailureUncancelled :: IO ()
testFakeCreatePostFailureUncancelled = withProvider $ \fake p -> do
failAfterCalls 1 fake 2 500
r <- pCreateInvoice p (SPMCrypto CCBtc) fiftyFourDollars
[created] <- fakeInvoiceIds fake
r `shouldSatisfy` namesInError ("; invoice " <> created <> " is left open, as its cancel failed: cancel invoice failed: HTTP 500")
length <$> apiRequests fake "POST" ["invoices", created, "status"] `shouldReturn` 1
testFakeCreateWrongMethod :: IO ()
testFakeCreateWrongMethod = withProvider $ \fake p -> do
@@ -851,6 +861,20 @@ testFakeOversizeAnswer = withProvider $ \fake p -> do
Right _ -> pure ()
Left e -> expectationFailure ("the next read must recover, and got " <> show e)
testFakeStalledAnswer :: IO ()
testFakeStalledAnswer = withProviderConfigured (\cfg -> cfg {bTimeoutMicros = 300000}) $ \fake p -> do
ProviderInvoice {piProviderRef = invRef} <- createdInvoice p (SPMCrypto CCBtc)
answerStalled fake True
start <- getCurrentTime
pReadInvoice p invRef >>= (`shouldSatisfy` namesInError "read invoice failed: timed out")
pCreateInvoice p (SPMCrypto CCBtc) fiftyFourDollars >>= (`shouldSatisfy` namesInError "create invoice failed: timed out")
elapsed <- (`diffUTCTime` start) <$> getCurrentTime
elapsed `shouldSatisfy` (< 2)
answerStalled fake False
pReadInvoice p invRef >>= \case
Right _ -> pure ()
Left e -> expectationFailure ("the next read must recover, and got " <> show e)
testFakeRead500 :: IO ()
testFakeRead500 = withProvider $ \fake p -> do
ProviderInvoice {piProviderRef = invRef} <- createdInvoice p (SPMCrypto CCBtc)
+22 -12
View File
@@ -17,6 +17,7 @@ module Bots.StoreService.FakeBTCPay
usePaymentMethodsFixture,
ignoreListPaging,
answerOversize,
answerStalled,
fakeRequests,
apiRequests,
fakeInvoiceIds,
@@ -27,7 +28,8 @@ module Bots.StoreService.FakeBTCPay
)
where
import StoreService.Config (BTCPayConfig (..), SpeedPolicy (..))
import StoreService.Config (BTCPayConfig (..), SpeedPolicy (..), providerTimeoutMicros)
import Bots.StoreService.FakeHttp (setSwitch, stalledAnswer)
import Control.Applicative ((<|>))
import Control.Concurrent.STM
import Control.Monad (join)
@@ -125,6 +127,7 @@ data FakeState = FakeState
fsMethods :: Maybe Text,
fsIgnorePaging :: Bool,
fsOversize :: Bool,
fsStalled :: Bool,
-- | The rates answer set by a test, else each pair asked at the fixtures' rate.
fsRates :: Maybe J.Value,
fsRequests :: [FakeRequest]
@@ -140,6 +143,7 @@ initialState =
fsMethods = Nothing,
fsIgnorePaging = False,
fsOversize = False,
fsStalled = False,
fsRates = Nothing,
fsRequests = []
}
@@ -170,7 +174,8 @@ fakeConfig host =
bWebhookSecret = fakeWebhookSecret,
bExpiryMinutes = fakeExpiryMinutes,
bSpeedPolicy = MediumSpeed,
bPaymentTolerance = 0.5
bPaymentTolerance = 0.5,
bTimeoutMicros = providerTimeoutMicros
}
-- | A BTCPay webhook delivery shaped as its documentation shows. Both suites sign this exact
@@ -286,7 +291,8 @@ fakeApp stv req respond = do
["_fail"] | isPost -> control body setFail
["_fixtures"] | isPost -> control body setFixtures
["_paging"] | isPost -> control body setPaging
["_oversize"] | isPost -> control body setOversize
["_oversize"] | isPost -> control body (setSwitch stv "_oversize" (\on st -> st {fsOversize = on}))
["_stalled"] | isPost -> control body (setSwitch stv "_stalled" (\on st -> st {fsStalled = on}))
["_rates"] | isPost -> setRatesAnswer body
"api" : "v1" : "stores" : storeId : rest -> apiCall body storeId rest
_ -> refuse notFound404 "no such path on the fake btcpay"
@@ -355,14 +361,6 @@ fakeApp stv req respond = do
Just v -> atomically (modifyTVar' stv (\st -> st {fsRates = Just v})) >> ok
Nothing -> refuse badRequest400 "_rates takes the answer to serve, as JSON"
setOversize o = case unknownKeys ["on"] o of
Just message -> pure (Just message)
Nothing -> case KM.lookup "on" o of
Just (J.Bool on) -> do
atomically (modifyTVar' stv (\st -> st {fsOversize = on}))
pure Nothing
_ -> pure (Just "_oversize takes {\"on\": <bool>}")
setPaging o = case unknownKeys ["ignore"] o of
Just message -> pure (Just message)
Nothing -> case KM.lookup "ignore" o of
@@ -378,11 +376,15 @@ fakeApp stv req respond = do
if storeId /= fakeStoreId
then refuse notFound404 ("no store " <> storeId <> " on the fake btcpay")
else case lookup hAuthorization (requestHeaders req) of
Just given | given == expectedAuth -> injectingFailure (greenfield body rest)
Just given | given == expectedAuth -> unlessStalled (injectingFailure (greenfield body rest))
_ -> refuse unauthorized401 "Authorization must be `token <api-key>`"
expectedAuth = "token " <> TE.encodeUtf8 fakeApiKey
unlessStalled act = do
stalled <- fsStalled <$> readTVarIO stv
if stalled then respond stalledAnswer else act
injectingFailure act = do
failing <- atomically $ do
st <- readTVar stv
@@ -409,6 +411,11 @@ fakeApp stv req respond = do
withInvoice invId $ \inv -> do
override <- fsMethods <$> readTVarIO stv
serve (fromMaybe (methodsFixture (isMethodId inv)) override) (patchMethods inv)
["invoices", invId, "status"] | isPost ->
withInvoice invId $ \inv -> do
let marked = inv {isStatus = fromMaybe (isStatus inv) (J.decode body >>= objectField "status" >>= asText)}
atomically $ modifyTVar' stv $ \st -> st {fsInvoices = M.insert invId marked (fsInvoices st)}
serve (invoiceFixture (isStatus marked)) (patchInvoice invId marked)
_ -> refuse notFound404 "no such greenfield path on the fake btcpay"
rates = do
@@ -552,6 +559,9 @@ failAfterCalls skip fake calls code =
answerOversize :: FakeBTCPay -> Bool -> IO ()
answerOversize fake on = controlPost fake "/_oversize" (J.object ["on" J..= on])
answerStalled :: FakeBTCPay -> Bool -> IO ()
answerStalled fake on = controlPost fake "/_stalled" (J.object ["on" J..= on])
-- | The rates call answers this from now on.
setRates :: FakeBTCPay -> J.Value -> IO ()
setRates fake = controlPost fake "/_rates"
+30
View File
@@ -0,0 +1,30 @@
{-# LANGUAGE OverloadedStrings #-}
module Bots.StoreService.FakeHttp
( setSwitch,
stalledAnswer,
)
where
import Control.Concurrent (threadDelay)
import Control.Concurrent.STM (TVar, atomically, modifyTVar')
import Control.Monad (forever)
import qualified Data.Aeson as J
import qualified Data.Aeson.KeyMap as KM
import Data.ByteString.Builder (byteString)
import Data.Text (Text)
import Network.HTTP.Types (hContentType, ok200)
import Network.Wai (Response, responseStream)
setSwitch :: TVar s -> Text -> (Bool -> s -> s) -> J.Object -> IO (Maybe Text)
setSwitch state path set o = case KM.toList o of
[("on", J.Bool on)] -> Nothing <$ atomically (modifyTVar' state (set on))
_ -> pure (Just (path <> " takes {\"on\": <bool>}"))
stalledAnswer :: Response
stalledAnswer = responseStream ok200 [(hContentType, "application/json")] $ \write flush -> do
write (byteString "[") >> flush
forever $ threadDelay trickleMicros >> write (byteString " ") >> flush
trickleMicros :: Int
trickleMicros = 100000
+16 -3
View File
@@ -10,6 +10,7 @@ module Bots.StoreService.FakeStripe
fakeSessionMinutes,
setIntentState,
failNextCalls,
answerStalled,
useListPageSize,
useListFixture,
apiRequests,
@@ -21,7 +22,8 @@ module Bots.StoreService.FakeStripe
)
where
import StoreService.Config (StripeConfig (..))
import StoreService.Config (StripeConfig (..), providerTimeoutMicros)
import Bots.StoreService.FakeHttp (setSwitch, stalledAnswer)
import Control.Concurrent.STM
import Control.Monad (forM_, when)
import Crypto.Hash (Digest, SHA256)
@@ -107,6 +109,7 @@ data FakeState = FakeState
fsFail :: FailPlan,
fsList :: Text,
fsPageSize :: Maybe Int,
fsStalled :: Bool,
fsRequests :: [FakeRequest],
-- | The first answer to each Idempotency-Key, which Stripe replays to every later call with it.
fsReplies :: M.Map ByteString Response
@@ -120,6 +123,7 @@ initialState =
fsFail = FailPlan {fpCalls = 0, fpStatus = 0},
fsList = "intent-list",
fsPageSize = Nothing,
fsStalled = False,
fsRequests = [],
fsReplies = M.empty
}
@@ -148,7 +152,8 @@ fakeConfig host =
sPublishableKey = "pk_test_x",
sWebhookSecret = fakeWebhookSecret,
sSessionMinutes = fakeSessionMinutes,
sHost = host
sHost = host,
sTimeoutMicros = providerTimeoutMicros
}
-- | Stripe-Signature: t=<unix>,v1=<hex HMAC-SHA256 of "t.body">.
@@ -211,6 +216,7 @@ fakeApp stv req respond0 = do
["_fail"] | isPost -> control body setFail
["_paging"] | isPost -> control body setPaging
["_fixtures"] | isPost -> control body setFixtures
["_stalled"] | isPost -> control body (setSwitch stv "_stalled" (\on st -> st {fsStalled = on}))
"v1" : "payment_intents" : rest -> apiCall body rest
["v1", "charges"] | isGet -> listCharges
_ -> refuse notFound404 "no such path on the fake stripe"
@@ -278,9 +284,13 @@ fakeApp stv req respond0 = do
modifyTVar' stv $ \st ->
st {fsRequests = FakeRequest verb (pathInfo req) (queryString req) (requestHeaders req) b : fsRequests st}
case lookup hAuthorization (requestHeaders req) of
Just given | given == expectedAuth -> replaying (injectingFailure (route b rest))
Just given | given == expectedAuth -> unlessStalled (replaying (injectingFailure (route b rest)))
_ -> refuse unauthorized401 "Authorization must be HTTP Basic with the secret key as username"
unlessStalled act = do
stalled <- fsStalled <$> readTVarIO stv
if stalled then respond0 stalledAnswer else act
-- Stripe authenticates the secret key as the Basic username with an empty password, which is
-- how http-client's applyBasicAuth builds the header.
expectedAuth = "Basic " <> convertToBase Base64 (TE.encodeUtf8 (fakeSecretKey <> ":"))
@@ -432,6 +442,9 @@ setIntentState fake pid fields = controlPost fake ("/_state/" <> T.unpack pid) (
failNextCalls :: FakeStripe -> Int -> Int -> IO ()
failNextCalls fake calls code = controlPost fake "/_fail" (J.object ["calls" J..= calls, "status" J..= code])
answerStalled :: FakeStripe -> Bool -> IO ()
answerStalled fake on = controlPost fake "/_stalled" (J.object ["on" J..= on])
useListPageSize :: FakeStripe -> Int -> IO ()
useListPageSize fake size = controlPost fake "/_paging" (J.object ["size" J..= size])
+11 -7
View File
@@ -144,7 +144,7 @@ namesOrdersTests = describe "StoreService names: orders" $ do
it "cancels the provider invoice and logs it when the order's insert fails" testInsertFailureCancels
it "checks the duration within the slack, before and after the term start" testDurationSlack
it "answers catalog_changed with the chain price" testCatalogChanged
it "counts toward the checkouts of every client only an order that reaches the provider" testOrdersLimitForAll
it "counts toward the checkouts of every client only an order that reaches the provider, and a card order past the spent BTCPay ones" testOrdersLimitForAll
it "answers name_taken for a registered, reserved or being registered name" testNameTaken
it "answers name_check_unavailable when a status or price read fails, or the price is under the floor, reaching no provider" testNameCheckUnavailable
it "refuses a body over 16384 bytes, accepting the longest order" testSizes
@@ -428,11 +428,11 @@ dynamisExpiresCall, dynamisReservedCall :: ByteString
dynamisExpiresCall = unhex "d6e4fa8678b602f03f164366531da963764c1f2fdfd588d0487daf2aa261ca799e5ffe33"
dynamisReservedCall = unhex "389c074878b602f03f164366531da963764c1f2fdfd588d0487daf2aa261ca799e5ffe33"
-- | Each request from its own client address, so the create limit counts none twice.
-- | Each request from its own client network, so the create and checkout limits count none twice.
post :: Ctx -> String -> LB.ByteString -> IO (Int, Maybe J.Object)
post Ctx {cClient, cIps} path body = do
n <- atomicModifyIORef' cIps (\i -> (i + 1, i))
let ip = "198.51." <> show (n `div` 250) <> "." <> show (n `mod` 250 + 1)
let ip = "198." <> show (n `div` 250) <> "." <> show (n `mod` 250 + 1) <> ".1"
r <- webRequestBody cClient "POST" path [(hContentType, "application/json"), ("X-Forwarded-For", BC.pack ip)] body
pure (statusOf r, J.decode (responseBody r))
@@ -677,11 +677,15 @@ testCatalogChanged = withOrders $ \ctx -> do
testOrdersLimitForAll :: IO ()
testOrdersLimitForAll = withOrders $ \ctx -> do
replicateM_ (lmPerMinute invoicesLimit) $ fst <$> placeOrder ctx aliceOrder {oPrice = 9000} `shouldReturn` 409
replicateM_ (lmPerMinute btcpayLimit) $ fst <$> placeOrder ctx aliceOrder {oPrice = 9000} `shouldReturn` 409
void $ placed ctx aliceOrder
replicateM_ (lmPerMinute invoicesLimit - 1) $ takeToken (weHttp $ cWeb ctx) invoicesLimit ""
placeOrder ctx aliceOrder {oLabel = "dynamis", oPrice = 20000, oCommitment = commitmentOf 2} `shouldReturn` refusedWith 429 "rate_limited"
length <$> stubCalls (cStub ctx) `shouldReturn` 1
replicateM_ (lmPerMinute btcpayLimit - 1) $ takeToken (weHttp $ cWeb ctx) btcpayLimit ""
let dynamis = aliceOrder {oLabel = "dynamis", oPrice = 20000, oCommitment = commitmentOf 2}
placeOrder ctx dynamis `shouldReturn` refusedWith 429 "rate_limited"
void $ placed ctx dynamis {oMethod = "card"}
length <$> stubCalls (cStub ctx) `shouldReturn` 2
where
btcpayLimit = invoicesLimit (SPMCrypto CCBtc)
testNameTaken :: IO ()
testNameTaken = withOrders $ \ctx@Ctx {cNode = node} -> do
+18 -2
View File
@@ -18,7 +18,7 @@ import ChatTests.DBUtils (TestParams)
import Control.Concurrent.Async (Async, async, concurrently, wait)
import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)
import Control.Concurrent.STM (atomically, check)
import Control.Monad (forM_, join, void, when)
import Control.Monad (forM_, join, replicateM_, void, when)
import qualified Data.Aeson as J
import qualified Data.Aeson.KeyMap as KM
import qualified Data.Aeson.Types as JT
@@ -33,7 +33,10 @@ import Data.Text.Encoding (encodeUtf8)
import Data.Time.Clock (UTCTime, addUTCTime, getCurrentTime)
import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
import Data.Word (Word64)
import Network.HTTP.Client (responseBody)
import Network.HTTP.Types (hContentType)
import Network.Wai (Application)
import qualified Network.Wai as Wai
import Simplex.Chat.Controller (ChatController (..))
import Simplex.Chat.PaymentService.Types (CryptoCurrency (..), CurrencyAmount (..), InvoiceId (..), InvoiceStatus (..), PaymentProvider (..), ServicePaymentMethod (..))
import Simplex.Messaging.Agent.Store.Common (DBStore, withTransaction)
@@ -56,7 +59,7 @@ import StoreService.Providers.BTCPay (btcpayProvider)
import StoreService.Names.Turns (balanceTurnCount, labelTurnCount, withBalanceTurn)
import StoreService.Store.Invoices (InvoiceRow (..), getInvoice)
import qualified StoreService.Web.Http as Http (findLimit)
import StoreService.Web.Http (createLimit, holdMicros, readLimit)
import StoreService.Web.Http (Limit (..), checkoutClient, checkoutLimit, createLimit, holdMicros, limitedCheckout, readLimit)
import StoreService.Web.Names (Route (..), namesApp)
import StoreService.Web.Names.Orders (spendHandler)
import StoreService.Web.Names.Owner (findHandler)
@@ -70,6 +73,7 @@ namesSpendTests = describe "StoreService names: spend" $ do
describe "orders" $ do
it "queues an order whose price the balance covers, spending the price and keeping the rest, or all of it" testCoveredSpend
it "makes an invoice for the difference, the order holding all of the balance until the invoice's expiry" testDifferenceSpend
it "refuses a difference from a client network whose checkouts are used up, reaching no provider" testDifferenceLimitedPerNetwork
it "answers an exact resend with its order in any phase, by its own hash, with a new timestamp and after the balance changed" testSpendResend
it "keeps a spend and an /api/invoice order of the same fields apart, each meeting the other as order_exists" testInvoiceBodyApart
describe "refusals" $ do
@@ -298,6 +302,18 @@ testDifferenceSpend = withSpend $ \ctx -> do
fmap irAmount <$> getInvoice (cStore ctx) invId `shouldReturn` Just (CurrencyAmount 4000)
field "balance" <$> viewOf ctx src `shouldReturn` Just (J.object ["amount" J..= (6000 :: Int), "held" J..= True, "heldUntil" J..= expiry, "refunded" J..= (0 :: Int)])
testDifferenceLimitedPerNetwork :: IO ()
testDifferenceLimitedPerNetwork = withSpend $ \ctx@Ctx {cClient, cWeb, cStub} -> do
src <- sourceOf ctx "src" 6000
let http = weHttp cWeb
fromNetwork forwardedFor = checkoutClient http Wai.defaultRequest {Wai.requestHeaders = [("X-Forwarded-For", forwardedFor)]}
replicateM_ (lmPerMinute checkoutLimit) $ limitedCheckout http (fromNetwork "203.0.113.7") (SPMCrypto CCBtc) (const $ pure ()) (pure ())
signed <- spendBody ctx src (difference 6000)
r <- webRequestBody cClient "POST" "/api/registration/src/spend" [(hContentType, "application/json"), ("X-Forwarded-For", "203.0.113.9")] (J.encode signed)
(statusOf r, J.decode (responseBody r)) `shouldBe` refusedWith 429 "rate_limited"
stubCalls cStub `shouldReturn` []
fst <$> spend ctx src (difference 6000) `shouldReturn` 200
testSpendResend :: IO ()
testSpendResend = withSpend $ \ctx@Ctx {cStore, cClock} -> do
src <- sourceOf ctx "src" 6000
+18 -2
View File
@@ -30,7 +30,7 @@ import Data.Word (Word32)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Data.Time.Clock (UTCTime, getCurrentTime)
import Data.Time.Clock (UTCTime, diffUTCTime, getCurrentTime)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime, utcTimeToPOSIXSeconds)
import Network.HTTP.Types (hAuthorization, parseSimpleQuery)
import Text.Read (readMaybe)
@@ -63,6 +63,7 @@ badgeStripeTests = describe "badge stripe adapter" $ do
it "cancels an intent waiting for a card after three declines in a row, and keeps one with fewer" testDeclinesCancel
it "makes a 500 at checkout a ProviderError, creating nothing" testFakeCreate500
it "makes a 500 on a read a ProviderError the next read recovers from" testFakeRead500
it "ends a call whose answer stalls in its body after the configured timeout, and reads again after" testFakeStalledAnswer
it "refuses a crypto method, since Stripe offers none" testRefusesCrypto
it "makes an unknown intent status a ProviderError, not a silent no-signal" testFakeReadUnknownStatus
it "settles a succeeded intent with no charge at read time" testSettledNoChargeReadTime
@@ -117,7 +118,10 @@ failWith :: HasCallStack => String -> IO a
failWith msg = expectationFailure msg >> error msg
withProvider :: HasCallStack => (FakeStripe -> Provider -> IO a) -> IO a
withProvider action = bounded $ withFakeStripe $ \fake -> stripeProvider (fsConfig fake) >>= action fake
withProvider = withProviderConfigured id
withProviderConfigured :: HasCallStack => (StripeConfig -> StripeConfig) -> (FakeStripe -> Provider -> IO a) -> IO a
withProviderConfigured configure action = bounded $ withFakeStripe $ \fake -> stripeProvider (configure (fsConfig fake)) >>= action fake
where
bounded act = timeout exampleCeiling act >>= maybe (failWith "the fake stripe did not answer within 20s") pure
@@ -286,6 +290,18 @@ testFakeRead500 = withProvider $ \fake p -> do
r `shouldSatisfy` namesInError "500"
pReadInvoice p pid `shouldReturn` Right (Just (SigSettled fiftyFourDollarsReceived fixtureChargeAt))
testFakeStalledAnswer :: IO ()
testFakeStalledAnswer = withProviderConfigured (\cfg -> cfg {sTimeoutMicros = 300000}) $ \fake p -> do
ProviderInvoice {piProviderRef = pid} <- createdInvoice p (SPMCard CPStripe)
answerStalled fake True
start <- getCurrentTime
pReadInvoice p pid >>= (`shouldSatisfy` namesInError ("read intent " <> pid <> " failed: timed out"))
pCreateInvoice p (SPMCard CPStripe) fiftyFourDollars >>= (`shouldSatisfy` namesInError "create intent failed: timed out")
elapsed <- (`diffUTCTime` start) <$> getCurrentTime
elapsed `shouldSatisfy` (< 2)
answerStalled fake False
pReadInvoice p pid `shouldReturn` Right Nothing
testRefusesCrypto :: IO ()
testRefusesCrypto = withProvider $ \_ p ->
pCreateInvoice p (SPMCrypto CCBtc) fiftyFourDollars >>= (`shouldSatisfy` isLeft)
+104 -11
View File
@@ -42,7 +42,7 @@ module Bots.StoreService.WebTests
where
import StoreService.Catalog (catalogCurrency, defaultCatalog)
import StoreService.Config (BTCPayConfig (..), ListenerConfig (..), NamesConfig, PollConfig (..), ServiceConfig (..), SpeedPolicy (..), StripeConfig (..), defaultLogLevel)
import StoreService.Config (BTCPayConfig (..), ListenerConfig (..), NamesConfig, PollConfig (..), ServiceConfig (..), SpeedPolicy (..), StripeConfig (..), defaultLogLevel, providerTimeoutMicros)
import StoreService.Orders (cancelOpenInvoice, codeLifetime, expireOverdue, settleOrder)
import StoreService.Poller
import StoreService.Providers
@@ -98,13 +98,15 @@ import GHC.IO.Handle.FD (handleToFd)
import Network.HTTP.Client (Manager, Request (..), RequestBody (..), Response, defaultManagerSettings, httpLbs, newManager, parseRequest, responseBody, responseHeaders, responseStatus, responseTimeoutMicro)
import Network.HTTP.Types (Header, HeaderName, hCacheControl, hContentType)
import Network.HTTP.Types.Status (statusCode)
import Network.Socket (SockAddr (..), tupleToHostAddress, tupleToHostAddress6)
import Network.Wai (Application)
import qualified Network.Wai as Wai
import qualified Network.Wai.Handler.Warp as Warp
import Simplex.Chat.Badges (BadgeCredential (..), BadgeInfo (..), BadgeMasterKey (..), BadgeType (..))
import Simplex.Chat.Badges.Ledger (addMonths, debitEntry, emptyEntry, grantEntry, issueEntry)
import Simplex.Chat.StoreService (BadgeOffer (..), BadgePrice (..), StatementCreditType (..), StatementDebitType (..), StatementEntry (..), SubscriptionState (..))
import Simplex.Chat.Badges.Types (BadgeCodePaymentStatus (..), BadgeItemStatus (..), BadgeOfferId (..), BadgePriceId (..), OfferDiscount (..))
import Simplex.Chat.PaymentService.Types (CryptoCurrency (..), CurrencyAmount (..), InvoiceId (..), InvoiceStatus (..), PaymentProvider (..), PaymentStatus (..), ServicePaymentDestination (..), ServicePaymentMethod (..))
import Simplex.Chat.PaymentService.Types (CardProvider (..), CryptoCurrency (..), CurrencyAmount (..), InvoiceId (..), InvoiceStatus (..), PaymentProvider (..), PaymentStatus (..), ServicePaymentDestination (..), ServicePaymentMethod (..))
import Simplex.Messaging.Agent.Store.Common (DBStore (..), withConnection, withTransaction)
import qualified Simplex.Messaging.Agent.Store.DB as DB
import Simplex.Messaging.Agent.Store.Interface
@@ -260,6 +262,9 @@ badgeWebTests = do
it "uses a forwarded client only when it parses as an IP address" testForwardedForMustBeAnAddress
it "keys an IPv6 client by its /64 and an IPv4-mapped one by its IPv4 address" testIPv6ClientKey
it "caps checkouts of every client together, counting only those that reach the provider" testInvoicesLimitForAll
it "caps checkouts per IPv4 /24 and IPv6 /48 before the shared cap, so the refused ones take none of it" testCheckoutLimitPerNetwork
it "admits a card checkout while the BTCPay ones are used up, the refused BTCPay ones taking none of the network's" testCardCheckoutPastSpentBTCPay
it "keys a checkout by the socket's IPv4 /24 or IPv6 /48 while forwarded addresses are not trusted" testCheckoutClientOfPeer
it "refuses every badly signed webhook, logging only the first few of a minute" testWebhookRefusalLogCapped
it "answers a poll at once with rate_limited while every hold slot is taken, and frees each slot after its hold" testHoldSlots
it "runs a search's chain reads only in a free search slot, and frees each slot after them" testSearchSlots
@@ -308,6 +313,9 @@ badgeWebTests = do
it "hands every signal the pass returned to settleOrder, unless the row answers it" testEverySignalSettles
it "passes over a listed invoice this service does not hold" testForeignRefIsPassedOver
it "changes nothing when the provider fails, and settles on the next pass" testProviderFailureLosesNothing
it "asks a stalled BTCPay once in a pass and again in the next, settling a card invoice listed after its invoices" testStalledBTCPayHoldsNoCardSettlement
it "reads the overdue invoices on their own after a list that timed out" testListTimeoutKeepsTheReads
it "reads every invoice of a provider whose reads fail without a timeout" testFailedReadKeepsTheOtherReads
it "reads the cadence fresh from the waiters each pass" testCadenceFollowsTheWaiters
it "cuts an idle sleep short when a browser arrives during it" testWaiterCutsTheIdleSleepShort
it "serves a hint batch without postponing a pass that falls due" testHintsDoNotPostponeThePass
@@ -1287,7 +1295,7 @@ testExportWebapp = do
staticDir <- prepareStaticDir root
let outDir = root </> "out"
lc = ListenerConfig {lHost = "127.0.0.1", lBadgesPort = 0, lBadgesStaticDir = staticDir, lServeWebapp = False, lBadgesExportDir = Just outDir, lTrustForwardedFor = False, lNamesStaticDir = Nothing, lNamesExportDir = Nothing, lNamesPort = Nothing}
stripeCfg = Just StripeConfig {sSecretKey = "rk_test_x", sPublishableKey = "pk_test_injected", sWebhookSecret = "whsec_x", sSessionMinutes = 60, sHost = "https://api.stripe.com"}
stripeCfg = Just StripeConfig {sSecretKey = "rk_test_x", sPublishableKey = "pk_test_injected", sWebhookSecret = "whsec_x", sSessionMinutes = 60, sHost = "https://api.stripe.com", sTimeoutMicros = providerTimeoutMicros}
exportWebapp (testServiceConfig staticDir False) {listener = lc, stripe = stripeCfg}
idx <- LB.readFile (outDir </> "index.html")
LB.toStrict idx `shouldSatisfy` BC.isInfixOf "content=\"pk_test_injected\""
@@ -1649,7 +1657,8 @@ publishTestStripe =
sPublishableKey = "pk_test_injected",
sWebhookSecret = "whsec_x",
sSessionMinutes = 60,
sHost = "https://api.stripe.com"
sHost = "https://api.stripe.com",
sTimeoutMicros = providerTimeoutMicros
}
testServesTheBuild :: IO ()
@@ -1934,9 +1943,53 @@ testInvoicesLimitForAll = bounded "checkouts for all" $ withSeededCheckout $ \cl
let malformed i = statusOf <$> postCreateAs client i "{}"
checkout i = statusOf <$> postCreateAs client i (createBody "price_legend" (Just "offer_12m") "btc" (codeHashText $ "code" <> tshow i))
-- refused requests never reach the provider, so they take none of the shared checkouts
mapM malformed [1 .. lmPerMinute invoicesLimit + 1] >>= (`shouldSatisfy` all (== 400))
mapM checkout [1 .. lmPerMinute invoicesLimit] >>= (`shouldSatisfy` notElem 429)
checkout (lmPerMinute invoicesLimit + 1) `shouldReturn` 429
mapM malformed [1 .. checkouts + 1] >>= (`shouldSatisfy` all (== 400))
mapM checkout [1 .. checkouts] >>= (`shouldSatisfy` notElem 429)
checkout (checkouts + 1) `shouldReturn` 429
where
checkouts = lmPerMinute (invoicesLimit (SPMCrypto CCBtc))
testCheckoutLimitPerNetwork :: IO ()
testCheckoutLimitPerNetwork = bounded "checkouts per network" $ withCheckoutProvider distinctProviderRefs $ \_ _ client -> do
let checkout = checkoutFrom client "btc"
perNetwork = lmPerMinute checkoutLimit
inV4Network i = "198.51.100." <> show i
inV6Network i = "2001:db8:1:" <> show i <> "::1"
mapM (checkout . inV4Network) [1 .. perNetwork] >>= (`shouldSatisfy` all (== 200))
mapM (checkout . inV4Network) [perNetwork + 1 .. perNetwork + lmPerMinute (invoicesLimit (SPMCrypto CCBtc))] >>= (`shouldSatisfy` all (== 429))
checkout "::ffff:198.51.100.250" `shouldReturn` 429
checkout "198.51.101.1" `shouldReturn` 200
mapM (checkout . inV6Network) [1 .. perNetwork] >>= (`shouldSatisfy` all (== 200))
checkout (inV6Network (perNetwork + 1)) `shouldReturn` 429
checkout "2001:db8:2::1" `shouldReturn` 200
testCardCheckoutPastSpentBTCPay :: IO ()
testCardCheckoutPastSpentBTCPay = bounded "card past spent btcpay" $ withCheckoutProviders (\ref -> [distinctProviderRefs ref, card ref]) $ \_ env client -> do
let crypto = invoicesLimit (SPMCrypto CCBtc)
fromNetwork i = "198.51.100." <> show i
replicateM_ (lmPerMinute crypto) $ takeToken (weHttp env) crypto ""
mapM (checkoutFrom client "btc" . fromNetwork) [1 .. lmPerMinute checkoutLimit] >>= (`shouldSatisfy` all (== 429))
checkoutFrom client "card" (fromNetwork (lmPerMinute checkoutLimit + 1)) `shouldReturn` 200
where
card ref =
let p = distinctProviderRefs ref
in p {pProvider = PPStripe, pCreateInvoice = \spm draft -> fmap (\inv -> inv {piDestination = SPDCard CPStripe "pi_secret"}) <$> pCreateInvoice p spm draft}
testCheckoutClientOfPeer :: IO ()
testCheckoutClientOfPeer = do
http <- newHttpEnv (listener (testServiceConfig "" False))
let from addr = checkoutClient http Wai.defaultRequest {Wai.remoteHost = addr, Wai.requestHeaders = [("X-Forwarded-For", "203.0.113.1")]}
v4 a b c d = SockAddrInet 0 (tupleToHostAddress (a, b, c, d))
v6 a b c d = SockAddrInet6 0 0 (tupleToHostAddress6 (a, b, c, d, 0, 0, 0, 1)) 0
from (v4 198 51 100 1) `shouldBe` from (v4 198 51 100 200)
from (v4 198 51 100 1) `shouldNotBe` from (v4 198 51 101 1)
from (v6 0x2001 0xdb8 1 1) `shouldBe` from (v6 0x2001 0xdb8 1 0xffff)
from (v6 0x2001 0xdb8 1 1) `shouldNotBe` from (v6 0x2001 0xdb8 2 1)
from (SockAddrInet6 0 0 (tupleToHostAddress6 (0, 0, 0, 0, 0, 0xffff, 0xc633, 0x6407)) 0) `shouldBe` from (v4 198 51 100 1)
checkoutFrom :: WebClient -> Text -> String -> IO Int
checkoutFrom client methodText address =
statusOf <$> webRequestBody client "POST" "/api/invoice" [(hContentType, "application/json"), ("X-Forwarded-For", BC.pack address)] (createBody supporterPriceId Nothing methodText (codeHashText (T.pack address)))
testHoldSlots :: IO ()
testHoldSlots = bounded "hold slots" $ withWebApp $ \env client -> do
@@ -2062,7 +2115,8 @@ testBTCPayConfig =
bWebhookSecret = "webhook-secret",
bExpiryMinutes = testExpiryMinutes,
bSpeedPolicy = MediumSpeed,
bPaymentTolerance = 0.5
bPaymentTolerance = 0.5,
bTimeoutMicros = providerTimeoutMicros
}
supporterPriceId, legendPriceId, disabledPriceId :: Text
@@ -2105,14 +2159,17 @@ postCreateAs client i body =
client
"POST"
"/api/invoice"
[(hContentType, "application/json"), ("X-Forwarded-For", BC.pack ("203.0.113." <> show i))]
[(hContentType, "application/json"), ("X-Forwarded-For", BC.pack ("203.0." <> show i <> ".1"))]
body
withCheckout :: (IORef StubState -> WebEnv -> WebClient -> IO a) -> IO a
withCheckout = withCheckoutProvider stubProvider
withCheckoutProvider :: (IORef StubState -> Provider) -> (IORef StubState -> WebEnv -> WebClient -> IO a) -> IO a
withCheckoutProvider mkProvider action =
withCheckoutProvider mkProvider = withCheckoutProviders (\ref -> [mkProvider ref])
withCheckoutProviders :: (IORef StubState -> [Provider]) -> (IORef StubState -> WebEnv -> WebClient -> IO a) -> IO a
withCheckoutProviders mkProviders action =
withServiceStore $ \st -> do
createDirectoryIfMissing True "tests/tmp"
withTempDirectory "tests/tmp" "badge-checkout" $ \root -> do
@@ -2120,7 +2177,7 @@ withCheckoutProvider mkProvider action =
seedCheckoutCatalog st
ref <- newIORef (newStubState (Right sampleProviderInvoice))
let cfg = (testServiceConfig staticDir True) {btcpay = Just testBTCPayConfig}
withListener [mkProvider ref] True holdMicros st cfg (action ref)
withListener (mkProviders ref) True holdMicros st cfg (action ref)
invoiceCount :: DBStore -> IO Int
invoiceCount st = withConnection st $ \db -> do
@@ -3089,6 +3146,42 @@ testProviderFailureLosesNothing = bounded "provider outage" $ withStubPoller rac
invoiceStatus (weStore env) iid `shouldReturn` ISPaid
stubCalls ref `shouldReturn` [StubRead "p-1", StubListOpen, StubRead "p-1"]
testStalledBTCPayHoldsNoCardSettlement :: IO ()
testStalledBTCPayHoldsNoCardSettlement = bounded "stalled btcpay" $ withFakePoller $ \fake poller env _ -> do
stalled <- btcpayProvider (fbConfig fake) {bTimeoutMicros = 300000}
ref <- newIORef (newStubState (Right sampleProviderInvoice))
seedBadgePrice (weStore env) "price1"
btcpayRows <- mapM (\i -> seedOpenRef (weStore env) i ("p-btcpay-" <> tshow i) someExpiry) [1 .. 5]
cardRow <- seedOpenRefOf PPStripe (weStore env) 9 "p-stripe" someExpiry
setSignals ref [("p-stripe", settledSignal)]
answerStalled fake True
asked <- length <$> fakeRequests fake
let pass = runOnePass poller {peProviders = [stalled, (stubProvider ref) {pProvider = PPStripe}]}
pass
subtract asked . length <$> fakeRequests fake `shouldReturn` 1
mapM (invoiceStatus (weStore env)) (btcpayRows <> [cardRow]) `shouldReturn` replicate 5 ISOpen <> [ISPaid]
pass
subtract asked . length <$> fakeRequests fake `shouldReturn` 2
testListTimeoutKeepsTheReads :: IO ()
testListTimeoutKeepsTheReads = bounded "list timeout" $ withStubPoller raceHold $ \ref poller env _ -> do
now <- getCurrentTime
seedBadgePrice (weStore env) "price1"
overdue <- seedOpenRef (weStore env) 1 "p-overdue" (addUTCTime (-3600) now)
mapM_ (\i -> seedOpenRef (weStore env) i ("p-bulk-" <> tshow i) someExpiry) [2 .. readsPerPass + 2]
failList ref (Just (timeoutError "list invoices"))
runOnePass poller
stubCalls ref `shouldReturn` [StubListOpen, StubRead "p-overdue"]
invoiceStatus (weStore env) overdue `shouldReturn` ISExpired
testFailedReadKeepsTheOtherReads :: IO ()
testFailedReadKeepsTheOtherReads = bounded "failed read" $ withStubPoller raceHold $ \ref poller env _ -> do
seedBadgePrice (weStore env) "price1"
mapM_ (\i -> seedOpenRef (weStore env) i ("p-" <> tshow i) someExpiry) [1 .. 3]
failRead ref (Just (ProviderError "connection refused"))
runOnePass poller
stubCalls ref `shouldReturn` [StubRead "p-1", StubRead "p-2", StubRead "p-3", StubListOpen]
testCadenceFollowsTheWaiters :: IO ()
testCadenceFollowsTheWaiters = bounded "cadence" $ withStubPoller raceHold $ \_ poller env client -> do
iid <- seedOpenInvoice env