Files
simplex-chat/tests/Bots/StoreService/GroupTests.hs
T
ad75fe706f store: sell and register SimpleX names (#7979)
* core: add prepaid name codes and length bounds

* store: run the names migration after badges

* store: issue and revoke prepaid name codes

* store: document issuing prepaid name codes

* store: move the ABI helpers to Names.Abi

* store: read the [names] and [chain] settings

* store: add the names chain client and reads

* store: refuse group name codes while names are off

* store: search names and preview links

* store: serve each site on its own port

* scripts: deploy the badges and names sites

* store: document search and the two sites

* store: add the drop_taken_codes migration

* store: read the names codes_only setting

* store: add the names store and order signatures

* store: take name orders by card, crypto or code

* store: document name orders and codes-only

* store: add the names transaction sender

* store: commit and register queued orders

* store: reveal and retry an owner's order

* store: document the gas key

* store: add the name balance migrations

* store: read crypto units, rates and confirmations

* store: keep a taken order's money as a balance

* store: spend a balance on another name

* store: record refunds with //refund

* store: document balances and refunds

* store: add the agreed terms migration

* store: read the terms and community names

* store: answer community and terms in search

* store: sign and store the agreed terms

* store: document the terms and community names

* store: add the invoiced units migration

* store: read the crypto an invoice asks

* store: credit late and overpaid crypto by share

* store: document crediting late crypto by share

* store: add the record changes migration

* store: find an owner's orders and move one

* store: relay owners' link edits on chain

* store: document link edits

* store: move isLoopbackHost to Config

* store: trust dev issuer keys on the local chain

* scripts: build the names site from a submodule

* scripts: add the dev setup and contract run

* store: document the dev setup and names image

* store: send a Stripe idempotency key for names

* tests: wait until a relay lets go of its edit

* store: refuse a link edit deadline under 10 min

* store: count reverted link edits in the year limit

* store: require https for a remote chain node

* store: refuse zero chain confirmations

* store: set up the dev stack from the names branch

* store: rerun a failed unpaid cleanup next pass

* store: never replace a succeeded Stripe intent

* store: refuse an ini setting written as key: value

* store: note the webapp submodule's pinned branch

* store: document confirmLanded judging by ownerOf

* store: update the names webapp submodule

* store-service: register names under the name policy, every name accepting its terms on chain (#7889)

* store: accept each name's terms on chain under the name policy

* ci: run the reduced build on sh/names-deploy

* store: address review: policy re-read, terms reads and startup log

* store: never credit an unconfirmed extra

* store: alert money sent to a paid name invoice

* store: refuse to start on another chain's node

* store: keep orders while the allowance is used up

* store: replace a stalled transaction after 3 blocks

* store: judge a name taken at confirmation depth

* store: bind the template's listener to loopback

* store: scan only the ids of active name orders

* store: refuse unknown [names] and [chain] settings

* store: fetch the webapp submodule in upgrade steps

* store: delete definitions only tests use

* store: lock only name invoices at settlement

* store: retry an unexpired commitment as usual

* store: share the helpers defined twice

* store: test route limits on the running service

* store: fix tests that could not fail

* ci: test the store service on Postgres

* store: count IPv6 clients by their /64

* store: sweep invoices read alone past a list cap

* store: cap checkouts of all clients together

* store: cap the long polls held at once

* store: stop the old badge project at upgrade

* store: keep search lookups free of previews

* store: read the ini as UTF-8 in any locale

* ci: run Postgres store tests in a UTF-8 locale

* store: cap the transactions one order sends

* store: cancel a card intent after three declines

* store: refuse a name price under a cent

* store: send each transaction with gas headroom

* store: cap searches and read terms once per block

* store: never log the group join link

* store: mask the database password at startup

* store: run one instance per database

* store: limit name codes to admins, 100 a day

* store: refuse HighSpeed settlement with names

* store: no unverified receipts with a trusted key

* store: cap the log lines of refused webhooks

* store: check Apple certificates at the signed date

* store: refuse a malformed Stripe publishable key

* store: check the owner before a refund

* store: fold the names migrations into one

* store: read onion name links through the proxy

* store: refund money after paid once confirmed

* store: limit the allowance wait to a dry run

* store: bind loopback when upgrading

* ci: cache and widen the store Postgres job

* store: fix stale and duplicate names tests

* store: fix the submodule path in the upgrade

* store: refuse unpaid name codes on the CLI

* store: apply the review's names test list

* store: finish the review's names test list

* store: restore the base registration tests

* store: pass link hosts that do not resolve here

* store: refuse a move once its sends are used up

* store: take the shared checkout at the provider

* store: hold a search slot for chain reads only

* store: state which refunds are safe on a reference

* store: check a failed order's name before refusing its move (#8060)

* store: test and document the shared checkout cap for name orders

* store: check a failed order's name on chain before refusing its move

* store: test name links whose host lookup fails

* store: test that a search holds its slot through the chain reads only

* store: restore the signed transaction check in the chain tests

* store: remove the chain tests' copy of the signed transaction check

* store: correct the search slot texts and the README's balance endpoints

* docs: system and sequence diagrams of the names service (#8068)

---------

Co-authored-by: sh-agents <350651734+sh-agents@users.noreply.github.com>
Co-authored-by: Evgeny Poberezkin <evgeny@poberezkin.com>
Co-authored-by: brenzi-agent <brenzi-agent@brenzi.ch>
Co-authored-by: Evgeny @ SimpleX Chat <259188159+evgeny-simplex@users.noreply.github.com>
2026-11-07 10:45:19 +00:00

196 lines
12 KiB
Haskell
Raw 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 OverloadedStrings #-}
module Bots.StoreService.GroupTests where
import StoreService.Config (GroupConfig (..))
import StoreService.Group (GroupAction (..), GroupEvent (..), TrackerAction (..), coalesceTrackerRefreshes, inertGroupConfig, noOwnerHint, orphanHint, trackerDecision)
import StoreService.Group.Command
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import Data.Time.Calendar (fromGregorian)
import Data.Time.Clock (UTCTime (..), addUTCTime)
import Simplex.Chat.Badges (BadgeType (..))
import Simplex.Chat.Badges.Code (BadgeCode, badgeCodeText, randomBadgeCode)
import Simplex.Chat.Controller (ChatCommand (DeleteGroup, MemberRole))
import Simplex.Chat.Library.Commands (parseChatCommand)
import Simplex.Chat.Types (GroupProfile (..))
import Simplex.Chat.Types.Shared (GroupMemberRole (..))
import qualified Simplex.Messaging.Crypto as C
import Simplex.Messaging.Util (tshow)
import Test.Hspec
badgeGroupTests :: Spec
badgeGroupTests = describe "badge group" $ do
let p = groupCmdAction GROwner
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–255, uses 1–1000\ne.g. /issue name 6 years 5 · /issue supporter months 12"
bulkUsage = ReplyText "Usage: /bulk <kind> [<length>] [years <Y> | months <M>] count <N>\nname <length>: length 6–63, years 2–10, count 1–100\nsupporter, legend, investor: months 1–255, count 1–100\ne.g. /bulk name 6 count 100 · /bulk legend months 3 count 10"
revokeUsage = ReplyText "Usage: /revoke <code>"
it "issue defaults" $ p "/issue supporter" `shouldBe` RunCmd (GCIssue BTSupporter 1 1)
it "issue with months and uses" $ p "/issue legend months 6 uses 50" `shouldBe` RunCmd (GCIssue BTLegend 6 50)
it "bulk with count" $ p "/bulk supporter count 20" `shouldBe` RunCmd (GCBulk BTSupporter 1 20)
it "issue and bulk take every badge type" $ do
map p ["/issue supporter", "/issue legend", "/issue investor"]
`shouldBe` map (\bt -> RunCmd (GCIssue bt 1 1)) [BTSupporter, BTLegend, BTInvestor]
map p ["/bulk supporter count 2", "/bulk legend count 2", "/bulk investor count 2"]
`shouldBe` map (\bt -> RunCmd (GCBulk bt 1 2)) [BTSupporter, BTLegend, BTInvestor]
it "parses the examples in the usage replies" $ do
p "/issue supporter months 12" `shouldBe` RunCmd (GCIssue BTSupporter 12 1)
p "/issue investor uses 50" `shouldBe` RunCmd (GCIssue BTInvestor 1 50)
p "/bulk legend months 3 count 10" `shouldBe` RunCmd (GCBulk BTLegend 3 10)
it "rejects a length, the names unit or the other command's option for a badge" $ do
map p ["/issue supporter 6", "/issue supporter years 2", "/issue legend months 3 years 2", "/issue supporter count 2", "/issue supporter uses 2 months 3"]
`shouldBe` replicate 5 issueUsage
map p ["/bulk supporter 6 count 2", "/bulk supporter years 2 count 2", "/bulk supporter count 2 uses 2", "/bulk supporter uses 2 count 2", "/bulk supporter count 2 months 3"]
`shouldBe` replicate 5 bulkUsage
it "rejects values past the upper bounds" $ do
p "/issue supporter uses 1001" `shouldBe` issueUsage
p "/bulk supporter count 101" `shouldBe` bulkUsage
p "/issue supporter months 256" `shouldBe` issueUsage
it "rejects zero values" $ do
p "/bulk supporter count 0" `shouldBe` bulkUsage
p "/issue supporter months 0" `shouldBe` issueUsage
it "rejects values past the machine word" $ do
let past64 = tshow (2 ^ (64 :: Int) + 1 :: Integer)
p ("/issue supporter uses " <> past64) `shouldBe` issueUsage
p ("/bulk supporter count " <> past64) `shouldBe` bulkUsage
p ("/issue supporter months " <> past64) `shouldBe` issueUsage
it "accepts the upper bounds" $ do
p "/issue supporter uses 1000" `shouldBe` RunCmd (GCIssue BTSupporter 1 1000)
p "/bulk supporter count 100" `shouldBe` RunCmd (GCBulk BTSupporter 1 100)
p "/issue supporter months 255" `shouldBe` RunCmd (GCIssue BTSupporter 255 1)
it "revoke" $ do
code <- newCode
p ("/revoke " <> badgeCodeText code) `shouldBe` RunCmd (GCRevoke code)
it "authorization, per role, as (issue, bulk, revoke)" $ do
someCode <- newCode
let runs role t = case groupCmdAction role t of
RunCmd _ -> True
_ -> False
allowed role =
( runs role "/issue supporter",
runs role "/bulk supporter count 1",
runs role ("/revoke " <> badgeCodeText someCode)
)
roles = [GRUnknown "future", GRRelay, GRObserver, GRAuthor, GRMember, GRModerator, GRAdmin, GROwner]
map (\role -> (role, allowed role)) roles
`shouldBe` [ (GRUnknown "future", (False, False, False)),
(GRRelay, (False, False, False)),
(GRObserver, (False, False, False)),
(GRAuthor, (False, False, False)),
(GRMember, (False, False, False)),
(GRModerator, (True, True, False)),
(GRAdmin, (True, True, True)),
(GROwner, (True, True, True))
]
describe "log hints give commands --run-cli parses for a group name with a space" $ do
let hintCommand = fst . T.breakOn " in --run-cli" . snd . T.breakOnEnd " with "
parsedHint hint = let cmd = hintCommand hint in (cmd, parseChatCommand (encodeUtf8 cmd))
it "owner" $
case parsedHint (T.replace "<member>" "alice" $ noOwnerHint "SimpleX Badges_1") of
(_, Right (MemberRole g m GROwner)) -> (g, m) `shouldBe` ("SimpleX Badges_1", "alice")
(cmd, r) -> expectationFailure $ "owner command " <> show cmd <> " parsed as " <> show r
it "orphan group" $
case parsedHint (orphanHint "SimpleX Badges_1") of
(_, Right (DeleteGroup g)) -> g `shouldBe` "SimpleX Badges_1"
(cmd, r) -> expectationFailure $ "delete command " <> show cmd <> " parsed as " <> show r
describe "classifying a group message" $ do
it "answers an advertised command that does not parse" $ do
map p
[ "/issue",
"/issue supporter uses 0",
"/issue supporter 3",
"/issue suporter",
"/issue supporter uses 5",
"/bulk supporter",
"/revoke",
"/revoke not-a-badge-code"
]
`shouldBe` replicate 5 issueUsage <> [bulkUsage, revokeUsage, revokeUsage]
it "answers a mistyped command only to a sender who may run it" $ do
map (`groupCmdAction` "/issue supporter uses 0") [GRMember, GRModerator, GRAdmin]
`shouldBe` [IgnoreMsg, issueUsage, issueUsage]
map (`groupCmdAction` "/bulk supporter") [GRMember, GRModerator, GRAdmin]
`shouldBe` [IgnoreMsg, bulkUsage, bulkUsage]
map (`groupCmdAction` "/revoke not-a-badge-code") [GRMember, GRModerator, GRAdmin]
`shouldBe` [IgnoreMsg, IgnoreMsg, revokeUsage]
it "runs a name code command only for an admin or owner, refusing a moderator" $ do
map (`groupCmdAction` "/issue name 6") [GRMember, GRModerator, GRAdmin, GROwner]
`shouldBe` [IgnoreMsg, ReplyText "Only admins can issue name codes.", RunCmd (GCIssueName 6 2), RunCmd (GCIssueName 6 2)]
map (`groupCmdAction` "/bulk name 6 count 2") [GRModerator, GRAdmin]
`shouldBe` [ReplyText "Only admins can issue name codes.", RunCmd (GCBulkName 6 2 2)]
it "accepts a command padded with whitespace" $ do
p " /issue supporter " `shouldBe` RunCmd (GCIssue BTSupporter 1 1)
p "\t/bulk supporter count 1" `shouldBe` RunCmd (GCBulk BTSupporter 1 1)
it "says nothing to anything that is not an advertised command" $
map p ["", "hello", "issue supporter", "/issued supporter", "/help", "see /issue above"]
`shouldBe` replicate 6 IgnoreMsg
it "says nothing to a command the sender may not run" $ do
map (`groupCmdAction` "/issue supporter") [GRMember, GRAuthor] `shouldBe` [IgnoreMsg, IgnoreMsg]
groupCmdAction GRMember "/bulk supporter count 1" `shouldBe` IgnoreMsg
it "tells a sender below admin that their revoke did not happen" $ do
code <- newCode
map (`groupCmdAction` ("/revoke " <> badgeCodeText code)) [GRMember, GRModerator]
`shouldBe` replicate 2 (ReplyText "Only admins can revoke codes. This code is now visible to all members.")
describe "configured group name and description" $ do
let cfg name descr = GroupConfig {gDisplayName = name, gDescription = descr}
profile name descr =
GroupProfile
{ displayName = name,
fullName = "",
shortDescr = Nothing,
description = descr,
image = Nothing,
publicGroup = Nothing,
groupPreferences = Nothing,
memberAdmission = Nothing,
chatLayout = Nothing
}
it "says nothing when the config matches the group profile" $ do
inertGroupConfig (cfg "SimpleX Badges" (Just "badge ops desk")) (profile "SimpleX Badges" (Just "badge ops desk"))
`shouldBe` Nothing
inertGroupConfig (cfg "SimpleX Badges" Nothing) (profile "SimpleX Badges" Nothing) `shouldBe` Nothing
it "says nothing when an omitted description meets an empty one" $
inertGroupConfig (cfg "SimpleX Badges" Nothing) (profile "SimpleX Badges" (Just "")) `shouldBe` Nothing
it "reports a name the config would change" $
inertGroupConfig (cfg "SimpleX Badges 2026" (Just "badge ops desk")) (profile "SimpleX Badges" (Just "badge ops desk"))
`shouldBe` Just "badge group config is not applied to an existing group: display_name \"SimpleX Badges 2026\", group has \"SimpleX Badges\""
it "shows a non-ASCII name as written" $
inertGroupConfig (cfg "Значки" Nothing) (profile "SimpleX Badges" Nothing)
`shouldBe` Just "badge group config is not applied to an existing group: display_name \"Значки\", group has \"SimpleX Badges\""
it "reports a description the config would change or remove" $ do
inertGroupConfig (cfg "SimpleX Badges" (Just "new desk")) (profile "SimpleX Badges" (Just "badge ops desk"))
`shouldBe` Just "badge group config is not applied to an existing group: description \"new desk\", group has \"badge ops desk\""
inertGroupConfig (cfg "SimpleX Badges" Nothing) (profile "SimpleX Badges" (Just "badge ops desk"))
`shouldBe` Just "badge group config is not applied to an existing group: description \"\", group has \"badge ops desk\""
it "reports both fields when both would change" $
inertGroupConfig (cfg "SimpleX Badges 2026" (Just "new desk")) (profile "SimpleX Badges" Nothing)
`shouldBe` Just
"badge group config is not applied to an existing group: \
\display_name \"SimpleX Badges 2026\", group has \"SimpleX Badges\"; \
\description \"new desk\", group has \"\""
describe "tracker" $
it "edits within 24h, reposts after" $ do
let t0 = UTCTime (fromGregorian 2026 1 1) 0
within = addUTCTime (23 * 3600) t0
past = addUTCTime (25 * 3600) t0
trackerDecision within t0 `shouldBe` Edit
trackerDecision past t0 `shouldBe` Repost
describe "coalescing tracker refreshes" $ do
it "keeps the last refresh of each code" $ do
code1 <- newCode
code2 <- newCode
coalesceTrackerRefreshes [GETracker 1 code1, GETracker 2 code2, GETracker 1 code1]
`shouldBe` [GETracker 2 code2, GETracker 1 code1]
it "keeps every other event, in order" $ do
code <- newCode
coalesceTrackerRefreshes
[ GEInGroup 7 (GACommand GRAdmin "a"),
GETracker 1 code,
GEInGroup 7 GAJoined,
GETracker 1 code
]
`shouldBe` [GEInGroup 7 (GACommand GRAdmin "a"), GEInGroup 7 GAJoined, GETracker 1 code]
newCode :: IO BadgeCode
newCode = C.newRandom >>= randomBadgeCode