Feature/pre 3440 multi shop configuration - #331
adumont-payplug wants to merge 13 commits into
Conversation
- de-dup CB base-currency form errors, not just flashes - flash() no longer throws with no request/session - drop 8 dead gatewayFactoryName property declarations - suppress PHPMD unused-param on shouldValidateBaseCurrency() - assert PaymentMethodTypeExtension::getExtendedTypes() - tighten PaymentMethodRepository docblocks to list<>
There was a problem hiding this comment.
Review pass on the full diff
Reviewed in five passes: form/validation (PRE-3628/3629), credential scoping (PRE-3682/3683/3685), auth controllers + extractor + revoker (PRE-3631/3632), tests, config/translations. Full PHPUnit suite run under PHP 8.2: 589 tests, green.
What holds up
Several of the load-bearing claims in the description were checked against vendor source rather than taken on trust, and all of them hold:
- The wither immutability is watertight.
SyliusUpcConfigurationRepositoryusesclone $thisand assigns on the clone; nothing mutates$this. Every consumer insrc/scopes before use — there is no unscopedconfigurationRepository->call left. The cross-tenant leakage failure mode during IPN is closed. - The token-cache purge is correct, which is easy to get wrong:
TOKEN_CACHE_KEY_PREFIXmatches UPC'sTokenManagerexactly, and both the revoker andTokenManagergo through the same sharedSyliusTokenCache, so PSR-6 key sanitization is symmetric on write and delete.GatewayConnectionRevokerTestexercising a real cache over anArrayAdapterinstead of mockingITokenCacheis the right call. - The
@?CSRF argument is sound. Sylius' ownCsrfProtectionEnabledExtension::isCsrfProtectionEnabled()is literally$this->container->has('security.csrf.token_manager')— the template gate and the controller null check are the same condition, so there is no window where the link omits a token the controller then demands. The route also sits behind/admin, so the token is defence-in-depth, not the only authorization. IdTokenEmailExtractoris genuinely total. Every branch checked:json_decodewithoutJSON_THROW_ON_ERRORreturnsnullfor non-UTF8 and for depth > 512; a segment length ≡ 1 mod 4 produces a padbase64_decode(..., true)rejects;filter_varnever throws.- Errors added to
channelsdo not bubble to the root (ChoiceTypesetserror_bubbling => falseon the type itself), andForm::add()insidePOST_SET_DATAdoes re-map data into the replaced child (lockSetDatais only on duringPRE_SET_DATA). Both docblock claims are accurate. GatewayChannelConflictCheckeris the strongest piece here. The asymmetry betweenfindConflicts()(bails on a disabled subject) andfindClaimedChannels()(unconditional, minus the subject's own channels) is non-obvious and correct.SupportedMethodsProvideris a real bug fix on its own — the old??=let the first method's/accountpayload govern every later one in the list.
Two findings with no file in the diff
Three factory-name credential lookups the description does not list as remaining gaps. The breaking-change section says the only open half of PRE-3682 is client.xml's singletons. It isn't:
src/Provider/OneySupportedPaymentChoiceProvider.php:42—findOneByGatewayName(OneyGatewayFactory::FACTORY_NAME)src/Provider/Payment/ApplePayPaymentProvider.php:52and:209— same, for Apple Paysrc/Twig/OneyExtension.php:35—findOneBy(['factoryName' => OneyGatewayFactory::FACTORY_NAME])
findOneByGatewayName() is setMaxResults(1)->getSingleResult(), so with two Oney or two Apple Pay gateways it returns an arbitrary one — the exact bug this PR exists to kill, in shop-facing code (Apple Pay merchant-session/domain validation, Oney simulation display). Not necessarily in scope to fix here, but they should be listed and ticketed. Separately: that method is typed ?PaymentMethodInterface but getSingleResult() throws NoResultException rather than returning null — pre-existing.
No CHANGELOG.md / UPGRADE.md entry. There is an eight-row breaking-change table for anyone extending the plugin — dropped constructor arguments, changed interface signatures, a removed translation key, protected → public hooks. CHANGELOG.md has a live ## [2.0.0] - Unreleased section and neither file was touched. Integrators will not read a PR body.
Assessment
Ready to merge: with fixes. The credential-scoping architecture is sound and the immutability, cache-key and form-mechanics claims all check out. One critical issue (see the IntegratedPaymentController thread) turns a previously dormant assumption into an exploitable one, and the form layer that enforces the new per-channel rule traded its only real-form test for an all-mock one.
On the plan itself: the four pre-justified tradeoffs — GET + query-string CSRF, unsigned id_token parsing, leaving already-held channels selectable, the wither-based scoped repository — all survive scrutiny, and in three cases the reasoning is more careful than the summary lets on. Where the plan under-reaches is that it treats "thread the PaymentMethodInterface through" as sufficient without asking where that PaymentMethodInterface comes from. IntegratedPaymentController is where that omission bites.
There was a problem hiding this comment.
Claude Code Review
Claude Code Review is paused for this repository. To reconnect it, an admin of this repository's GitHub organization (or the account owner, for personal repositories) who can also manage your Claude organization's Code Review settings needs to re-link GitHub in Code Review settings. This is a one-time step.
Tip: disable this comment in your organization's Code Review settings.
5e10bf7 to
2aecfe0
Compare
Description
Multi-shop support: a Sylius installation can now hold several PayPlug gateway configurations of the same type, each connected to its own PayPlug account and scoped to its own set of channels.
Until now the plugin assumed one PayPlug account per installation.
AbstractGatewayConfigurationTyperefused the creation of a second gateway config for a factory name that already existed, and everything downstream — the API client, the/accountpayload, the UPC configuration repository — resolved credentials by factory name alone. That is fine with one account, and silently wrong with several: a name-based lookup returns an arbitrary config, so a request for channel A can be signed with channel B's credentials.This PR replaces the installation-wide uniqueness rule with a per-channel one, then threads the payment method (rather than the factory name) through every place that needs to know which account it is talking to, and gives the admin the two things that become necessary once several accounts coexist: seeing which account a gateway is connected to, and disconnecting one of them without touching the others.
Motivation: merchants running several shops on one Sylius installation need one PayPlug account per channel.
Related issue(s): PRE-3440 — includes PRE-3628, PRE-3629, PRE-3631, PRE-3632, PRE-3682, PRE-3683, PRE-3685.
PRE-3628 — per-channel gateway uniqueness
The rule is now: a channel may be linked to at most one enabled gateway config per factory type. Two CB gateways may coexist and both be enabled as long as their channel sets are disjoint; different factory types never conflict.
Checker/GatewayChannelConflictChecker— matches on channel code rather than object identity, ignores disabled gateways on both sides, and handles the not-yet-persisted subject (no id ⇒ can never match a rival).Gateway/Form/Extension/PaymentMethodTypeExtension— carries both the conflict rule and the base-currency rule on the root payment-method form. That move is the crux: Sylius addschannelsfromCoreBundle's own type extension, i.e. aftergatewayConfig, so a listener insidegatewayConfig.configruns beforeenabledandchannelsare submitted and can only ever see persisted data. RootPOST_SUBMITis the first point where the submitted channel set, the submittedenabledflag and the mapped gateway config all exist.AbstractGatewayConfigurationTypeloses itsPRE_SUBMITlistener, thecanBeCreated()/checkCreationRequirements()pair and two constructor dependencies; the per-gateway currency policy stays where it belongs (one hook per gateway type) and is read back by the extension.PayPlugGatewayFactory::resolveDisplayMode()instead of the unmappedDISPLAY_MODE_FIELDform key, which never reaches the persisted config.PaymentMethodRepository::findEnabledByGatewayName().form.only_one_gateway_allowed→form.gateway_channel_conflict(en/fr/it).PRE-3629 — claimed channels are unselectable in the picker
POST_SET_DATAon the root form replaces thechannelschild with a copy carrying achoice_attrclosure, so a channel already held by another enabled gateway of the same factory rendersdisabledwith atitlenaming the claiming payment method.Channels the edited payment method already holds are deliberately left selectable: browsers do not submit disabled checkboxes, so disabling a checked one would silently drop that channel on save. Pre-existing overlaps are reported by the submit-time rule instead. Both answers come from the same
claims()lookup, which is what keeps the picker and the validator in step.PRE-3682 / PRE-3683 / PRE-3685 — scoping credentials to the payment method
PayPlugApiClientFactoryInterface::create(string $factoryName)is removed from the interface.createForPaymentMethod()is now the only way application code can obtain a client — the compiler, not review, is the guard against reintroducing a channel-ambiguous lookup. The concretecreate()survives as@internalpurely for theclient.xmlservice-factory definitions (the remaining open half of PRE-3682, tracked separately).SupportedMethodsProviderfetches/accountper gateway config, memoized by persisted id (falling back tospl_object_idfor unflushed configs) instead of once per call — previously the first method's account governed every later one in the list. Thepayment_methodssub-key is resolved from the config the payload was fetched for.Upc/ScopedConfigurationRepositoryInterface— UPC'sIConfigurationRepositorytakes no context on any method (it was written for one account per installation). Rather than widen a shared contract that other plugins consume, the scope is carried Sylius-side by a sub-interface withwithGatewayConfig()/forPaymentMethod()withers: the repository is a shared service, and a mutable scope would leak across requests — IPN and background token refresh being exactly where that would go unnoticed.UnifiedApiPaymentCreatorInterface::createPayment(),OperationStatusFetcherInterface::getOperation(), the UHF command handlers,HostedFieldsWebhookNotificationHandler,IpnAction,OneClickAction,IntegratedPaymentController,PaymentStateResolver,CaptureAuthorizedPaymentProcessorand the Oney/permission validators all take or resolve the payment method now.PRE-3631 — the connected account, per gateway
New
Auth/IdTokenEmailExtractorreads theemailclaim out of the OAuthid_tokenat callback time andUnifiedAuthenticationControllerwrites it to the gateway config asaccount_email; a read-onlyconnected_account.html.twigrenders it on the update screen of all seven gateways.Worth knowing:
/accountcarries no email (verified live — the payload isid,company_ref,country,object,is_live,configuration,permissions,payment_methods), and neither does the client-credentials token used for background calls. The interactive authorization-code exchange is the only place the address exists, which is why it is captured at login rather than fetched on demand — same approach as the PrestaShop module. The extractor is total (any malformed input returnsnull) and deliberately does not verify the signature: the token arrives as the direct response body of a server-to-server POST, never via the browser, and the claim is display text, not an authorization decision. A gateway connected before this change shows the "re-authenticate" placeholder until the merchant reconnects.Requires
payplug/unified-plugin-core ^1.1.2, whereTokenOutputgained a nullableidToken— earlier versions dropid_tokenfrom the token response entirely. Constraint bumped accordingly.PRE-3632 — disconnect one gateway
New
UnifiedLogoutController+Auth/GatewayConnectionRevoker— the inverse of the OAuth callback, scoped to a single gateway config. It clearslive_client,test_clientandaccount_email, drops both cached UPC tokens, and disables the payment method.hfIdentifieris cleared only when the config is a CB gateway with Hosted Fields selected; elsewhere it is a merchant-typed value, not account-bound state.live,oneClick,deferredCapture, the display-mode flags andfees_forare untouched.renew_oauthcheckbox, which immediately mints new credentials — logout ends with none.PaymentMethodValidator::process()only ever disables, the merchant must re-tick "Enabled" by hand after reconnecting.GET, notPOST: the button is rendered inside the Sylius payment-method<form>, where a nested<form>would be invalid HTML. The CSRF token travels in the query string, the same shape as Sylius's ownsylius_admin_shipment_resend_confirmation_email.security.csrf.token_manageris injected with@?— it is absent when CSRF protection is off, and a hard reference would break container compilation for such an app.Type of Change
Breaking changes for anyone extending the plugin
PayPlugApiClientFactoryInterface::create(string $factoryName)createForPaymentMethod(PaymentMethodInterface $pm)UnifiedApiPaymentCreatorInterface::createPayment($dto)createPayment($dto, PaymentMethodInterface $method)OperationStatusFetcherInterface::getOperation($id)getOperation($id, PaymentMethodInterface $method)AbstractGatewayConfigurationType::__construct()—$gatewayConfigRepositoryand$requestStackdroppedshouldValidateBaseCurrency()/baseCurrencyViolationMessage()—protected→public, now take the mapped config$gatewayFactoryNameproperty on the 8 configuration typesform.only_one_gateway_allowedform.gateway_channel_conflict(%channel%,%payment_method%)PayplugUnifiedCore\Contracts\IConfigurationRepositoryScopedConfigurationRepositoryInterface, scoped per payment methodChecklist
Code Quality
Testing
New suites:
GatewayChannelConflictCheckerTest,PaymentMethodTypeExtensionTest,IdTokenEmailExtractorTest,GatewayConnectionRevokerTest,UnifiedLogoutControllerTest,IntegratedPaymentControllerTest, plus scoping coverage added to the UPC, API-client-factory andSupportedMethodsProvidertests.Security & Ops
Manual test plan
channelsfield.SupportedMethodsProvideramount limits and allowed countries follow the right account too).