mirror of
https://github.com/simplex-chat/simplex-chat.git
synced 2026-11-22 19:58:26 +00:00
core: badge service config file
This commit is contained in:
1 parent
f36e93de46
commit
1cb6390ce0
6 files changed
+589
-11
No files matched your search
@@ -0,0 +1,325 @@
|
||||
{-# LANGUAGE NamedFieldPuns #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
|
||||
-- | `badge_service.ini` deployment configuration (decision 4): the record, the parser and
|
||||
-- startup validation, plus 'BadgeServiceEnv', the single runtime value every handler
|
||||
-- receives. Secrets are always file paths named from the ini, never inline values, so the
|
||||
-- ini can go into configuration management while the secrets do not.
|
||||
module BadgeService.Config
|
||||
( IssuerConfig (..),
|
||||
CodesConfig (..),
|
||||
WebConfig (..),
|
||||
BtcPayConfig (..),
|
||||
StripeConfig (..),
|
||||
ServiceConfig (..),
|
||||
ReconcileConfig (..),
|
||||
BadgeServiceConfig (..),
|
||||
readBadgeServiceConfig,
|
||||
BadgeServiceEnv (..),
|
||||
newBadgeServiceEnv,
|
||||
)
|
||||
where
|
||||
|
||||
import Data.Ini (Ini, keys, lookupValue, readIniFile, sections)
|
||||
import Data.Maybe (isJust)
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
import Data.Time.Clock (UTCTime, getCurrentTime)
|
||||
import Simplex.Messaging.Agent.Store.Common (DBStore)
|
||||
import Simplex.Messaging.Util (eitherToMaybe)
|
||||
import System.Directory (doesFileExist)
|
||||
import Text.Read (readMaybe)
|
||||
|
||||
data IssuerConfig = IssuerConfig
|
||||
{ issuerKeyFile :: FilePath,
|
||||
issuerKeyIdx :: Int
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
data CodesConfig = CodesConfig
|
||||
{ codesSecretFile :: FilePath,
|
||||
codesDefaultExpiryDays :: Int
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
data WebConfig = WebConfig
|
||||
{ webPort :: Int,
|
||||
webHost :: Text,
|
||||
webBaseUrl :: Text,
|
||||
webSupportContact :: Text,
|
||||
webBehindProxy :: Bool,
|
||||
webDir :: Maybe FilePath
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
data BtcPayConfig = BtcPayConfig
|
||||
{ btcPayUrl :: Text,
|
||||
btcPayStoreId :: Text,
|
||||
btcPayApiKeyFile :: FilePath,
|
||||
btcPayWebhookSecretFile :: FilePath,
|
||||
btcPayXmrMethodId :: Text,
|
||||
btcPayBtcExpiryMinutes :: Int,
|
||||
btcPayXmrExpiryMinutes :: Int
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
data StripeConfig = StripeConfig
|
||||
{ stripeSecretKeyFile :: FilePath,
|
||||
stripeWebhookSecretFile :: FilePath
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
newtype ServiceConfig = ServiceConfig
|
||||
{ serviceAddressFile :: Maybe FilePath
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
newtype ReconcileConfig = ReconcileConfig
|
||||
{ reconcileIntervalSeconds :: Int
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
data BadgeServiceConfig = BadgeServiceConfig
|
||||
{ issuer :: IssuerConfig,
|
||||
codes :: CodesConfig,
|
||||
web :: Maybe WebConfig,
|
||||
btcpay :: Maybe BtcPayConfig,
|
||||
stripe :: Maybe StripeConfig,
|
||||
service :: Maybe ServiceConfig,
|
||||
reconcile :: Maybe ReconcileConfig
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
-- | Read, parse and validate `badge_service.ini`. Returns 'Left' naming the file, and naming
|
||||
-- the offending key where there is one, on: a missing file, an unparsable ini, an unknown
|
||||
-- key in a known section, a missing `[issuer]` or `[codes]` section, or a half-configured
|
||||
-- `[btcpay]`/`[stripe]` section.
|
||||
readBadgeServiceConfig :: FilePath -> IO (Either String BadgeServiceConfig)
|
||||
readBadgeServiceConfig path = do
|
||||
exists <- doesFileExist path
|
||||
if not exists
|
||||
then pure $ configError path "file not found"
|
||||
else do
|
||||
parsed <- readIniFile path
|
||||
pure $ case parsed of
|
||||
Left e -> configError path e
|
||||
Right ini -> parseBadgeServiceConfig path ini
|
||||
|
||||
parseBadgeServiceConfig :: FilePath -> Ini -> Either String BadgeServiceConfig
|
||||
parseBadgeServiceConfig path ini = do
|
||||
issuerCfg <- parseIssuer path ini
|
||||
codesCfg <- parseCodes path ini
|
||||
webCfg <- parseWeb path ini
|
||||
btcPayCfg <- parseBtcPay path ini
|
||||
stripeCfg <- parseStripe path ini
|
||||
serviceCfg <- parseService path ini
|
||||
reconcileCfg <- parseReconcile path ini
|
||||
if (isJust btcPayCfg || isJust stripeCfg) && not (isJust webCfg)
|
||||
then configError path "[web] section is required when a provider (btcpay or stripe) is configured"
|
||||
else
|
||||
pure
|
||||
BadgeServiceConfig
|
||||
{ issuer = issuerCfg,
|
||||
codes = codesCfg,
|
||||
web = webCfg,
|
||||
btcpay = btcPayCfg,
|
||||
stripe = stripeCfg,
|
||||
service = serviceCfg,
|
||||
reconcile = reconcileCfg
|
||||
}
|
||||
|
||||
issuerKeys :: [Text]
|
||||
issuerKeys = ["key_file", "key_idx"]
|
||||
|
||||
parseIssuer :: FilePath -> Ini -> Either String IssuerConfig
|
||||
parseIssuer path ini = do
|
||||
requiredSection path "issuer" ini
|
||||
checkKnownKeys path "issuer" issuerKeys ini
|
||||
keyFile <- T.unpack <$> requiredValue path "issuer" "key_file" ini
|
||||
keyIdx <- requiredInt path "issuer" "key_idx" ini
|
||||
pure IssuerConfig {issuerKeyFile = keyFile, issuerKeyIdx = keyIdx}
|
||||
|
||||
codesKeys :: [Text]
|
||||
codesKeys = ["secret_file", "default_expiry_days"]
|
||||
|
||||
parseCodes :: FilePath -> Ini -> Either String CodesConfig
|
||||
parseCodes path ini = do
|
||||
requiredSection path "codes" ini
|
||||
checkKnownKeys path "codes" codesKeys ini
|
||||
secretFile <- T.unpack <$> requiredValue path "codes" "secret_file" ini
|
||||
expiryDays <- requiredInt path "codes" "default_expiry_days" ini
|
||||
pure CodesConfig {codesSecretFile = secretFile, codesDefaultExpiryDays = expiryDays}
|
||||
|
||||
webKeys :: [Text]
|
||||
webKeys = ["port", "host", "base_url", "support_contact", "behind_proxy", "web_dir"]
|
||||
|
||||
parseWeb :: FilePath -> Ini -> Either String (Maybe WebConfig)
|
||||
parseWeb path ini
|
||||
| "web" `notElem` sections ini = Right Nothing
|
||||
| otherwise = do
|
||||
checkKnownKeys path "web" webKeys ini
|
||||
port <- requiredInt path "web" "port" ini
|
||||
baseUrl <- requiredValue path "web" "base_url" ini
|
||||
supportContact <- requiredValue path "web" "support_contact" ini
|
||||
let host = optionalValue "127.0.0.1" "web" "host" ini
|
||||
dir = T.unpack <$> optionalMaybeValue "web" "web_dir" ini
|
||||
behindProxy <- optionalBool path "web" "behind_proxy" False ini
|
||||
pure $
|
||||
Just
|
||||
WebConfig
|
||||
{ webPort = port,
|
||||
webHost = host,
|
||||
webBaseUrl = baseUrl,
|
||||
webSupportContact = supportContact,
|
||||
webBehindProxy = behindProxy,
|
||||
webDir = dir
|
||||
}
|
||||
|
||||
btcPayKeys :: [Text]
|
||||
btcPayKeys = ["url", "store_id", "api_key_file", "webhook_secret_file", "xmr_method_id", "btc_expiry_minutes", "xmr_expiry_minutes"]
|
||||
|
||||
btcPayRequiredKeys :: [Text]
|
||||
btcPayRequiredKeys = ["url", "store_id", "api_key_file", "webhook_secret_file"]
|
||||
|
||||
parseBtcPay :: FilePath -> Ini -> Either String (Maybe BtcPayConfig)
|
||||
parseBtcPay path ini
|
||||
| "btcpay" `notElem` sections ini = Right Nothing
|
||||
| otherwise = do
|
||||
checkKnownKeys path "btcpay" btcPayKeys ini
|
||||
case requiredKeysPresent "btcpay" btcPayRequiredKeys ini of
|
||||
[] -> Right Nothing
|
||||
present
|
||||
| length present == length btcPayRequiredKeys -> do
|
||||
url <- requiredValue path "btcpay" "url" ini
|
||||
storeId <- requiredValue path "btcpay" "store_id" ini
|
||||
apiKeyFile <- T.unpack <$> requiredValue path "btcpay" "api_key_file" ini
|
||||
webhookSecretFile <- T.unpack <$> requiredValue path "btcpay" "webhook_secret_file" ini
|
||||
let xmrMethodId = optionalValue "XMR-CHAIN" "btcpay" "xmr_method_id" ini
|
||||
btcExpiryMinutes <- optionalInt path "btcpay" "btc_expiry_minutes" 15 ini
|
||||
xmrExpiryMinutes <- optionalInt path "btcpay" "xmr_expiry_minutes" 60 ini
|
||||
pure $
|
||||
Just
|
||||
BtcPayConfig
|
||||
{ btcPayUrl = url,
|
||||
btcPayStoreId = storeId,
|
||||
btcPayApiKeyFile = apiKeyFile,
|
||||
btcPayWebhookSecretFile = webhookSecretFile,
|
||||
btcPayXmrMethodId = xmrMethodId,
|
||||
btcPayBtcExpiryMinutes = btcExpiryMinutes,
|
||||
btcPayXmrExpiryMinutes = xmrExpiryMinutes
|
||||
}
|
||||
| otherwise ->
|
||||
let missing = head $ filter (`notElem` present) btcPayRequiredKeys
|
||||
in halfConfiguredError path "btcpay" missing btcPayRequiredKeys
|
||||
|
||||
stripeKeys :: [Text]
|
||||
stripeKeys = ["secret_key_file", "webhook_secret_file"]
|
||||
|
||||
parseStripe :: FilePath -> Ini -> Either String (Maybe StripeConfig)
|
||||
parseStripe path ini
|
||||
| "stripe" `notElem` sections ini = Right Nothing
|
||||
| otherwise = do
|
||||
checkKnownKeys path "stripe" stripeKeys ini
|
||||
case requiredKeysPresent "stripe" stripeKeys ini of
|
||||
[] -> Right Nothing
|
||||
present
|
||||
| length present == length stripeKeys -> do
|
||||
secretKeyFile <- T.unpack <$> requiredValue path "stripe" "secret_key_file" ini
|
||||
webhookSecretFile <- T.unpack <$> requiredValue path "stripe" "webhook_secret_file" ini
|
||||
pure $ Just StripeConfig {stripeSecretKeyFile = secretKeyFile, stripeWebhookSecretFile = webhookSecretFile}
|
||||
| otherwise ->
|
||||
let missing = head $ filter (`notElem` present) stripeKeys
|
||||
in halfConfiguredError path "stripe" missing stripeKeys
|
||||
|
||||
parseService :: FilePath -> Ini -> Either String (Maybe ServiceConfig)
|
||||
parseService path ini
|
||||
| "service" `notElem` sections ini = Right Nothing
|
||||
| otherwise = do
|
||||
checkKnownKeys path "service" ["address_file"] ini
|
||||
let addressFile = T.unpack <$> optionalMaybeValue "service" "address_file" ini
|
||||
pure $ Just ServiceConfig {serviceAddressFile = addressFile}
|
||||
|
||||
parseReconcile :: FilePath -> Ini -> Either String (Maybe ReconcileConfig)
|
||||
parseReconcile path ini
|
||||
| "reconcile" `notElem` sections ini = Right Nothing
|
||||
| otherwise = do
|
||||
checkKnownKeys path "reconcile" ["interval_seconds"] ini
|
||||
intervalSeconds <- requiredInt path "reconcile" "interval_seconds" ini
|
||||
pure $ Just ReconcileConfig {reconcileIntervalSeconds = intervalSeconds}
|
||||
|
||||
-- Validation helpers ---------------------------------------------------------
|
||||
|
||||
configError :: FilePath -> String -> Either String a
|
||||
configError path msg = Left (path <> ": " <> msg)
|
||||
|
||||
halfConfiguredError :: FilePath -> Text -> Text -> [Text] -> Either String a
|
||||
halfConfiguredError path section missingKey allRequired =
|
||||
configError path $
|
||||
"section [" <> T.unpack section <> "] is missing key '" <> T.unpack missingKey
|
||||
<> "' ("
|
||||
<> T.unpack (T.intercalate ", " allRequired)
|
||||
<> " must all be set together)"
|
||||
|
||||
requiredKeysPresent :: Text -> [Text] -> Ini -> [Text]
|
||||
requiredKeysPresent section requiredKeys ini =
|
||||
filter (\k -> either (const False) (const True) (lookupValue section k ini)) requiredKeys
|
||||
|
||||
requiredSection :: FilePath -> Text -> Ini -> Either String ()
|
||||
requiredSection path name ini
|
||||
| name `elem` sections ini = Right ()
|
||||
| otherwise = configError path ("missing required section [" <> T.unpack name <> "]")
|
||||
|
||||
checkKnownKeys :: FilePath -> Text -> [Text] -> Ini -> Either String ()
|
||||
checkKnownKeys path name allowed ini = case keys name ini of
|
||||
Left e -> configError path e
|
||||
Right ks -> case filter (`notElem` allowed) ks of
|
||||
[] -> Right ()
|
||||
(k : _) -> configError path ("unknown key '" <> T.unpack k <> "' in section [" <> T.unpack name <> "]")
|
||||
|
||||
requiredValue :: FilePath -> Text -> Text -> Ini -> Either String Text
|
||||
requiredValue path section key ini = case lookupValue section key ini of
|
||||
Right v -> Right v
|
||||
Left _ -> configError path ("missing required key '" <> T.unpack key <> "' in section [" <> T.unpack section <> "]")
|
||||
|
||||
requiredInt :: FilePath -> Text -> Text -> Ini -> Either String Int
|
||||
requiredInt path section key ini = do
|
||||
v <- requiredValue path section key ini
|
||||
case readMaybe (T.unpack v) of
|
||||
Just n -> Right n
|
||||
Nothing -> configError path ("key '" <> T.unpack key <> "' in section [" <> T.unpack section <> "] must be an integer, got: " <> T.unpack v)
|
||||
|
||||
optionalValue :: Text -> Text -> Text -> Ini -> Text
|
||||
optionalValue def section key ini = either (const def) id (lookupValue section key ini)
|
||||
|
||||
optionalMaybeValue :: Text -> Text -> Ini -> Maybe Text
|
||||
optionalMaybeValue section key ini = eitherToMaybe (lookupValue section key ini)
|
||||
|
||||
optionalInt :: FilePath -> Text -> Text -> Int -> Ini -> Either String Int
|
||||
optionalInt path section key def ini = case lookupValue section key ini of
|
||||
Left _ -> Right def
|
||||
Right v -> case readMaybe (T.unpack v) of
|
||||
Just n -> Right n
|
||||
Nothing -> configError path ("key '" <> T.unpack key <> "' in section [" <> T.unpack section <> "] must be an integer, got: " <> T.unpack v)
|
||||
|
||||
optionalBool :: FilePath -> Text -> Text -> Bool -> Ini -> Either String Bool
|
||||
optionalBool path section key def ini = case lookupValue section key ini of
|
||||
Left _ -> Right def
|
||||
Right "on" -> Right True
|
||||
Right "off" -> Right False
|
||||
Right v -> configError path ("key '" <> T.unpack key <> "' in section [" <> T.unpack section <> "] must be 'on' or 'off', got: " <> T.unpack v)
|
||||
|
||||
-- Runtime environment ---------------------------------------------------------
|
||||
|
||||
-- | The single runtime value every badge service handler receives. A6 defines only the
|
||||
-- parsed config, the store and the clock; later steps add the field they own (the decoded
|
||||
-- code secret, the issuer key, RPC token buckets, provider clients, IP buckets).
|
||||
data BadgeServiceEnv = BadgeServiceEnv
|
||||
{ config :: BadgeServiceConfig,
|
||||
store :: DBStore,
|
||||
-- | Every service component reads the clock through this, and none calls
|
||||
-- 'getCurrentTime' directly, so a test can advance service time without sleeping.
|
||||
now :: IO UTCTime
|
||||
}
|
||||
|
||||
newBadgeServiceEnv :: BadgeServiceConfig -> DBStore -> IO BadgeServiceEnv
|
||||
newBadgeServiceEnv cfg st = pure BadgeServiceEnv {config = cfg, store = st, now = getCurrentTime}
|
||||
@@ -15,6 +15,7 @@ import qualified Data.Text as T
|
||||
import Options.Applicative
|
||||
import Simplex.Chat.Controller (updateStr, versionNumber, versionString)
|
||||
import Simplex.Chat.Options (ChatCmdLog (..), ChatOpts (..), CoreChatOpts, CreateBotOpts (..), coreChatOptsP)
|
||||
import System.FilePath ((</>))
|
||||
|
||||
data BadgeServiceOpts = BadgeServiceOpts
|
||||
{ coreOptions :: CoreChatOpts,
|
||||
@@ -22,12 +23,21 @@ data BadgeServiceOpts = BadgeServiceOpts
|
||||
clientService :: Bool,
|
||||
noAddress :: Bool,
|
||||
runCLI :: Bool,
|
||||
testing :: Bool
|
||||
testing :: Bool,
|
||||
configFile :: FilePath
|
||||
}
|
||||
|
||||
badgeServiceOpts :: FilePath -> FilePath -> Parser BadgeServiceOpts
|
||||
badgeServiceOpts appDir defaultDbName = do
|
||||
coreOptions <- coreChatOptsP appDir defaultDbName
|
||||
configFile <-
|
||||
strOption
|
||||
( long "config"
|
||||
<> metavar "FILE"
|
||||
<> help "Path to the badge service deployment configuration (ini)"
|
||||
<> value (appDir </> "badge_service.ini")
|
||||
<> showDefault
|
||||
)
|
||||
serviceName <-
|
||||
strOption
|
||||
( long "service-name"
|
||||
@@ -57,7 +67,8 @@ badgeServiceOpts appDir defaultDbName = do
|
||||
clientService,
|
||||
noAddress,
|
||||
runCLI,
|
||||
testing = False
|
||||
testing = False,
|
||||
configFile
|
||||
}
|
||||
|
||||
getBadgeServiceOpts :: FilePath -> FilePath -> IO BadgeServiceOpts
|
||||
|
||||
@@ -11,6 +11,7 @@ module BadgeService.Service
|
||||
where
|
||||
|
||||
import BadgeService.Catalog (seedCatalog)
|
||||
import BadgeService.Config (BadgeServiceEnv, newBadgeServiceEnv, readBadgeServiceConfig)
|
||||
import BadgeService.Options
|
||||
import BadgeService.Store.Migrate (runBadgeServiceMigrations)
|
||||
import Control.Concurrent.STM
|
||||
@@ -34,14 +35,16 @@ import System.Exit (exitFailure)
|
||||
|
||||
data ServiceState = ServiceState
|
||||
{ serviceCC :: TMVar ChatController,
|
||||
serviceEnv :: TMVar BadgeServiceEnv,
|
||||
serviceRequestQ :: TQueue (User, AgentInvId, J.Object)
|
||||
}
|
||||
|
||||
newServiceState :: IO ServiceState
|
||||
newServiceState = do
|
||||
serviceCC <- newEmptyTMVarIO
|
||||
serviceEnv <- newEmptyTMVarIO
|
||||
serviceRequestQ <- newTQueueIO
|
||||
pure ServiceState {serviceCC, serviceRequestQ}
|
||||
pure ServiceState {serviceCC, serviceEnv, serviceRequestQ}
|
||||
|
||||
welcomeGetOpts :: IO BadgeServiceOpts
|
||||
welcomeGetOpts = do
|
||||
@@ -58,7 +61,7 @@ badgeService opts cfg = do
|
||||
env <- newServiceState
|
||||
let chatHooks =
|
||||
defaultChatHooks
|
||||
{ preStartHook = Just $ badgePreStartHook opts,
|
||||
{ preStartHook = Just $ badgePreStartHook opts env,
|
||||
postStartHook = Just $ badgePostStartHook opts env
|
||||
}
|
||||
simplexChatCore cfg {chatHooks} (mkChatOpts opts) $ \_ cc ->
|
||||
@@ -80,7 +83,7 @@ badgeServiceCLI opts = do
|
||||
pure ev
|
||||
chatHooks =
|
||||
defaultChatHooks
|
||||
{ preStartHook = Just $ badgePreStartHook opts,
|
||||
{ preStartHook = Just $ badgePreStartHook opts env,
|
||||
postStartHook = Just $ badgePostStartHook opts env,
|
||||
eventHook = Just eventHook
|
||||
}
|
||||
@@ -100,10 +103,19 @@ processQueuedRequests env = do
|
||||
-- of the service must see the catalog before it can serve a request. B8's operator
|
||||
-- subcommand (not yet implemented) will need to call seedCatalog the same way, so operator
|
||||
-- tooling sees the same catalog.
|
||||
badgePreStartHook :: BadgeServiceOpts -> ChatController -> IO ()
|
||||
badgePreStartHook opts ChatController {config, chatStore} = do
|
||||
--
|
||||
-- The badge service env is built here too, once, after migrations and seedCatalog: it reads
|
||||
-- and validates badge_service.ini, exits on a bad config (naming the file and the offending
|
||||
-- key), and stores the built env for badgePostStartHook and the request handlers to reach.
|
||||
badgePreStartHook :: BadgeServiceOpts -> ServiceState -> ChatController -> IO ()
|
||||
badgePreStartHook opts@BadgeServiceOpts {configFile} ServiceState {serviceEnv} ChatController {config, chatStore} = do
|
||||
runBadgeServiceMigrations opts config chatStore
|
||||
seedCatalog chatStore
|
||||
readBadgeServiceConfig configFile >>= \case
|
||||
Left e -> putStrLn e >> exitFailure
|
||||
Right bsConfig -> do
|
||||
bsEnv <- newBadgeServiceEnv bsConfig chatStore
|
||||
atomically $ putTMVar serviceEnv bsEnv
|
||||
|
||||
badgePostStartHook :: BadgeServiceOpts -> ServiceState -> ChatController -> IO ()
|
||||
badgePostStartHook BadgeServiceOpts {noAddress, testing} env cc = do
|
||||
|
||||
@@ -132,7 +132,7 @@ The two `-m` filters are needed because the badge tests live under two hspec pat
|
||||
| A3 | Service schema: `web_orders`, `codes`, `provider_events` | — | ☑ |
|
||||
| A4 | `Catalog.hs`: internal pricing, totals, seeding | A2, A5 | ☑ |
|
||||
| A5 | Cabal dependencies for the service | — | ☑ |
|
||||
| A6 | `badge_service.ini`: configuration file | A3, A4, A5 | ☐ |
|
||||
| A6 | `badge_service.ini`: configuration file | A3, A4, A5 | ☑ |
|
||||
| B1 | Store layer: purchases, ledger, issuances, codes, catalog | A2, A3, A4, A5 | ☐ |
|
||||
| B2 | `Ledger.hs`: pure transitions and property tests | A5 | ☐ |
|
||||
| B3 | `Codes.hs`: derive, encode, hash, classify | A5, A6, B1 | ☐ |
|
||||
|
||||
@@ -417,6 +417,7 @@ executable simplex-badge-service
|
||||
StrictData
|
||||
other-modules:
|
||||
BadgeService.Catalog
|
||||
BadgeService.Config
|
||||
BadgeService.Options
|
||||
BadgeService.Service
|
||||
BadgeService.Store.Migrate
|
||||
@@ -431,6 +432,7 @@ executable simplex-badge-service
|
||||
, crypton ==0.34.*
|
||||
, directory ==1.3.*
|
||||
, file-embed ==0.0.15.*
|
||||
, filepath ==1.4.*
|
||||
, http-client ==0.7.*
|
||||
, http-client-tls ==0.3.*
|
||||
, http-types ==0.12.*
|
||||
@@ -693,6 +695,7 @@ test-suite simplex-chat-test
|
||||
API.Docs.Types
|
||||
API.TypeInfo
|
||||
BadgeService.Catalog
|
||||
BadgeService.Config
|
||||
BadgeService.Options
|
||||
BadgeService.Service
|
||||
BadgeService.Store.Migrate
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
module Bots.BadgeServiceTests where
|
||||
|
||||
import BadgeService.Catalog (catalogTotals, defaultCatalog, offerTotal, seedCatalog)
|
||||
import BadgeService.Config (BadgeServiceConfig (..), readBadgeServiceConfig)
|
||||
import BadgeService.Options
|
||||
import BadgeService.Service
|
||||
import ChatClient
|
||||
@@ -13,8 +14,11 @@ import ChatTests.DBUtils
|
||||
import ChatTests.Utils
|
||||
import Control.Concurrent (forkIO, killThread, threadDelay)
|
||||
import Control.Exception (SomeException, evaluate, finally, try)
|
||||
import Crypto.Random (getRandomBytes)
|
||||
import qualified Data.Aeson as J
|
||||
import Data.List (find)
|
||||
import qualified Data.ByteString.Base64 as B64
|
||||
import qualified Data.ByteString.Char8 as BC
|
||||
import Data.List (find, isInfixOf)
|
||||
import Data.Maybe (fromJust, isJust)
|
||||
import Data.String (fromString)
|
||||
import Data.Text (Text)
|
||||
@@ -32,6 +36,8 @@ import Simplex.Messaging.Agent.Store.Common (DBStore, withConnection)
|
||||
import qualified Simplex.Messaging.Agent.Store.DB as DB
|
||||
import Simplex.Messaging.Agent.Store.Interface (closeDBStore, createDBStore)
|
||||
import Simplex.Messaging.Agent.Store.Shared (Migration (..), MigrationConfig (..), MigrationConfirmation (..), MigrationsToRun (..), toDownMigration)
|
||||
import Simplex.Messaging.Crypto.BBS (BBSPublicKey (..), BBSSecretKey (..), bbsKeyGen)
|
||||
import Simplex.Messaging.Encoding.String (strEncode)
|
||||
import System.FilePath ((</>))
|
||||
import Test.Hspec hiding (it)
|
||||
#if defined(dbPostgres)
|
||||
@@ -53,6 +59,16 @@ badgeServiceTests = do
|
||||
it "should fill total for every seeded offer" testBadgeCatalogTotalsFillsSeededOffers
|
||||
it "should reject an offer with freeMonths >= months instead of wrapping" testBadgeCatalogOfferTotalRejectsBadFreeMonths
|
||||
it "should encode BadgeItemStatus on the wire as active/deprecated/disabled" testBadgeItemStatusJsonWireFormat
|
||||
it "should fail to start on a missing config file, naming the file" testBadgeServiceConfigMissingFile
|
||||
it "should fail to start on an unparsable value, naming the key" testBadgeServiceConfigUnparsableValue
|
||||
it "should fail to start on an unknown key in a known section" testBadgeServiceConfigUnknownKey
|
||||
it "should fail to start on a missing [issuer] section" testBadgeServiceConfigMissingIssuerSection
|
||||
it "should fail to start on a missing [codes] section" testBadgeServiceConfigMissingCodesSection
|
||||
it "should fail to start on a half-configured [btcpay] section" testBadgeServiceConfigHalfConfiguredBtcPay
|
||||
it "should fail to start on a half-configured [stripe] section" testBadgeServiceConfigHalfConfiguredStripe
|
||||
it "should fail to start when a provider is configured without [web]" testBadgeServiceConfigProviderRequiresWeb
|
||||
it "should start with just [issuer] and [codes], no provider section" testBadgeServiceConfigMinimalStarts
|
||||
it "should start the service from a complete config with web and both providers" testBadgeServiceCompleteConfigStarts
|
||||
|
||||
badgeProfile :: Profile
|
||||
badgeProfile = Profile {displayName = "SimpleX Badges", fullName = "", shortDescr = Nothing, description = Nothing, image = Nothing, contactLink = Nothing, peerType = Just CPTBot, preferences = Nothing, badge = Nothing, contactDomain = Nothing}
|
||||
@@ -77,12 +93,56 @@ mkBadgeServiceOpts TestParams {tmpPath = ps} =
|
||||
clientService = True,
|
||||
noAddress = False,
|
||||
runCLI = False,
|
||||
testing = True
|
||||
testing = True,
|
||||
configFile = badgeServiceConfigPath ps
|
||||
}
|
||||
|
||||
badgeServiceConfigPath :: FilePath -> FilePath
|
||||
badgeServiceConfigPath tmpPath = tmpPath </> "badge_service.ini"
|
||||
|
||||
-- Generates a real issuer key file (the two-line `badge keygen` output: "secret ..\npublic
|
||||
-- ..") and a real 32-byte code secret (base64-encoded), at fixed names under tmpPath. A6
|
||||
-- doesn't read either file's contents -- that's B3 and B4 -- but the harness must still hand
|
||||
-- every later step real files at real paths, per the config keys naming secrets as files.
|
||||
writeTestBadgeServiceSecrets :: FilePath -> IO (FilePath, FilePath)
|
||||
writeTestBadgeServiceSecrets tmpPath = do
|
||||
let issuerKeyFile = tmpPath </> "badge-issuer.keys"
|
||||
codeSecretFile = tmpPath </> "badge-code.secret"
|
||||
Right (BBSPublicKey pk, BBSSecretKey sk) <- bbsKeyGen
|
||||
writeFile issuerKeyFile $ "secret " <> BC.unpack (strEncode sk) <> "\npublic " <> BC.unpack (strEncode pk) <> "\n"
|
||||
codeSecret <- getRandomBytes 32
|
||||
writeFile codeSecretFile $ BC.unpack (B64.encode codeSecret) <> "\n"
|
||||
pure (issuerKeyFile, codeSecretFile)
|
||||
|
||||
issuerCodesIniLines :: FilePath -> FilePath -> [String]
|
||||
issuerCodesIniLines issuerKeyFile codeSecretFile =
|
||||
[ "[issuer]",
|
||||
"key_file = " <> issuerKeyFile,
|
||||
"key_idx = 1",
|
||||
"",
|
||||
"[codes]",
|
||||
"secret_file = " <> codeSecretFile,
|
||||
"default_expiry_days = 365"
|
||||
]
|
||||
|
||||
-- Writes a complete but minimal badge_service.ini (required sections only, no provider
|
||||
-- section) at the path mkBadgeServiceOpts points BadgeServiceOpts's configFile at. Provider
|
||||
-- sections are omitted until E2 and F1 add them.
|
||||
writeTestBadgeServiceConfig :: TestParams -> IO ()
|
||||
writeTestBadgeServiceConfig TestParams {tmpPath} = do
|
||||
(issuerKeyFile, codeSecretFile) <- writeTestBadgeServiceSecrets tmpPath
|
||||
writeFile (badgeServiceConfigPath tmpPath) $ unlines (issuerCodesIniLines issuerKeyFile codeSecretFile)
|
||||
|
||||
withBadgeService :: HasCallStack => TestParams -> (TestCC -> String -> IO ()) -> IO ()
|
||||
withBadgeService ps test = do
|
||||
withBadgeService ps = withBadgeServiceConfig ps (writeTestBadgeServiceConfig ps)
|
||||
|
||||
-- Shared by withBadgeService and testBadgeServiceCompleteConfigStarts: the two-phase startup
|
||||
-- dance (CreateMyAddress, then ShowMyAddress) is the same regardless of what the config looks
|
||||
-- like, as long as it's valid; writeConfig is what varies.
|
||||
withBadgeServiceConfig :: HasCallStack => TestParams -> IO () -> (TestCC -> String -> IO ()) -> IO ()
|
||||
withBadgeServiceConfig ps writeConfig test = do
|
||||
let opts = mkBadgeServiceOpts ps
|
||||
writeConfig
|
||||
withNewTestChatCfg ps testCfg serviceDbPrefix badgeProfile $ \_ -> pure ()
|
||||
-- First start: badge service takes the CreateMyAddress branch.
|
||||
runBadgeService testCfg opts (pure ())
|
||||
@@ -233,6 +293,173 @@ testBadgeItemStatusJsonWireFormat _ps = do
|
||||
J.encode BISDeprecated `shouldBe` "\"deprecated\""
|
||||
J.encode BISDisabled `shouldBe` "\"disabled\""
|
||||
|
||||
testBadgeServiceConfigMissingFile :: HasCallStack => TestParams -> IO ()
|
||||
testBadgeServiceConfigMissingFile TestParams {tmpPath} = do
|
||||
let path = tmpPath </> "missing.ini"
|
||||
Left err <- readBadgeServiceConfig path
|
||||
err `shouldSatisfy` (path `isInfixOf`)
|
||||
|
||||
testBadgeServiceConfigUnparsableValue :: HasCallStack => TestParams -> IO ()
|
||||
testBadgeServiceConfigUnparsableValue TestParams {tmpPath} = do
|
||||
(issuerKeyFile, codeSecretFile) <- writeTestBadgeServiceSecrets tmpPath
|
||||
let path = tmpPath </> "unparsable.ini"
|
||||
writeFile path $
|
||||
unlines
|
||||
[ "[issuer]",
|
||||
"key_file = " <> issuerKeyFile,
|
||||
"key_idx = not-a-number",
|
||||
"",
|
||||
"[codes]",
|
||||
"secret_file = " <> codeSecretFile,
|
||||
"default_expiry_days = 365"
|
||||
]
|
||||
Left err <- readBadgeServiceConfig path
|
||||
err `shouldSatisfy` ("key_idx" `isInfixOf`)
|
||||
|
||||
testBadgeServiceConfigUnknownKey :: HasCallStack => TestParams -> IO ()
|
||||
testBadgeServiceConfigUnknownKey TestParams {tmpPath} = do
|
||||
(issuerKeyFile, codeSecretFile) <- writeTestBadgeServiceSecrets tmpPath
|
||||
let path = tmpPath </> "unknown-key.ini"
|
||||
writeFile path $
|
||||
unlines $
|
||||
issuerCodesIniLines issuerKeyFile codeSecretFile
|
||||
++ [ "",
|
||||
"[web]",
|
||||
"port = 8080",
|
||||
"base_url = https://badges.example.org",
|
||||
"support_contact = https://simplex.chat/contact",
|
||||
"bogus_key = 1"
|
||||
]
|
||||
Left err <- readBadgeServiceConfig path
|
||||
err `shouldSatisfy` ("bogus_key" `isInfixOf`)
|
||||
|
||||
testBadgeServiceConfigMissingIssuerSection :: HasCallStack => TestParams -> IO ()
|
||||
testBadgeServiceConfigMissingIssuerSection TestParams {tmpPath} = do
|
||||
(_issuerKeyFile, codeSecretFile) <- writeTestBadgeServiceSecrets tmpPath
|
||||
let path = tmpPath </> "no-issuer.ini"
|
||||
writeFile path $ unlines ["[codes]", "secret_file = " <> codeSecretFile, "default_expiry_days = 365"]
|
||||
Left err <- readBadgeServiceConfig path
|
||||
err `shouldSatisfy` ("[issuer]" `isInfixOf`)
|
||||
|
||||
testBadgeServiceConfigMissingCodesSection :: HasCallStack => TestParams -> IO ()
|
||||
testBadgeServiceConfigMissingCodesSection TestParams {tmpPath} = do
|
||||
(issuerKeyFile, _codeSecretFile) <- writeTestBadgeServiceSecrets tmpPath
|
||||
let path = tmpPath </> "no-codes.ini"
|
||||
writeFile path $ unlines ["[issuer]", "key_file = " <> issuerKeyFile, "key_idx = 1"]
|
||||
Left err <- readBadgeServiceConfig path
|
||||
err `shouldSatisfy` ("[codes]" `isInfixOf`)
|
||||
|
||||
testBadgeServiceConfigHalfConfiguredBtcPay :: HasCallStack => TestParams -> IO ()
|
||||
testBadgeServiceConfigHalfConfiguredBtcPay TestParams {tmpPath} = do
|
||||
(issuerKeyFile, codeSecretFile) <- writeTestBadgeServiceSecrets tmpPath
|
||||
let path = tmpPath </> "half-btcpay.ini"
|
||||
writeFile path $
|
||||
unlines $
|
||||
issuerCodesIniLines issuerKeyFile codeSecretFile
|
||||
++ [ "",
|
||||
"[web]",
|
||||
"port = 8080",
|
||||
"base_url = https://badges.example.org",
|
||||
"support_contact = https://simplex.chat/contact",
|
||||
"",
|
||||
"[btcpay]",
|
||||
"url = https://btcpay.example.org",
|
||||
"store_id = teststore"
|
||||
]
|
||||
Left err <- readBadgeServiceConfig path
|
||||
err `shouldSatisfy` ("btcpay" `isInfixOf`)
|
||||
|
||||
testBadgeServiceConfigHalfConfiguredStripe :: HasCallStack => TestParams -> IO ()
|
||||
testBadgeServiceConfigHalfConfiguredStripe TestParams {tmpPath} = do
|
||||
(issuerKeyFile, codeSecretFile) <- writeTestBadgeServiceSecrets tmpPath
|
||||
let stripeKeyFile = tmpPath </> "stripe.key"
|
||||
path = tmpPath </> "half-stripe.ini"
|
||||
writeFile path $
|
||||
unlines $
|
||||
issuerCodesIniLines issuerKeyFile codeSecretFile
|
||||
++ [ "",
|
||||
"[web]",
|
||||
"port = 8080",
|
||||
"base_url = https://badges.example.org",
|
||||
"support_contact = https://simplex.chat/contact",
|
||||
"",
|
||||
"[stripe]",
|
||||
"secret_key_file = " <> stripeKeyFile
|
||||
]
|
||||
Left err <- readBadgeServiceConfig path
|
||||
err `shouldSatisfy` ("stripe" `isInfixOf`)
|
||||
|
||||
testBadgeServiceConfigProviderRequiresWeb :: HasCallStack => TestParams -> IO ()
|
||||
testBadgeServiceConfigProviderRequiresWeb TestParams {tmpPath} = do
|
||||
(issuerKeyFile, codeSecretFile) <- writeTestBadgeServiceSecrets tmpPath
|
||||
let apiKeyFile = tmpPath </> "btcpay-api.key"
|
||||
webhookFile = tmpPath </> "btcpay-webhook.secret"
|
||||
path = tmpPath </> "provider-no-web.ini"
|
||||
writeFile apiKeyFile "api-key\n"
|
||||
writeFile webhookFile "webhook-secret\n"
|
||||
writeFile path $
|
||||
unlines $
|
||||
issuerCodesIniLines issuerKeyFile codeSecretFile
|
||||
++ [ "",
|
||||
"[btcpay]",
|
||||
"url = https://btcpay.example.org",
|
||||
"store_id = teststore",
|
||||
"api_key_file = " <> apiKeyFile,
|
||||
"webhook_secret_file = " <> webhookFile
|
||||
]
|
||||
Left err <- readBadgeServiceConfig path
|
||||
err `shouldSatisfy` ("[web]" `isInfixOf`)
|
||||
|
||||
testBadgeServiceConfigMinimalStarts :: HasCallStack => TestParams -> IO ()
|
||||
testBadgeServiceConfigMinimalStarts TestParams {tmpPath} = do
|
||||
(issuerKeyFile, codeSecretFile) <- writeTestBadgeServiceSecrets tmpPath
|
||||
let path = tmpPath </> "minimal.ini"
|
||||
writeFile path $ unlines (issuerCodesIniLines issuerKeyFile codeSecretFile)
|
||||
result <- readBadgeServiceConfig path
|
||||
case result of
|
||||
Right BadgeServiceConfig {web} -> web `shouldBe` Nothing
|
||||
Left err -> expectationFailure $ "expected a minimal config to parse, got: " <> err
|
||||
|
||||
-- Proves a fully populated ini -- issuer, codes, web and both providers -- starts the real
|
||||
-- service end to end, not just that readBadgeServiceConfig accepts it.
|
||||
testBadgeServiceCompleteConfigStarts :: HasCallStack => TestParams -> IO ()
|
||||
testBadgeServiceCompleteConfigStarts ps@TestParams {tmpPath} =
|
||||
withBadgeServiceConfig ps writeCompleteConfig $ \client bsLink -> do
|
||||
let redeemReq =
|
||||
"{\"version\":1,\"request\":{\"type\":\"purchaseBadge\",\"payment\":{\"type\":\"code\",\"code\":\"TEST-CODE\"}}}"
|
||||
client ##> ("/_service_request 1 " <> bsLink <> " " <> redeemReq)
|
||||
client <## "service response: {\"code\":\"unsupported_version\",\"type\":\"error\"}"
|
||||
where
|
||||
writeCompleteConfig = do
|
||||
(issuerKeyFile, codeSecretFile) <- writeTestBadgeServiceSecrets tmpPath
|
||||
let apiKeyFile = tmpPath </> "btcpay-api.key"
|
||||
btcWebhookFile = tmpPath </> "btcpay-webhook.secret"
|
||||
stripeKeyFile = tmpPath </> "stripe.key"
|
||||
stripeWebhookFile = tmpPath </> "stripe-webhook.secret"
|
||||
writeFile apiKeyFile "btcpay-api-key\n"
|
||||
writeFile btcWebhookFile "btcpay-webhook-secret\n"
|
||||
writeFile stripeKeyFile "sk_test_123\n"
|
||||
writeFile stripeWebhookFile "whsec_test_123\n"
|
||||
writeFile (badgeServiceConfigPath tmpPath) $
|
||||
unlines $
|
||||
issuerCodesIniLines issuerKeyFile codeSecretFile
|
||||
++ [ "",
|
||||
"[web]",
|
||||
"port = 0",
|
||||
"base_url = https://badges.example.org",
|
||||
"support_contact = https://simplex.chat/contact",
|
||||
"",
|
||||
"[btcpay]",
|
||||
"url = https://btcpay.example.org",
|
||||
"store_id = teststore",
|
||||
"api_key_file = " <> apiKeyFile,
|
||||
"webhook_secret_file = " <> btcWebhookFile,
|
||||
"",
|
||||
"[stripe]",
|
||||
"secret_key_file = " <> stripeKeyFile,
|
||||
"webhook_secret_file = " <> stripeWebhookFile
|
||||
]
|
||||
|
||||
#if defined(dbPostgres)
|
||||
runMigrationsToRun :: DBStore -> MigrationsToRun -> IO ()
|
||||
runMigrationsToRun st = Migrations.run st Nothing
|
||||
|
||||
Reference in new issue
Block a user