Files
sh-agentsandsh-agents 57d67e5ff0 store: serve the pages as built, settings from /api/config (#8097)
* store: serve the pages as built, settings from /api/config

* store: badges page reads its Stripe key from the API

* store: badges worker waits for a slow page, not the old build

* store: badges page kept a stale Stripe key after the tab returned

* store: names page read settings the service no longer writes

* store: Caddy had no built sites to serve once the export was gone

* store: two page folders where one mount would do

* store: example Caddyfile missed the bare /api and /webhooks paths

* store: a hand-written page copy script where rsync does it

---------

Co-authored-by: sh-agents <350651734+sh-agents@users.noreply.github.com>
2026-11-14 12:26:54 +00:00

324 lines
18 KiB
Haskell
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module Bots.StoreService.NamesCodesTests (namesCodesTests) where
import Bots.StoreService.NamesStoreTests (order, ownerA, ownerB, placeCode, placePaid, usable)
import Bots.StoreService.WebTests (withServiceStore, withApp)
import Control.Arrow ((&&&))
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (concurrently)
import Control.Monad (forM_)
import qualified Data.Aeson as J
import qualified Data.Aeson.KeyMap as KM
import qualified Data.ByteString.Lazy.Char8 as LB
import Data.IORef (newIORef, readIORef, writeIORef)
import Data.Maybe (fromJust, fromMaybe)
import Data.Text (Text)
import Data.Time.Calendar (fromGregorian)
import Data.Time.Clock (UTCTime (..), addUTCTime)
import Network.HTTP.Client (Manager, Response, RequestBody (..), httpLbs, method, parseRequest, requestBody, responseBody, responseStatus)
import Network.HTTP.Types.Status (statusCode)
import Simplex.Chat.Badges.Code (NameCode (..), NamePrepaidCode, formatNameCode, namePrepaidCodeHash, parseNameCode, randomNamePrepaidCode)
import Simplex.Chat.Badges.Types (BadgeCodePaymentStatus (..))
import Simplex.Chat.Types.Shared (GroupMemberRole (..))
import Simplex.Messaging.Agent.Store.Common (DBStore, withTransaction)
import qualified Simplex.Messaging.Agent.Store.DB as DB
import qualified Simplex.Messaging.Crypto as C
import StoreService.Config (ListenerConfig (..))
import StoreService.Group.Command (CmdAction (..), GroupCmd (..), groupCmdAction)
import StoreService.Names.Codes
import StoreService.Names.Phases (RegistrationId (..))
import StoreService.Names.Store (NewPrepaidCode (..), PrepaidCode (..), getPrepaidCode, insertPrepaidCode, reservePrepaidCode, revokePrepaidCode, spendLandedPrepaidCode)
import StoreService.Names.Turns (Turns, newTurns)
import StoreService.Store (RevokeResult (..))
import StoreService.Web.Http (codeLimit, newHttpEnv, notFound)
import StoreService.Web.Names (Route (..), namesApp)
import StoreService.Web.Names.Codes (codeCheckHandler)
import Test.Hspec
namesCodesTests :: Spec
namesCodesTests = describe "StoreService names: prepaid codes" $ do
describe "state" $
it "reads each state from the code's row, a spent code as used even if revoked while held" testCodeStates
describe "check" $ do
it "folds a code typed in lower case with spaces to the issued one, and changes no code" testCheckFolded
it "answers code_invalid to an unknown code, an owner code or other text" testCheckInvalid
it "answers bad_request to a body that is not an object with a code text" testCheckBadBody
describe "reservations" $ do
it "reserves an unused code after the registration's write, in its transaction" testReserve
it "refuses each unusable code with its tag, a code spent by the reserving registration itself as used, before the write runs" testReserveRefusals
it "keeps a code its registration holds even if revoked or expired since, still checking the length" testReserveHeld
it "reserves nothing when the write refuses" testReserveWriteRefused
it "rolls the write back when the code's reservation is refused after it" testReserveRollsBack
it "lets one of two concurrent reservations of a code win, the other answered code_reserved" testConcurrentReserve
it "releases and spends a code only after the write, and only for its holder" testReleaseSpend
describe "group commands" $ do
it "parses /issue name with the length only, answering the usage to years and to /bulk name" testGroupNameCommands
it "answers the usage to a bad length, years or count, or a badge option" testGroupNameCommandsRefused
it "parses /revoke of a prepaid code, telling a moderator it was not revoked" testGroupRevokeNameCommand
r1, r2 :: RegistrationId
r1 = RegistrationId "r1"
r2 = RegistrationId "r2"
tNow :: UTCTime
tNow = UTCTime (fromGregorian 2026 10 21) 3600
baseCode :: PrepaidCode
baseCode =
PrepaidCode
{ pcId = 1,
pcCodeHash = "",
pcMinLength = 8,
pcYears = 2,
pcPaymentStatus = CPSPaid,
pcReservedBy = Nothing,
pcReservedAt = Nothing,
pcSpentAt = Nothing,
pcRevokedAt = Nothing,
pcExpiresAt = Nothing,
pcCreatedAt = tNow
}
testCodeStates :: IO ()
testCodeStates = do
let stateOf = codeState tNow
held = baseCode {pcReservedBy = Just r1, pcReservedAt = Just tNow}
revoked = Just tNow
map codeStateText [minBound .. maxBound] `shouldBe` ["unused", "reserved", "used", "revoked", "expired", "unpaid"]
stateOf baseCode `shouldBe` CSUnused
stateOf baseCode {pcPaymentStatus = CPSFree, pcExpiresAt = Just (addUTCTime 1 tNow)} `shouldBe` CSUnused
stateOf held `shouldBe` CSReserved
stateOf held {pcSpentAt = Just tNow} `shouldBe` CSUsed
stateOf held {pcSpentAt = Just tNow, pcRevokedAt = revoked} `shouldBe` CSUsed
stateOf baseCode {pcRevokedAt = revoked} `shouldBe` CSRevoked
stateOf held {pcRevokedAt = revoked} `shouldBe` CSRevoked
stateOf baseCode {pcPaymentStatus = CPSUnpaid} `shouldBe` CSUnpaid
stateOf baseCode {pcPaymentStatus = CPSUnpaid, pcExpiresAt = Just tNow} `shouldBe` CSUnpaid
stateOf baseCode {pcExpiresAt = Just tNow} `shouldBe` CSExpired
stateOf held {pcExpiresAt = Just tNow} `shouldBe` CSReserved
-- The route as namesRoutes registers it, since a NamesEnv needs a running chat controller.
withCodeCheck :: (DBStore -> Client -> IO a) -> IO a
withCodeCheck action = withServiceStore $ \st -> do
http <- newHttpEnv ListenerConfig {lHost = "127.0.0.1", lBadgesPort = 0, lBadgesStaticDir = "", lServeWebapp = False, lTrustForwardedFor = False, lNamesStaticDir = Nothing, lNamesPort = Nothing, lMetricsPort = Nothing}
let routes = \case
["api", "code", "check"] -> Just Route {rMethod = "POST", rLimit = codeLimit, rHandler = codeCheckHandler st}
_ -> Nothing
app req respond = fromMaybe (respond notFound) (namesApp http routes req respond)
withApp app (action st)
type Client = (Manager, String)
postCheck :: Client -> LB.ByteString -> IO (Response LB.ByteString)
postCheck (mgr, base) body = do
req <- parseRequest (base <> "/api/code/check")
httpLbs req {method = "POST", requestBody = RequestBodyLBS body} mgr
checkText :: Client -> Text -> IO (Response LB.ByteString)
checkText client code = postCheck client (J.encode (J.object ["code" J..= code]))
checkCode :: Client -> NamePrepaidCode -> IO (Response LB.ByteString)
checkCode client = checkText client . formatNameCode . NCPrepaid
answerOf :: Response LB.ByteString -> (Int, Maybe J.Object)
answerOf r = (statusCode (responseStatus r), J.decode (responseBody r))
coverage :: Int -> Int -> Text -> (Int, Maybe J.Object)
coverage minLength years state = (200, Just $ KM.fromList [("minLength", J.toJSON minLength), ("years", J.toJSON years), ("state", J.String state)])
refused :: Int -> Text -> (Int, Maybe J.Object)
refused status tag = (status, Just $ KM.fromList [("error", J.String tag)])
newCode :: Int -> IO NamePrepaidCode
newCode len = C.newRandom >>= (`randomNamePrepaidCode` len)
issueAs :: DBStore -> NamePrepaidCode -> NewPrepaidCode -> IO PrepaidCode
issueAs st code new = withTransaction st $ \db -> do
Right _ <- insertPrepaidCode db new {npcCodeHash = namePrepaidCodeHash code} tNow
fromJust <$> getPrepaidCode db (namePrepaidCodeHash code)
readCode :: DBStore -> PrepaidCode -> IO (Maybe PrepaidCode)
readCode st PrepaidCode {pcCodeHash} = withTransaction st (`getPrepaidCode` pcCodeHash)
-- The webapp's and core's vector: these two spellings are one code.
testCheckFolded :: IO ()
testCheckFolded = withCodeCheck $ \st client -> do
Just (NCPrepaid code) <- pure $ parseNameCode "SN7-BJTBP-29596-R3HJ8-25YM7"
row <- issueAs st code usable {npcMinLength = 7}
unchanged <- readCode st row
answerOf <$> checkText client "sn7 bjtbp 29596 r3hj8 25ym7" `shouldReturn` coverage 7 2 "unused"
readCode st row `shouldReturn` unchanged
testCheckInvalid :: IO ()
testCheckInvalid = withCodeCheck $ \_ client -> do
unknown <- newCode 8
let invalid = refused 400 "code_invalid"
answerOf <$> checkCode client unknown `shouldReturn` invalid
forM_
[ "SN-DWPHS-6JBFR-ZR1MA-T5HQ9-P17QM-F5GM5",
"alicebakery"
]
$ \text -> (text,) . answerOf <$> checkText client text `shouldReturn` (text, invalid)
testCheckBadBody :: IO ()
testCheckBadBody = withCodeCheck $ \_ client -> do
let badRequest = refused 400 "bad_request"
forM_ ["", "not json", "[\"SN7-BJTBP-29596-R3HJ8-25YM7\"]", "{}", "{\"code\": 7}", "{\"code\": null}"] $ \body ->
(body,) . answerOf <$> postCheck client body `shouldReturn` (body, badRequest)
let overCap = "{\"code\": \"SN7-BJTBP-29596-R3HJ8-25YM7\", \"pad\": \"" <> LB.replicate 8192 'x' <> "\"}"
answerOf <$> postCheck client overCap `shouldReturn` badRequest
-- | Two paid orders, so a code can be reserved for either.
withOrders :: (Turns -> DBStore -> IO a) -> IO a
withOrders action = withServiceStore $ \st -> do
placePaid st "r1" ownerA (order "alicebakery" 1) tNow `shouldReturn` Right ()
placePaid st "r2" ownerB (order "bobsbakery" 2) tNow `shouldReturn` Right ()
turns <- newTurns
action turns st
writeOk :: DB.Connection -> IO (Either Text ())
writeOk _ = pure $ Right ()
testReserve :: IO ()
testReserve = withOrders $ \turns st -> do
code <- newCode 8
PrepaidCode {pcCodeHash} <- issueAs st code usable
let holderInWrite db = Right . (pcReservedBy =<<) <$> getPrepaidCode db pcCodeHash :: IO (Either Text (Maybe RegistrationId))
reserveCode turns st tNow pcCodeHash r1 8 holderInWrite `shouldReturn` Right (Right Nothing)
(pcReservedBy =<<) <$> withTransaction st (`getPrepaidCode` pcCodeHash) `shouldReturn` Just r1
reserveCode turns st tNow pcCodeHash r1 11 holderInWrite `shouldReturn` Right (Right (Just r1))
testReserveRefusals :: IO ()
testReserveRefusals = withOrders $ \turns st -> do
[reserved, used, own, revoked, expired, unpaid, unknown, short] <- mapM newCode [8, 8, 8, 8, 8, 8, 8, 8]
reservedRow <- issueAs st reserved usable
usedRow <- issueAs st used usable
ownRow <- issueAs st own usable
revokedRow <- issueAs st revoked usable
expiredRow <- issueAs st expired usable {npcExpiresAt = Just tNow}
unpaidRow <- issueAs st unpaid usable {npcPaymentStatus = CPSUnpaid}
shortRow <- issueAs st short usable
placeCode st "r5" ownerA (order "erinsbakery" 5) reservedRow `shouldReturn` Right ()
placeCode st "r3" ownerB (order "carolsbakery" 4) usedRow `shouldReturn` Right ()
withTransaction st (\db -> spendLandedPrepaidCode db (pcId usedRow) (RegistrationId "r3") tNow) `shouldReturn` True
placeCode st "r6" ownerB (order "franksbakery" 6) ownRow `shouldReturn` Right ()
withTransaction st (\db -> spendLandedPrepaidCode db (pcId ownRow) (RegistrationId "r6") tNow) `shouldReturn` True
withTransaction st (\db -> revokePrepaidCode db (pcCodeHash revokedRow) tNow) `shouldReturn` Revoked (pcId revokedRow)
wrote <- newIORef False
let reserveFor rid hash len = reserveCode turns st tNow hash rid len (\_ -> Right () <$ writeIORef wrote True :: IO (Either Text ()))
reserve = reserveFor r1
rows = [reservedRow, usedRow, ownRow, revokedRow, expiredRow, unpaidRow, shortRow]
rowsBefore <- mapM (readCode st) rows
reserve (pcCodeHash reservedRow) 8 `shouldReturn` Left CRReserved
reserve (pcCodeHash usedRow) 8 `shouldReturn` Left CRUsed
reserveFor (RegistrationId "r6") (pcCodeHash ownRow) 8 `shouldReturn` Left CRUsed
reserve (pcCodeHash revokedRow) 8 `shouldReturn` Left CRInvalid
reserve (pcCodeHash expiredRow) 8 `shouldReturn` Left CRExpired
reserve (pcCodeHash unpaidRow) 8 `shouldReturn` Left CRPaymentPending
reserve (namePrepaidCodeHash unknown) 8 `shouldReturn` Left CRInvalid
reserve (pcCodeHash shortRow) 7 `shouldReturn` Left CRNotCovering
reserve (pcCodeHash revokedRow) 7 `shouldReturn` Left CRInvalid
readIORef wrote `shouldReturn` False
mapM (readCode st) rows `shouldReturn` rowsBefore
map codeRefusalTag [CRInvalid, CRUsed, CRReserved, CRExpired, CRPaymentPending, CRNotCovering]
`shouldBe` ["code_invalid", "code_used", "code_reserved", "code_expired", "payment_pending", "code_not_covering"]
testReserveHeld :: IO ()
testReserveHeld = withOrders $ \turns st -> do
code <- newCode 8
row@PrepaidCode {pcCodeHash} <- issueAs st code usable
placeCode st "r3" ownerB (order "carolsbakery" 3) row `shouldReturn` Right ()
let r3 = RegistrationId "r3"
withTransaction st (\db -> revokePrepaidCode db pcCodeHash tNow) `shouldReturn` Revoked (pcId row)
withTransaction st $ \db -> DB.execute db "UPDATE sx_badge_service_name_prepaid_codes SET expires_at = ? WHERE code_hash = ?" (tNow, DB.Binary pcCodeHash)
held <- readCode st row
reserveCode turns st tNow pcCodeHash r3 9 writeOk `shouldReturn` Right (Right ())
reserveCode turns st tNow pcCodeHash r3 7 writeOk `shouldReturn` Left CRNotCovering
reserveCode turns st tNow pcCodeHash r1 9 writeOk `shouldReturn` Left CRInvalid
readCode st row `shouldReturn` held
testReserveWriteRefused :: IO ()
testReserveWriteRefused = withOrders $ \turns st -> do
code <- newCode 8
row@PrepaidCode {pcCodeHash} <- issueAs st code usable
reserveCode turns st tNow pcCodeHash r1 8 (\_ -> pure (Left "registration_changed" :: Either Text ())) `shouldReturn` Right (Left "registration_changed")
(pcReservedBy =<<) <$> readCode st row `shouldReturn` Nothing
reserveCode turns st tNow pcCodeHash r2 8 writeOk `shouldReturn` Right (Right ())
(pcReservedBy =<<) <$> readCode st row `shouldReturn` Just r2
-- | The write reserves the code for another registration, as a writer outside this process could between the check and the reservation.
testReserveRollsBack :: IO ()
testReserveRollsBack = withOrders $ \turns st -> do
code <- newCode 8
row@PrepaidCode {pcId, pcCodeHash} <- issueAs st code usable
let takenMeanwhile db = Right () <$ reservePrepaidCode db pcId r2 tNow :: IO (Either Text ())
reserveCode turns st tNow pcCodeHash r1 8 takenMeanwhile `shouldReturn` Left CRReserved
readCode st row `shouldReturn` Just row
testConcurrentReserve :: IO ()
testConcurrentReserve = withOrders $ \turns st -> do
code <- newCode 8
row@PrepaidCode {pcCodeHash} <- issueAs st code usable
let slowWrite _ = Right () <$ threadDelay 100000 :: IO (Either Text ())
reserveFor rid = reserveCode turns st tNow pcCodeHash rid 8 slowWrite
outcomes <- concurrently (reserveFor r1) (reserveFor r2)
outcomes `shouldSatisfy` (`elem` [(Right (Right ()), Left CRReserved), (Left CRReserved, Right (Right ()))])
holder <- (pcReservedBy =<<) <$> readCode st row
holder `shouldBe` Just (if fst outcomes == Right (Right ()) then r1 else r2)
testReleaseSpend :: IO ()
testReleaseSpend = withOrders $ \turns st -> do
[spent, released] <- mapM newCode [8, 8]
spentRow <- issueAs st spent usable
releasedRow <- issueAs st released usable
placeCode st "r3" ownerB (order "carolsbakery" 3) spentRow `shouldReturn` Right ()
placeCode st "r4" ownerB (order "davesbakery" 4) releasedRow `shouldReturn` Right ()
let r3 = RegistrationId "r3"
r4 = RegistrationId "r4"
holderInWrite row db = Right . (pcReservedBy =<<) <$> getPrepaidCode db (pcCodeHash row) :: IO (Either Text (Maybe RegistrationId))
changed _ = pure (Left "registration_changed") :: IO (Either Text ())
spendLandedCode turns st tNow (pcId spentRow) r3 changed `shouldReturn` Left "registration_changed"
(pcSpentAt =<<) <$> readCode st spentRow `shouldReturn` Nothing
spendLandedCode turns st tNow (pcId spentRow) r1 writeOk `shouldReturn` Right ((), False)
spendLandedCode turns st tNow (pcId spentRow) r3 writeOk `shouldReturn` Right ((), True)
((pcReservedBy =<<) &&& (pcSpentAt =<<)) <$> readCode st spentRow `shouldReturn` (Just r3, Just tNow)
releaseCode turns st (pcId spentRow) r3 writeOk `shouldReturn` Right ((), False)
releaseCode turns st (pcId releasedRow) r4 changed `shouldReturn` Left "registration_changed"
releaseCode turns st (pcId releasedRow) r1 writeOk `shouldReturn` Right ((), False)
releaseCode turns st (pcId releasedRow) r4 (holderInWrite releasedRow) `shouldReturn` Right (Just r4, True)
(pcReservedBy =<<) <$> readCode st releasedRow `shouldReturn` Nothing
testGroupNameCommands :: IO ()
testGroupNameCommands = do
let p = groupCmdAction GRAdmin
p "/issue name 8" `shouldBe` RunCmd (GCIssueName 8 2)
p "/issue name 63" `shouldBe` RunCmd (GCIssueName 63 2)
p "/issue name 6 years 2" `shouldBe` RunCmd (GCIssueName 6 2)
p "/issue name 63 years 10" `shouldBe` RunCmd (GCIssueName 63 10)
map p ["/bulk name 7 count 3", "/bulk name 12 years 2 count 100", "/bulk name 6 count 1"] `shouldBe` replicate 3 bulkUsage
groupCmdAction GRMember "/issue name 8" `shouldBe` IgnoreMsg
testGroupRevokeNameCommand :: IO ()
testGroupRevokeNameCommand = do
code <- newCode 8
let cmd = "/revoke " <> formatNameCode (NCPrepaid code)
groupCmdAction GRAdmin cmd `shouldBe` RunCmd (GCRevokeName code)
groupCmdAction GRModerator cmd `shouldBe` ReplyText "Only admins can revoke codes. This code is now visible to all members."
groupCmdAction GRAdmin (cmd <> " junk") `shouldBe` ReplyText "Usage: /revoke <code>"
testGroupNameCommandsRefused :: IO ()
testGroupNameCommandsRefused = do
let p = groupCmdAction GRModerator
forM_ ["name", "name 5", "name 64", "name 06", "name 8 years 1", "name 8 years 0", "name 8 years 11", "name 8 uses 2", "name 8 months 2", "name 8 paid", "name 8 years 18446744073709551618", "name 8 count 2", "name 8 count 1"] $ \args ->
(args, p ("/issue " <> args)) `shouldBe` (args, issueUsage)
forM_ ["name 8", "name 8 count 0", "name 8 count 101", "name 8 years 1 count 2", "name 5 count 2", "name 08 count 2", "name 8 months 2 count 2", "name 8 count 2 uses 2", "name 8 uses 2 count 2", "name 8 count 2 years 5", "name count 2"] $ \args ->
(args, p ("/bulk " <> args)) `shouldBe` (args, bulkUsage)
issueUsage, bulkUsage :: CmdAction
issueUsage = ReplyText "Usage: /issue <kind> [<length>] [years <Y> | months <M>] [uses <N>]\nname <length>: length 6–63, years 2–10\nsupporter, legend, investor: months 1–12, uses 1–1000\ne.g. /issue name 6 years 5 · /issue supporter months 12"
bulkUsage = ReplyText "Usage: /bulk <kind> [months <M>] count <N>\nsupporter, legend, investor: months 1–12, count 1–100\ne.g. /bulk legend months 3 count 10"