Skip to content

Commit

Permalink
NEXT-25802 - Update JWT package
Browse files Browse the repository at this point in the history
  • Loading branch information
shyim committed Nov 28, 2023
1 parent 0e57aeb commit bba0ee6
Show file tree
Hide file tree
Showing 33 changed files with 109 additions and 81 deletions.
8 changes: 8 additions & 0 deletions changelog/_unreleased/2023-11-13-update-jwt-package.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
title: Update jwt package
issue: NEXT-25802
---

# Core

* Changed the version of composer package `lcobucci/jwt` from 4 to 5.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@
"ezyang/htmlpurifier": "^4.16",
"guzzlehttp/guzzle": "^7.5.0",
"guzzlehttp/psr7": "^2.4",
"lcobucci/jwt": "^4.2",
"lcobucci/jwt": "^5.0",
"lcobucci/clock": "^3.1.0",
"league/flysystem": "^3.10.3",
"league/flysystem-memory": "^3.10.3",
"league/mime-type-detection": "^1.13.0",
Expand Down
1 change: 1 addition & 0 deletions devenv.nix
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ in {
not path /theme/* /media/* /thumbnail/* /bundles/* /css/* /fonts/* /js/* /sitemap/*
}
encode zstd gzip
root * public
php_fastcgi @default unix/${config.languages.php.fpm.pools.web.socket} {
trusted_proxies private_ranges
Expand Down
29 changes: 0 additions & 29 deletions phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -2490,11 +2490,6 @@ parameters:
count: 1
path: src/Core/Content/Rule/Aggregate/RuleCondition/RuleConditionEntity.php

-
message: "#^Parameter \\#1 \\$ids of method Shopware\\\\Core\\\\Content\\\\Rule\\\\DataAbstractionLayer\\\\RuleAreaUpdater\\:\\:update\\(\\) expects list\\<string\\>, array given\\.$#"
count: 1
path: src/Core/Content/Rule/DataAbstractionLayer/RuleAreaUpdater.php

-
message: "#^Parameter \\#1 \\$ids of method Shopware\\\\Core\\\\Content\\\\Rule\\\\DataAbstractionLayer\\\\RuleAreaUpdater\\:\\:update\\(\\) expects list\\<string\\>, non\\-empty\\-array given\\.$#"
count: 1
Expand All @@ -2510,11 +2505,6 @@ parameters:
count: 1
path: src/Core/Content/Rule/DataAbstractionLayer/RulePayloadSubscriber.php

-
message: "#^Parameter \\#1 \\$ids of method Shopware\\\\Core\\\\Content\\\\Rule\\\\DataAbstractionLayer\\\\RulePayloadUpdater\\:\\:update\\(\\) expects list\\<string\\>, array given\\.$#"
count: 1
path: src/Core/Content/Rule/DataAbstractionLayer/RulePayloadUpdater.php

-
message: "#^Method Shopware\\\\Core\\\\Content\\\\Rule\\\\Event\\\\RuleIndexerEvent\\:\\:__construct\\(\\) has parameter \\$ids with no value type specified in iterable type array\\.$#"
count: 1
Expand Down Expand Up @@ -7332,25 +7322,6 @@ parameters:
count: 1
path: src/Core/Framework/Util/Random.php

-
message: "#^Method Shopware\\\\Core\\\\Framework\\\\Uuid\\\\Uuid\\:\\:fromBytesToHexList\\(\\) has parameter \\$bytesList with no value type specified in iterable type array\\.$#"
count: 1
path: src/Core/Framework/Uuid/Uuid.php

-
message: "#^Method Shopware\\\\Core\\\\Framework\\\\Uuid\\\\Uuid\\:\\:fromBytesToHexList\\(\\) return type has no value type specified in iterable type array\\.$#"
count: 1
path: src/Core/Framework/Uuid/Uuid.php

-
message: "#^Method Shopware\\\\Core\\\\Framework\\\\Uuid\\\\Uuid\\:\\:fromHexToBytesList\\(\\) has parameter \\$uuids with no value type specified in iterable type array\\.$#"
count: 1
path: src/Core/Framework/Uuid/Uuid.php

-
message: "#^Method Shopware\\\\Core\\\\Framework\\\\Uuid\\\\Uuid\\:\\:fromHexToBytesList\\(\\) return type has no value type specified in iterable type array\\.$#"
count: 1
path: src/Core/Framework/Uuid/Uuid.php

-
message: "#^Method Shopware\\\\Core\\\\Framework\\\\Validation\\\\DataValidationDefinition\\:\\:getListDefinitions\\(\\) return type has no value type specified in iterable type array\\.$#"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Decoder;
use Lcobucci\JWT\Encoder;
use Lcobucci\JWT\Encoding\JoseEncoder;
use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Validation\Constraint\SignedWith;
Expand All @@ -31,15 +32,17 @@ public static function createJWTConfiguration(
$publicKey = InMemory::plainText($publicKeyText, $publicKey->getPassPhrase() ?? '');
} else {
$privateKey = InMemory::file($privateKey->getKeyPath(), $privateKey->getPassPhrase() ?? '');
$publicKey = InMemory::file($publicKey->getKeyPath(), $publicKey->getPassPhrase() ?? '');
$publicKeyPath = $publicKey->getKeyPath();
\assert($publicKeyPath !== '');
$publicKey = InMemory::file($publicKeyPath, $publicKey->getPassPhrase() ?? '');
}

$configuration = Configuration::forAsymmetricSigner(
$signer,
$privateKey,
$publicKey,
$encoder,
$decoder
$encoder ?? new JoseEncoder(),
$decoder ?? new JoseEncoder()
);

// add basic constraint for token signature validation
Expand Down
30 changes: 17 additions & 13 deletions src/Core/Checkout/Payment/Cart/Token/JWTFactoryV2.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,13 @@
#[Package('checkout')]
class JWTFactoryV2 implements TokenFactoryInterfaceV2
{
/**
* @var Configuration
*/
protected $configuration;

/**
* @internal
*/
public function __construct(
Configuration $configuration,
private Configuration $configuration,
private readonly Connection $connection
) {
$this->configuration = $configuration;
}

public function generateToken(TokenStruct $tokenStruct): string
Expand All @@ -43,22 +37,32 @@ public function generateToken(TokenStruct $tokenStruct): string
);
}

$jwtToken = $this->configuration->builder()
$jwtTokenBuilder = $this->configuration->builder()
->identifiedBy(Uuid::randomHex())
->issuedAt(new \DateTimeImmutable('@' . time()))
->canOnlyBeUsedAfter(new \DateTimeImmutable('@' . time()))
->expiresAt($expires)
->relatedTo($tokenStruct->getTransactionId() ?? '')
->withClaim('pmi', $tokenStruct->getPaymentMethodId())
->withClaim('ful', $tokenStruct->getFinishUrl())
->withClaim('eul', $tokenStruct->getErrorUrl())
->getToken($this->configuration->signer(), $this->configuration->signingKey());
->withClaim('eul', $tokenStruct->getErrorUrl());

$this->write($jwtToken->toString(), $expires);
$transactionId = $tokenStruct->getTransactionId();
if ($transactionId !== '' && $transactionId !== null) {
$jwtTokenBuilder = $jwtTokenBuilder->relatedTo($transactionId);
}

return $jwtToken->toString();
$token = $jwtTokenBuilder->getToken($this->configuration->signer(), $this->configuration->signingKey())->toString();
$this->write(
$token,
$expires
);

return $token;
}

/**
* @param non-empty-string $token
*/
public function parseToken(string $token): TokenStruct
{
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,10 +151,13 @@ public function updateCustomersRecipient(array $ids): void
continue;
}

/** @var non-empty-string[] $salesChannelIds */
$salesChannelIds = array_keys(
json_decode((string) $customer['newsletter_sales_channel_ids'], true, 512, \JSON_THROW_ON_ERROR)
);

$parameters[] = [
'newsletter_ids' => array_keys(
json_decode((string) $customer['newsletter_sales_channel_ids'], true, 512, \JSON_THROW_ON_ERROR)
),
'newsletter_ids' => $salesChannelIds,
'email' => $customer['email'],
'first_name' => $customer['first_name'],
'last_name' => $customer['last_name'],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ public function onEntityWritten(EntityWrittenContainerEvent $event): void
return;
}

$this->update(Uuid::fromBytesToHexList(array_unique(array_filter($ruleIds))));
$this->update(array_values(Uuid::fromBytesToHexList(array_filter(array_unique($ruleIds)))));

$this->cacheInvalidator->invalidate([CachedRuleLoader::CACHE_KEY]);
}
Expand Down Expand Up @@ -156,9 +156,9 @@ public function update(array $ids): void

/**
* @param FkField[] $fields
* @param string[] $ruleIds
* @param list<non-empty-string|null> $ruleIds
*
* @return string[]
* @return list<non-empty-string|null>
*/
private function hydrateRuleIds(array $fields, EntityWrittenEvent $nestedEvent, array $ruleIds): array
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ public function update(array $ids): array

public function updatePayloads(EntityWrittenEvent $event): void
{
/** @var list<non-empty-string> $ruleIds */
$ruleIds = $this->connection->fetchFirstColumn(
'SELECT DISTINCT rc.rule_id
FROM rule_condition rc
Expand All @@ -108,7 +109,7 @@ public function updatePayloads(EntityWrittenEvent $event): void
return;
}

$this->update(Uuid::fromBytesToHexList($ruleIds));
$this->update(array_values(Uuid::fromBytesToHexList($ruleIds)));
}

/**
Expand Down
1 change: 1 addition & 0 deletions src/Core/Framework/Api/OAuth/BearerTokenValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public function validateAuthorization(ServerRequestInterface $request)

$header = $request->getHeader('authorization');

/** @var non-empty-string $jwt */
$jwt = trim(preg_replace('/^(?:\s+)?Bearer\s/', '', $header[0]) ?? '');

/** @var UnencryptedToken $token */
Expand Down
14 changes: 8 additions & 6 deletions src/Core/Framework/App/Api/AppJWTGenerateRoute.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ public function generate(string $name, SalesChannelContext $context): JsonRespon
);

$expiration = new \DateTimeImmutable('+10 minutes');

/** @var non-empty-string $shopId */
$shopId = $this->shopIdProvider->getShopId();
$builder = $configuration
->builder()
Expand All @@ -52,27 +54,27 @@ public function generate(string $name, SalesChannelContext $context): JsonRespon
->expiresAt($expiration);

if (\in_array('sales_channel:read', $privileges, true)) {
$builder->withClaim('salesChannelId', $context->getSalesChannel()->getId());
$builder = $builder->withClaim('salesChannelId', $context->getSalesChannel()->getId());
}

if (\in_array('customer:read', $privileges, true)) {
$builder->withClaim('customerId', $context->getCustomer()->getId());
$builder = $builder->withClaim('customerId', $context->getCustomer()->getId());
}

if (\in_array('currency:read', $privileges, true)) {
$builder->withClaim('currencyId', $context->getCurrency()->getId());
$builder = $builder->withClaim('currencyId', $context->getCurrency()->getId());
}

if (\in_array('language:read', $privileges, true)) {
$builder->withClaim('languageId', $context->getLanguageId());
$builder = $builder->withClaim('languageId', $context->getLanguageId());
}

if (\in_array('payment_method:read', $privileges, true)) {
$builder->withClaim('paymentMethodId', $context->getPaymentMethod()->getId());
$builder = $builder->withClaim('paymentMethodId', $context->getPaymentMethod()->getId());
}

if (\in_array('shipping_method:read', $privileges, true)) {
$builder->withClaim('shippingMethodId', $context->getShippingMethod()->getId());
$builder = $builder->withClaim('shippingMethodId', $context->getShippingMethod()->getId());
}

return new JsonResponse([
Expand Down
25 changes: 24 additions & 1 deletion src/Core/Framework/Uuid/Uuid.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,18 @@ class Uuid

private static ?UnixTimeGenerator $generator = null;

/**
* @return non-empty-string
*/
public static function randomHex(): string
{
return bin2hex(self::randomBytes());
}

/**
* same as Ramsey\Uuid\UuidFactory->uuidFromBytesAndVersion without using a transfer object
*
* @return non-empty-string
*/
public static function randomBytes(): string
{
Expand All @@ -45,13 +50,17 @@ public static function randomBytes(): string
$clockSeqHiAndReserved = pack('n*', BinaryUtils::applyVariant($clockSeqHi));

$bytes = substr_replace($bytes, $timeHiAndVersion, 6, 2);
$bytes = substr_replace($bytes, $clockSeqHiAndReserved, 8, 2);
\assert($bytes !== '');

return substr_replace($bytes, $clockSeqHiAndReserved, 8, 2);
return $bytes;
}

/**
* @throws InvalidUuidException
* @throws InvalidUuidLengthException
*
* @return non-empty-string
*/
public static function fromBytesToHex(string $bytes): string
{
Expand All @@ -64,9 +73,16 @@ public static function fromBytesToHex(string $bytes): string
throw new InvalidUuidException($uuid);
}

\assert($uuid !== '');

return $uuid;
}

/**
* @param array<string> $bytesList
*
* @return array<non-empty-string>
*/
public static function fromBytesToHexList(array $bytesList): array
{
$converted = [];
Expand All @@ -77,6 +93,11 @@ public static function fromBytesToHexList(array $bytesList): array
return $converted;
}

/**
* @param array<string> $uuids
*
* @return array<non-empty-string>
*/
public static function fromHexToBytesList(array $uuids): array
{
$converted = [];
Expand All @@ -89,6 +110,8 @@ public static function fromHexToBytesList(array $uuids): array

/**
* @throws InvalidUuidException
*
* @return non-empty-string
*/
public static function fromHexToBytes(string $uuid): string
{
Expand Down
2 changes: 1 addition & 1 deletion src/Core/Test/Stub/Checkout/Payment/Cart/Token/TestKey.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class TestKey implements Key
{
public function contents(): string
{
return '';
return 'test';
}

public function passphrase(): string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public function algorithmId(): string

public function sign(string $payload, Key $key): string
{
return '';
return 'empty';
}

public function verify(string $expected, string $payload, Key $key): bool
Expand Down
3 changes: 2 additions & 1 deletion src/Core/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@
"ezyang/htmlpurifier": "^4.16",
"guzzlehttp/guzzle": "^7.5.0",
"guzzlehttp/psr7": "^2.4",
"lcobucci/jwt": "^4.2",
"lcobucci/jwt": "^5.0",
"lcobucci/clock": "^3.1.0",
"league/flysystem": "^3.10.3",
"league/flysystem-memory": "^3.10.3",
"league/mime-type-detection": "^1.13.0",
Expand Down
2 changes: 1 addition & 1 deletion src/Elasticsearch/Admin/Indexer/AbstractAdminIndexer.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public function mapping(array $mapping): array
abstract public function getIterator(): IterableQuery;

/**
* @param array<string>|array<int, array<string>> $ids
* @param array<string> $ids
*
* @return array<string, array<string, string>>
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public function globalData(array $result, Context $context): array
}

/**
* @param array<string>|array<int, array<string>> $ids
* @param array<string> $ids
*
* @throws Exception
*
Expand Down
Loading

0 comments on commit bba0ee6

Please sign in to comment.