Merge pull request #2491 from woocommerce/use-client-credentials-for-user-tokens

Use client credentials for user tokens (3518)
This commit is contained in:
Emili Castells 2024-08-07 13:55:32 +02:00 committed by GitHub
commit ff4cd0c9a4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 211 additions and 81 deletions

View file

@ -9,6 +9,7 @@ declare(strict_types=1);
namespace WooCommerce\PayPalCommerce\ApiClient;
use WooCommerce\PayPalCommerce\ApiClient\Authentication\ClientCredentials;
use WooCommerce\PayPalCommerce\ApiClient\Authentication\SdkClientToken;
use WooCommerce\PayPalCommerce\ApiClient\Authentication\UserIdToken;
use WooCommerce\PayPalCommerce\ApiClient\Endpoint\PaymentMethodTokensEndpoint;
@ -1656,18 +1657,28 @@ return array(
return new PurchaseUnitSanitizer( $behavior, $line_name );
}
),
'api.client-credentials' => static function( ContainerInterface $container ): ClientCredentials {
return new ClientCredentials(
$container->get( 'wcgateway.settings' )
);
},
'api.client-credentials-cache' => static function( ContainerInterface $container ): Cache {
return new Cache( 'ppcp-client-credentials-cache' );
},
'api.user-id-token' => static function( ContainerInterface $container ): UserIdToken {
return new UserIdToken(
$container->get( 'api.host' ),
$container->get( 'api.bearer' ),
$container->get( 'woocommerce.logger.woocommerce' )
$container->get( 'woocommerce.logger.woocommerce' ),
$container->get( 'api.client-credentials' ),
$container->get( 'api.client-credentials-cache' )
);
},
'api.sdk-client-token' => static function( ContainerInterface $container ): SdkClientToken {
return new SdkClientToken(
$container->get( 'api.host' ),
$container->get( 'api.bearer' ),
$container->get( 'woocommerce.logger.woocommerce' )
$container->get( 'woocommerce.logger.woocommerce' ),
$container->get( 'api.client-credentials' ),
$container->get( 'api.client-credentials-cache' )
);
},
);

View file

@ -10,6 +10,8 @@ declare(strict_types=1);
namespace WooCommerce\PayPalCommerce\ApiClient;
use WC_Order;
use WooCommerce\PayPalCommerce\ApiClient\Authentication\UserIdToken;
use WooCommerce\PayPalCommerce\ApiClient\Helper\Cache;
use WooCommerce\PayPalCommerce\ApiClient\Helper\FailureRegistry;
use WooCommerce\PayPalCommerce\ApiClient\Helper\OrderTransient;
use WooCommerce\PayPalCommerce\Vendor\Dhii\Container\ServiceProvider;
@ -94,6 +96,18 @@ class ApiModule implements ModuleInterface {
10,
2
);
add_action(
'wp_logout',
function( int $user_id ) use ( $c ) {
$client_credentials_cache = $c->get( 'api.client-credentials-cache' );
assert( $client_credentials_cache instanceof Cache );
if ( $client_credentials_cache->has( UserIdToken::CACHE_KEY . '-' . (string) $user_id ) ) {
$client_credentials_cache->delete( UserIdToken::CACHE_KEY . '-' . (string) $user_id );
}
}
);
}
/**

View file

@ -0,0 +1,49 @@
<?php
/**
* The client credentials.
*
* @package WooCommerce\PayPalCommerce\ApiClient\Authentication
*/
declare(strict_types=1);
namespace WooCommerce\PayPalCommerce\ApiClient\Authentication;
use WooCommerce\PayPalCommerce\WcGateway\Settings\Settings;
use WooCommerce\PayPalCommerce\WcGateway\Exception\NotFoundException;
/**
* Class ClientCredentials
*/
class ClientCredentials {
/**
* The settings.
*
* @var Settings
*/
protected $settings;
/**
* ClientCredentials constructor.
*
* @param Settings $settings The settings.
*/
public function __construct( Settings $settings ) {
$this->settings = $settings;
}
/**
* Returns encoded client credentials.
*
* @return string
* @throws NotFoundException If setting does not found.
*/
public function credentials(): string {
$client_id = $this->settings->has( 'client_id' ) ? $this->settings->get( 'client_id' ) : '';
$client_secret = $this->settings->has( 'client_secret' ) ? $this->settings->get( 'client_secret' ) : '';
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
return 'Basic ' . base64_encode( $client_id . ':' . $client_secret );
}
}

View file

@ -11,6 +11,7 @@ use Psr\Log\LoggerInterface;
use WooCommerce\PayPalCommerce\ApiClient\Endpoint\RequestTrait;
use WooCommerce\PayPalCommerce\ApiClient\Exception\PayPalApiException;
use WooCommerce\PayPalCommerce\ApiClient\Exception\RuntimeException;
use WooCommerce\PayPalCommerce\ApiClient\Helper\Cache;
use WP_Error;
/**
@ -20,6 +21,8 @@ class SdkClientToken {
use RequestTrait;
const CACHE_KEY = 'sdk-client-token-key';
/**
* The host.
*
@ -27,13 +30,6 @@ class SdkClientToken {
*/
private $host;
/**
* The bearer.
*
* @var Bearer
*/
private $bearer;
/**
* The logger.
*
@ -41,35 +37,52 @@ class SdkClientToken {
*/
private $logger;
/**
* The client credentials.
*
* @var ClientCredentials
*/
private $client_credentials;
/**
* The cache.
*
* @var Cache
*/
private $cache;
/**
* SdkClientToken constructor.
*
* @param string $host The host.
* @param Bearer $bearer The bearer.
* @param LoggerInterface $logger The logger.
* @param string $host The host.
* @param LoggerInterface $logger The logger.
* @param ClientCredentials $client_credentials The client credentials.
* @param Cache $cache The cache.
*/
public function __construct(
string $host,
Bearer $bearer,
LoggerInterface $logger
LoggerInterface $logger,
ClientCredentials $client_credentials,
Cache $cache
) {
$this->host = $host;
$this->bearer = $bearer;
$this->logger = $logger;
$this->host = $host;
$this->logger = $logger;
$this->client_credentials = $client_credentials;
$this->cache = $cache;
}
/**
* Returns `sdk_client_token` which uniquely identifies the payer.
*
* @param string $target_customer_id Vaulted customer id.
* Returns the client token for SDK `data-sdk-client-token`.
*
* @return string
*
* @throws PayPalApiException If the request fails.
* @throws RuntimeException If something unexpected happens.
*/
public function sdk_client_token( string $target_customer_id = '' ): string {
$bearer = $this->bearer->bearer();
public function sdk_client_token(): string {
if ( $this->cache->has( self::CACHE_KEY ) ) {
return $this->cache->get( self::CACHE_KEY );
}
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$domain = wp_unslash( $_SERVER['HTTP_HOST'] ?? '' );
@ -77,19 +90,10 @@ class SdkClientToken {
$url = trailingslashit( $this->host ) . 'v1/oauth2/token?grant_type=client_credentials&response_type=client_token&intent=sdk_init&domains[]=' . $domain;
if ( $target_customer_id ) {
$url = add_query_arg(
array(
'target_customer_id' => $target_customer_id,
),
$url
);
}
$args = array(
'method' => 'POST',
'headers' => array(
'Authorization' => 'Bearer ' . $bearer->token(),
'Authorization' => $this->client_credentials->credentials(),
'Content-Type' => 'application/x-www-form-urlencoded',
),
);
@ -105,6 +109,11 @@ class SdkClientToken {
throw new PayPalApiException( $json, $status_code );
}
return $json->access_token;
$access_token = $json->access_token;
$expires_in = (int) $json->expires_in;
$this->cache->set( self::CACHE_KEY, $access_token, $expires_in );
return $access_token;
}
}

View file

@ -11,6 +11,7 @@ use Psr\Log\LoggerInterface;
use WooCommerce\PayPalCommerce\ApiClient\Endpoint\RequestTrait;
use WooCommerce\PayPalCommerce\ApiClient\Exception\PayPalApiException;
use WooCommerce\PayPalCommerce\ApiClient\Exception\RuntimeException;
use WooCommerce\PayPalCommerce\ApiClient\Helper\Cache;
use WP_Error;
/**
@ -20,6 +21,8 @@ class UserIdToken {
use RequestTrait;
const CACHE_KEY = 'user-id-token-key';
/**
* The host.
*
@ -27,13 +30,6 @@ class UserIdToken {
*/
private $host;
/**
* The bearer.
*
* @var Bearer
*/
private $bearer;
/**
* The logger.
*
@ -41,21 +37,38 @@ class UserIdToken {
*/
private $logger;
/**
* The client credentials.
*
* @var ClientCredentials
*/
private $client_credentials;
/**
* The cache.
*
* @var Cache
*/
private $cache;
/**
* UserIdToken constructor.
*
* @param string $host The host.
* @param Bearer $bearer The bearer.
* @param LoggerInterface $logger The logger.
* @param string $host The host.
* @param LoggerInterface $logger The logger.
* @param ClientCredentials $client_credentials The client credentials.
* @param Cache $cache The cache.
*/
public function __construct(
string $host,
Bearer $bearer,
LoggerInterface $logger
LoggerInterface $logger,
ClientCredentials $client_credentials,
Cache $cache
) {
$this->host = $host;
$this->bearer = $bearer;
$this->logger = $logger;
$this->host = $host;
$this->logger = $logger;
$this->client_credentials = $client_credentials;
$this->cache = $cache;
}
/**
@ -69,7 +82,9 @@ class UserIdToken {
* @throws RuntimeException If something unexpected happens.
*/
public function id_token( string $target_customer_id = '' ): string {
$bearer = $this->bearer->bearer();
if ( $this->cache->has( self::CACHE_KEY . '-' . (string) get_current_user_id() ) ) {
return $this->cache->get( self::CACHE_KEY . '-' . (string) get_current_user_id() );
}
$url = trailingslashit( $this->host ) . 'v1/oauth2/token?grant_type=client_credentials&response_type=id_token';
if ( $target_customer_id ) {
@ -84,7 +99,7 @@ class UserIdToken {
$args = array(
'method' => 'POST',
'headers' => array(
'Authorization' => 'Bearer ' . $bearer->token(),
'Authorization' => $this->client_credentials->credentials(),
'Content-Type' => 'application/x-www-form-urlencoded',
),
);
@ -100,6 +115,11 @@ class UserIdToken {
throw new PayPalApiException( $json, $status_code );
}
return $json->id_token;
$id_token = $json->id_token;
$expires_in = (int) $json->expires_in;
$this->cache->set( self::CACHE_KEY . '-' . (string) get_current_user_id(), $id_token, $expires_in );
return $id_token;
}
}

View file

@ -280,15 +280,7 @@ class AxoModule implements ModuleInterface {
array $localized_script_data
): array {
try {
$target_customer_id = '';
if ( is_user_logged_in() ) {
$target_customer_id = get_user_meta( get_current_user_id(), '_ppcp_target_customer_id', true );
if ( ! $target_customer_id ) {
$target_customer_id = get_user_meta( get_current_user_id(), 'ppcp_customer_id', true );
}
}
$sdk_client_token = $api->sdk_client_token( $target_customer_id );
$sdk_client_token = $api->sdk_client_token();
$localized_script_data['axo'] = array(
'sdk_client_token' => $sdk_client_token,
);

View file

@ -71,7 +71,10 @@ export const loadPaypalScript = ( config, onLoaded, onError = null ) => {
}
// Load PayPal script for special case with data-client-token
if ( config.data_client_id?.set_attribute ) {
if (
config.data_client_id?.set_attribute &&
config.vault_v3_enabled !== '1'
) {
dataClientIdAttributeHandler(
scriptOptions,
config.data_client_id,

View file

@ -189,9 +189,8 @@ return array(
$login_seller_sandbox = $container->get( 'api.endpoint.login-seller-sandbox' );
$partner_referrals_data = $container->get( 'api.repository.partner-referrals-data' );
$settings = $container->get( 'wcgateway.settings' );
$logger = $container->get( 'woocommerce.logger.woocommerce' );
$cache = new Cache( 'ppcp-paypal-bearer' );
$logger = $container->get( 'woocommerce.logger.woocommerce' );
return new LoginSellerEndpoint(
$request_data,
$login_seller_production,
@ -199,7 +198,8 @@ return array(
$partner_referrals_data,
$settings,
$cache,
$logger
$logger,
new Cache( 'ppcp-client-credentials-cache' )
);
},
'onboarding.endpoint.pui' => static function( ContainerInterface $container ) : UpdateSignupLinksEndpoint {

View file

@ -12,6 +12,8 @@ namespace WooCommerce\PayPalCommerce\Onboarding\Endpoint;
use Exception;
use Psr\Log\LoggerInterface;
use WooCommerce\PayPalCommerce\ApiClient\Authentication\PayPalBearer;
use WooCommerce\PayPalCommerce\ApiClient\Authentication\SdkClientToken;
use WooCommerce\PayPalCommerce\ApiClient\Authentication\UserIdToken;
use WooCommerce\PayPalCommerce\ApiClient\Endpoint\LoginSeller;
use WooCommerce\PayPalCommerce\ApiClient\Helper\Cache;
use WooCommerce\PayPalCommerce\ApiClient\Repository\PartnerReferralsData;
@ -76,6 +78,13 @@ class LoginSellerEndpoint implements EndpointInterface {
*/
protected $logger;
/**
* The client credentials cache.
*
* @var Cache
*/
private $client_credentials_cache;
/**
* LoginSellerEndpoint constructor.
*
@ -86,6 +95,7 @@ class LoginSellerEndpoint implements EndpointInterface {
* @param Settings $settings The Settings.
* @param Cache $cache The Cache.
* @param LoggerInterface $logger The logger.
* @param Cache $client_credentials_cache The client credentials cache.
*/
public function __construct(
RequestData $request_data,
@ -94,16 +104,18 @@ class LoginSellerEndpoint implements EndpointInterface {
PartnerReferralsData $partner_referrals_data,
Settings $settings,
Cache $cache,
LoggerInterface $logger
LoggerInterface $logger,
Cache $client_credentials_cache
) {
$this->request_data = $request_data;
$this->login_seller_production = $login_seller_production;
$this->login_seller_sandbox = $login_seller_sandbox;
$this->partner_referrals_data = $partner_referrals_data;
$this->settings = $settings;
$this->cache = $cache;
$this->logger = $logger;
$this->request_data = $request_data;
$this->login_seller_production = $login_seller_production;
$this->login_seller_sandbox = $login_seller_sandbox;
$this->partner_referrals_data = $partner_referrals_data;
$this->settings = $settings;
$this->cache = $cache;
$this->logger = $logger;
$this->client_credentials_cache = $client_credentials_cache;
}
/**
@ -175,6 +187,9 @@ class LoginSellerEndpoint implements EndpointInterface {
if ( $this->cache->has( PayPalBearer::CACHE_KEY ) ) {
$this->cache->delete( PayPalBearer::CACHE_KEY );
}
if ( $this->client_credentials_cache->has( SdkClientToken::CACHE_KEY ) ) {
$this->client_credentials_cache->delete( SdkClientToken::CACHE_KEY );
}
wp_schedule_single_event(
time() + 5,

View file

@ -84,10 +84,6 @@ class SavePaymentMethodsModule implements ModuleInterface {
add_filter(
'woocommerce_paypal_payments_localized_script_data',
function( array $localized_script_data ) use ( $c ) {
if ( ! is_user_logged_in() ) {
return $localized_script_data;
}
$api = $c->get( 'api.user-id-token' );
assert( $api instanceof UserIdToken );

View file

@ -366,7 +366,8 @@ return array(
$container->get( 'api.partner_merchant_id-production' ),
$container->get( 'api.partner_merchant_id-sandbox' ),
$container->get( 'api.endpoint.billing-agreements' ),
$logger
$logger,
new Cache( 'ppcp-client-credentials-cache' )
);
},
'wcgateway.order-processor' => static function ( ContainerInterface $container ): OrderProcessor {

View file

@ -12,6 +12,8 @@ namespace WooCommerce\PayPalCommerce\WcGateway\Settings;
use Psr\Log\LoggerInterface;
use WooCommerce\PayPalCommerce\ApiClient\Authentication\Bearer;
use WooCommerce\PayPalCommerce\ApiClient\Authentication\PayPalBearer;
use WooCommerce\PayPalCommerce\ApiClient\Authentication\SdkClientToken;
use WooCommerce\PayPalCommerce\ApiClient\Authentication\UserIdToken;
use WooCommerce\PayPalCommerce\ApiClient\Endpoint\BillingAgreementsEndpoint;
use WooCommerce\PayPalCommerce\ApiClient\Exception\RuntimeException;
use WooCommerce\PayPalCommerce\ApiClient\Helper\Cache;
@ -164,6 +166,13 @@ class SettingsListener {
*/
private $logger;
/**
* The client credentials cache.
*
* @var Cache
*/
private $client_credentials_cache;
/**
* SettingsListener constructor.
*
@ -183,6 +192,7 @@ class SettingsListener {
* @param string $partner_merchant_id_sandbox Partner merchant ID sandbox.
* @param BillingAgreementsEndpoint $billing_agreements_endpoint Billing Agreements endpoint.
* @param ?LoggerInterface $logger The logger.
* @param Cache $client_credentials_cache The client credentials cache.
*/
public function __construct(
Settings $settings,
@ -200,7 +210,8 @@ class SettingsListener {
string $partner_merchant_id_production,
string $partner_merchant_id_sandbox,
BillingAgreementsEndpoint $billing_agreements_endpoint,
LoggerInterface $logger = null
LoggerInterface $logger = null,
Cache $client_credentials_cache
) {
$this->settings = $settings;
@ -219,6 +230,7 @@ class SettingsListener {
$this->partner_merchant_id_sandbox = $partner_merchant_id_sandbox;
$this->billing_agreements_endpoint = $billing_agreements_endpoint;
$this->logger = $logger ?: new NullLogger();
$this->client_credentials_cache = $client_credentials_cache;
}
/**
@ -490,6 +502,9 @@ class SettingsListener {
if ( $this->cache->has( PayPalBearer::CACHE_KEY ) ) {
$this->cache->delete( PayPalBearer::CACHE_KEY );
}
if ( $this->client_credentials_cache->has( SdkClientToken::CACHE_KEY ) ) {
$this->client_credentials_cache->delete( SdkClientToken::CACHE_KEY );
}
if ( $this->pui_status_cache->has( PayUponInvoiceProductStatus::PUI_STATUS_CACHE_KEY ) ) {
$this->pui_status_cache->delete( PayUponInvoiceProductStatus::PUI_STATUS_CACHE_KEY );

View file

@ -43,6 +43,7 @@ class SettingsListenerTest extends ModularTestCase
$billing_agreement_endpoint = Mockery::mock(BillingAgreementsEndpoint::class);
$subscription_helper = Mockery::mock(SubscriptionHelper::class);
$logger = Mockery::mock(LoggerInterface::class);
$client_credentials_cache = Mockery::mock(Cache::class);
$testee = new SettingsListener(
$settings,
@ -60,7 +61,8 @@ class SettingsListenerTest extends ModularTestCase
'',
'',
$billing_agreement_endpoint,
$logger
$logger,
$client_credentials_cache
);
$_GET['section'] = PayPalGateway::ID;
@ -94,6 +96,9 @@ class SettingsListenerTest extends ModularTestCase
->andReturn(false);
$dcc_status_cache->shouldReceive('has')
->andReturn(false);
$client_credentials_cache->shouldReceive('has')->andReturn(true);
$client_credentials_cache->shouldReceive('delete');
$testee->listen();
}