Merge pull request #2257 from acelaya-forks/feature/geolocation-country-code-redirects

Add new geolocatio-country-code redirect condition type
This commit is contained in:
Alejandro Celaya 2024-11-14 09:43:10 +01:00 committed by GitHub
commit dbef32ffcb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
15 changed files with 168 additions and 19 deletions

View File

@ -11,6 +11,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com), and this
This change applies both to the `GET /short-urls` endpoint, via the `domain` query parameter, and the `short-url:list` console command, via the `--domain`|`-d` flag. This change applies both to the `GET /short-urls` endpoint, via the `domain` query parameter, and the `short-url:list` console command, via the `--domain`|`-d` flag.
* [#1774](https://github.com/shlinkio/shlink/issues/1774) Add new geolocation redirect rules for the dynamic redirects system.
* `geolocation-country-code`: Allows to perform redirections based on the ISO 3166-1 alpha-2 two-letter country code resolved while geolocating the visitor.
### Changed ### Changed
* [#2193](https://github.com/shlinkio/shlink/issues/2193) API keys are now hashed using SHA256, instead of being saved in plain text. * [#2193](https://github.com/shlinkio/shlink/issues/2193) API keys are now hashed using SHA256, instead of being saved in plain text.

View File

@ -49,7 +49,7 @@
"shlinkio/shlink-event-dispatcher": "^4.1", "shlinkio/shlink-event-dispatcher": "^4.1",
"shlinkio/shlink-importer": "^5.3.2", "shlinkio/shlink-importer": "^5.3.2",
"shlinkio/shlink-installer": "^9.2", "shlinkio/shlink-installer": "^9.2",
"shlinkio/shlink-ip-geolocation": "^4.1", "shlinkio/shlink-ip-geolocation": "dev-main#fadae5d as 4.2",
"shlinkio/shlink-json": "^1.1", "shlinkio/shlink-json": "^1.1",
"spiral/roadrunner": "^2024.1", "spiral/roadrunner": "^2024.1",
"spiral/roadrunner-cli": "^2.6", "spiral/roadrunner-cli": "^2.6",

View File

@ -15,7 +15,7 @@
"properties": { "properties": {
"type": { "type": {
"type": "string", "type": "string",
"enum": ["device", "language", "query-param", "ip-address"], "enum": ["device", "language", "query-param", "ip-address", "geolocation-country-code"],
"description": "The type of the condition, which will determine the logic used to match it" "description": "The type of the condition, which will determine the logic used to match it"
}, },
"matchKey": { "matchKey": {

View File

@ -111,6 +111,9 @@ class RedirectRuleHandler implements RedirectRuleHandlerInterface
RedirectConditionType::IP_ADDRESS => RedirectCondition::forIpAddress( RedirectConditionType::IP_ADDRESS => RedirectCondition::forIpAddress(
$this->askMandatory('IP address, CIDR block or wildcard-pattern (1.2.*.*)', $io), $this->askMandatory('IP address, CIDR block or wildcard-pattern (1.2.*.*)', $io),
), ),
RedirectConditionType::GEOLOCATION_COUNTRY_CODE => RedirectCondition::forGeolocationCountryCode(
$this->askMandatory('Country code to match?', $io),
)
}; };
$continue = $io->confirm('Do you want to add another condition?'); $continue = $io->confirm('Do you want to add another condition?');

View File

@ -117,6 +117,7 @@ class RedirectRuleHandlerTest extends TestCase
'Query param name?' => 'foo', 'Query param name?' => 'foo',
'Query param value?' => 'bar', 'Query param value?' => 'bar',
'IP address, CIDR block or wildcard-pattern (1.2.*.*)' => '1.2.3.4', 'IP address, CIDR block or wildcard-pattern (1.2.*.*)' => '1.2.3.4',
'Country code to match?' => 'FR',
default => '', default => '',
}, },
); );
@ -165,6 +166,10 @@ class RedirectRuleHandlerTest extends TestCase
true, true,
]; ];
yield 'IP address' => [RedirectConditionType::IP_ADDRESS, [RedirectCondition::forIpAddress('1.2.3.4')]]; yield 'IP address' => [RedirectConditionType::IP_ADDRESS, [RedirectCondition::forIpAddress('1.2.3.4')]];
yield 'Geolocation country code' => [
RedirectConditionType::GEOLOCATION_COUNTRY_CODE,
[RedirectCondition::forGeolocationCountryCode('FR')],
];
} }
#[Test] #[Test]

View File

@ -15,6 +15,7 @@ use Shlinkio\Shlink\Core\ShortUrl\Entity\ShortUrl;
use Shlinkio\Shlink\Core\ShortUrl\Model\ShortUrlIdentifier; use Shlinkio\Shlink\Core\ShortUrl\Model\ShortUrlIdentifier;
use Shlinkio\Shlink\Core\ShortUrl\ShortUrlResolverInterface; use Shlinkio\Shlink\Core\ShortUrl\ShortUrlResolverInterface;
use Shlinkio\Shlink\Core\Visit\RequestTrackerInterface; use Shlinkio\Shlink\Core\Visit\RequestTrackerInterface;
use Shlinkio\Shlink\IpGeolocation\Model\Location;
abstract class AbstractTrackingAction implements MiddlewareInterface, RequestMethodInterface abstract class AbstractTrackingAction implements MiddlewareInterface, RequestMethodInterface
{ {
@ -30,9 +31,12 @@ abstract class AbstractTrackingAction implements MiddlewareInterface, RequestMet
try { try {
$shortUrl = $this->urlResolver->resolveEnabledShortUrl($identifier); $shortUrl = $this->urlResolver->resolveEnabledShortUrl($identifier);
$this->requestTracker->trackIfApplicable($shortUrl, $request); $visit = $this->requestTracker->trackIfApplicable($shortUrl, $request);
return $this->createSuccessResp($shortUrl, $request); return $this->createSuccessResp(
$shortUrl,
$request->withAttribute(Location::class, $visit?->getVisitLocation()),
);
} catch (ShortUrlNotFoundException) { } catch (ShortUrlNotFoundException) {
return $this->createErrorResp($request, $handler); return $this->createErrorResp($request, $handler);
} }

View File

@ -4,7 +4,6 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Core\Action; namespace Shlinkio\Shlink\Core\Action;
use Fig\Http\Message\StatusCodeInterface;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ServerRequestInterface;
use Shlinkio\Shlink\Core\ShortUrl\Entity\ShortUrl; use Shlinkio\Shlink\Core\ShortUrl\Entity\ShortUrl;
@ -13,7 +12,7 @@ use Shlinkio\Shlink\Core\ShortUrl\ShortUrlResolverInterface;
use Shlinkio\Shlink\Core\Util\RedirectResponseHelperInterface; use Shlinkio\Shlink\Core\Util\RedirectResponseHelperInterface;
use Shlinkio\Shlink\Core\Visit\RequestTrackerInterface; use Shlinkio\Shlink\Core\Visit\RequestTrackerInterface;
class RedirectAction extends AbstractTrackingAction implements StatusCodeInterface class RedirectAction extends AbstractTrackingAction
{ {
public function __construct( public function __construct(
ShortUrlResolverInterface $urlResolver, ShortUrlResolverInterface $urlResolver,

View File

@ -9,6 +9,8 @@ use Shlinkio\Shlink\Core\Model\DeviceType;
use Shlinkio\Shlink\Core\RedirectRule\Model\RedirectConditionType; use Shlinkio\Shlink\Core\RedirectRule\Model\RedirectConditionType;
use Shlinkio\Shlink\Core\RedirectRule\Model\Validation\RedirectRulesInputFilter; use Shlinkio\Shlink\Core\RedirectRule\Model\Validation\RedirectRulesInputFilter;
use Shlinkio\Shlink\Core\Util\IpAddressUtils; use Shlinkio\Shlink\Core\Util\IpAddressUtils;
use Shlinkio\Shlink\Core\Visit\Entity\VisitLocation;
use Shlinkio\Shlink\IpGeolocation\Model\Location;
use function Shlinkio\Shlink\Core\acceptLanguageToLocales; use function Shlinkio\Shlink\Core\acceptLanguageToLocales;
use function Shlinkio\Shlink\Core\ArrayUtils\some; use function Shlinkio\Shlink\Core\ArrayUtils\some;
@ -16,7 +18,7 @@ use function Shlinkio\Shlink\Core\ipAddressFromRequest;
use function Shlinkio\Shlink\Core\normalizeLocale; use function Shlinkio\Shlink\Core\normalizeLocale;
use function Shlinkio\Shlink\Core\splitLocale; use function Shlinkio\Shlink\Core\splitLocale;
use function sprintf; use function sprintf;
use function strtolower; use function strcasecmp;
use function trim; use function trim;
class RedirectCondition extends AbstractEntity implements JsonSerializable class RedirectCondition extends AbstractEntity implements JsonSerializable
@ -52,6 +54,11 @@ class RedirectCondition extends AbstractEntity implements JsonSerializable
return new self(RedirectConditionType::IP_ADDRESS, $ipAddressPattern); return new self(RedirectConditionType::IP_ADDRESS, $ipAddressPattern);
} }
public static function forGeolocationCountryCode(string $countryCode): self
{
return new self(RedirectConditionType::GEOLOCATION_COUNTRY_CODE, $countryCode);
}
public static function fromRawData(array $rawData): self public static function fromRawData(array $rawData): self
{ {
$type = RedirectConditionType::from($rawData[RedirectRulesInputFilter::CONDITION_TYPE]); $type = RedirectConditionType::from($rawData[RedirectRulesInputFilter::CONDITION_TYPE]);
@ -71,6 +78,7 @@ class RedirectCondition extends AbstractEntity implements JsonSerializable
RedirectConditionType::LANGUAGE => $this->matchesLanguage($request), RedirectConditionType::LANGUAGE => $this->matchesLanguage($request),
RedirectConditionType::DEVICE => $this->matchesDevice($request), RedirectConditionType::DEVICE => $this->matchesDevice($request),
RedirectConditionType::IP_ADDRESS => $this->matchesRemoteIpAddress($request), RedirectConditionType::IP_ADDRESS => $this->matchesRemoteIpAddress($request),
RedirectConditionType::GEOLOCATION_COUNTRY_CODE => $this->matchesGeolocationCountryCode($request),
}; };
} }
@ -109,7 +117,7 @@ class RedirectCondition extends AbstractEntity implements JsonSerializable
private function matchesDevice(ServerRequestInterface $request): bool private function matchesDevice(ServerRequestInterface $request): bool
{ {
$device = DeviceType::matchFromUserAgent($request->getHeaderLine('User-Agent')); $device = DeviceType::matchFromUserAgent($request->getHeaderLine('User-Agent'));
return $device !== null && $device->value === strtolower($this->matchValue); return $device !== null && $device->value === $this->matchValue;
} }
private function matchesRemoteIpAddress(ServerRequestInterface $request): bool private function matchesRemoteIpAddress(ServerRequestInterface $request): bool
@ -118,6 +126,17 @@ class RedirectCondition extends AbstractEntity implements JsonSerializable
return $remoteAddress !== null && IpAddressUtils::ipAddressMatchesGroups($remoteAddress, [$this->matchValue]); return $remoteAddress !== null && IpAddressUtils::ipAddressMatchesGroups($remoteAddress, [$this->matchValue]);
} }
private function matchesGeolocationCountryCode(ServerRequestInterface $request): bool
{
$geolocation = $request->getAttribute(Location::class);
// TODO We should eventually rely on `Location` type only
if (! ($geolocation instanceof Location) && ! ($geolocation instanceof VisitLocation)) {
return false;
}
return strcasecmp($geolocation->countryCode, $this->matchValue) === 0;
}
public function jsonSerialize(): array public function jsonSerialize(): array
{ {
return [ return [
@ -138,6 +157,7 @@ class RedirectCondition extends AbstractEntity implements JsonSerializable
$this->matchValue, $this->matchValue,
), ),
RedirectConditionType::IP_ADDRESS => sprintf('IP address matches %s', $this->matchValue), RedirectConditionType::IP_ADDRESS => sprintf('IP address matches %s', $this->matchValue),
RedirectConditionType::GEOLOCATION_COUNTRY_CODE => sprintf('country code is %s', $this->matchValue),
}; };
} }
} }

View File

@ -2,10 +2,49 @@
namespace Shlinkio\Shlink\Core\RedirectRule\Model; namespace Shlinkio\Shlink\Core\RedirectRule\Model;
use Shlinkio\Shlink\Core\Model\DeviceType;
use Shlinkio\Shlink\Core\Util\IpAddressUtils;
use function Shlinkio\Shlink\Core\ArrayUtils\contains;
use function Shlinkio\Shlink\Core\enumValues;
enum RedirectConditionType: string enum RedirectConditionType: string
{ {
case DEVICE = 'device'; case DEVICE = 'device';
case LANGUAGE = 'language'; case LANGUAGE = 'language';
case QUERY_PARAM = 'query-param'; case QUERY_PARAM = 'query-param';
case IP_ADDRESS = 'ip-address'; case IP_ADDRESS = 'ip-address';
case GEOLOCATION_COUNTRY_CODE = 'geolocation-country-code';
/**
* Tells if a value is valid for the condition type
*/
public function isValid(string $value): bool
{
return match ($this) {
RedirectConditionType::DEVICE => contains($value, enumValues(DeviceType::class)),
// RedirectConditionType::LANGUAGE => TODO Validate at least format,
RedirectConditionType::IP_ADDRESS => IpAddressUtils::isStaticIpCidrOrWildcard($value),
RedirectConditionType::GEOLOCATION_COUNTRY_CODE => contains($value, [
// List of ISO 3166-1 alpha-2 two-letter country codes https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
'AF', 'AX', 'AL', 'DZ', 'AS', 'AD', 'AO', 'AI', 'AQ', 'AG', 'AR', 'AM', 'AW', 'AU', 'AT', 'AZ',
'BS', 'BH', 'BD', 'BB', 'BY', 'BE', 'BZ', 'BJ', 'BM', 'BT', 'BO', 'BQ', 'BA', 'BW', 'BV', 'BR',
'IO', 'BN', 'BG', 'BF', 'BI', 'CV', 'KH', 'CM', 'CA', 'KY', 'CF', 'TD', 'CL', 'CN', 'CX', 'CC',
'CO', 'KM', 'CG', 'CD', 'CK', 'CR', 'CI', 'HR', 'CU', 'CW', 'CY', 'CZ', 'DK', 'DJ', 'DM', 'DO',
'EC', 'EG', 'SV', 'GQ', 'ER', 'EE', 'SZ', 'ET', 'FK', 'FO', 'FJ', 'FI', 'FR', 'GF', 'PF', 'TF',
'GA', 'GM', 'GE', 'DE', 'GH', 'GI', 'GR', 'GL', 'GD', 'GP', 'GU', 'GT', 'GG', 'GN', 'GW', 'GY',
'HT', 'HM', 'VA', 'HN', 'HK', 'HU', 'IS', 'IN', 'ID', 'IR', 'IQ', 'IE', 'IM', 'IL', 'IT', 'JM',
'JP', 'JE', 'JO', 'KZ', 'KE', 'KI', 'KP', 'KR', 'KW', 'KG', 'LA', 'LV', 'LB', 'LS', 'LR', 'LY',
'LI', 'LT', 'LU', 'MO', 'MG', 'MW', 'MY', 'MV', 'ML', 'MT', 'MH', 'MQ', 'MR', 'MU', 'YT', 'MX',
'FM', 'MD', 'MC', 'MN', 'ME', 'MS', 'MA', 'MZ', 'MM', 'NA', 'NR', 'NP', 'NL', 'NC', 'NZ', 'NI',
'NE', 'NG', 'NU', 'NF', 'MK', 'MP', 'NO', 'OM', 'PK', 'PW', 'PS', 'PA', 'PG', 'PY', 'PE', 'PH',
'PN', 'PL', 'PT', 'PR', 'QA', 'RE', 'RO', 'RU', 'RW', 'BL', 'SH', 'KN', 'LC', 'MF', 'PM', 'VC',
'WS', 'SM', 'ST', 'SA', 'SN', 'RS', 'SC', 'SL', 'SG', 'SX', 'SK', 'SI', 'SB', 'SO', 'ZA', 'GS',
'SS', 'ES', 'LK', 'SD', 'SR', 'SJ', 'SE', 'CH', 'SY', 'TW', 'TJ', 'TZ', 'TH', 'TL', 'TG', 'TK',
'TO', 'TT', 'TN', 'TR', 'TM', 'TC', 'TV', 'UG', 'UA', 'AE', 'GB', 'US', 'UM', 'UY', 'UZ', 'VU',
'VE', 'VN', 'VG', 'VI', 'WF', 'EH', 'YE', 'ZM', 'ZW',
]),
default => true,
};
}
} }

View File

@ -9,12 +9,9 @@ use Laminas\InputFilter\InputFilter;
use Laminas\Validator\Callback; use Laminas\Validator\Callback;
use Laminas\Validator\InArray; use Laminas\Validator\InArray;
use Shlinkio\Shlink\Common\Validation\InputFactory; use Shlinkio\Shlink\Common\Validation\InputFactory;
use Shlinkio\Shlink\Core\Model\DeviceType;
use Shlinkio\Shlink\Core\RedirectRule\Model\RedirectConditionType; use Shlinkio\Shlink\Core\RedirectRule\Model\RedirectConditionType;
use Shlinkio\Shlink\Core\ShortUrl\Model\Validation\ShortUrlInputFilter; use Shlinkio\Shlink\Core\ShortUrl\Model\Validation\ShortUrlInputFilter;
use Shlinkio\Shlink\Core\Util\IpAddressUtils;
use function Shlinkio\Shlink\Core\ArrayUtils\contains;
use function Shlinkio\Shlink\Core\enumValues; use function Shlinkio\Shlink\Core\enumValues;
/** @extends InputFilter<mixed> */ /** @extends InputFilter<mixed> */
@ -80,11 +77,9 @@ class RedirectRulesInputFilter extends InputFilter
$value = InputFactory::basic(self::CONDITION_MATCH_VALUE, required: true); $value = InputFactory::basic(self::CONDITION_MATCH_VALUE, required: true);
$value->getValidatorChain()->attach(new Callback( $value->getValidatorChain()->attach(new Callback(
fn (string $value, array $context) => match ($context[self::CONDITION_TYPE]) { function (string $value, array $context): bool {
RedirectConditionType::DEVICE->value => contains($value, enumValues(DeviceType::class)), $conditionType = RedirectConditionType::tryFrom($context[self::CONDITION_TYPE]);
RedirectConditionType::IP_ADDRESS->value => IpAddressUtils::isStaticIpCidrOrWildcard($value), return $conditionType === null || $conditionType->isValid($value);
// RedirectConditionType::LANGUAGE->value => TODO,
default => true,
}, },
)); ));
$redirectConditionInputFilter->add($value); $redirectConditionInputFilter->add($value);

View File

@ -17,6 +17,7 @@ use Shlinkio\Shlink\Core\ShortUrl\Model\ShortUrlIdentifier;
use Shlinkio\Shlink\Core\ShortUrl\ShortUrlResolverInterface; use Shlinkio\Shlink\Core\ShortUrl\ShortUrlResolverInterface;
use Shlinkio\Shlink\Core\Util\RedirectResponseHelperInterface; use Shlinkio\Shlink\Core\Util\RedirectResponseHelperInterface;
use Shlinkio\Shlink\Core\Visit\RequestTrackerInterface; use Shlinkio\Shlink\Core\Visit\RequestTrackerInterface;
use Shlinkio\Shlink\IpGeolocation\Model\Location;
use function array_slice; use function array_slice;
use function count; use function count;
@ -73,9 +74,13 @@ readonly class ExtraPathRedirectMiddleware implements MiddlewareInterface
try { try {
$shortUrl = $this->resolver->resolveEnabledShortUrl($identifier); $shortUrl = $this->resolver->resolveEnabledShortUrl($identifier);
$this->requestTracker->trackIfApplicable($shortUrl, $request); $visit = $this->requestTracker->trackIfApplicable($shortUrl, $request);
$longUrl = $this->redirectionBuilder->buildShortUrlRedirect($shortUrl, $request, $extraPath); $longUrl = $this->redirectionBuilder->buildShortUrlRedirect(
$shortUrl,
$request->withAttribute(Location::class, $visit?->getVisitLocation()),
$extraPath,
);
return $this->redirectResponseHelper->buildRedirectResponse($longUrl); return $this->redirectResponseHelper->buildRedirectResponse($longUrl);
} catch (ShortUrlNotFoundException) { } catch (ShortUrlNotFoundException) {
if ($extraPath === null || ! $this->urlShortenerOptions->multiSegmentSlugsEnabled) { if ($extraPath === null || ! $this->urlShortenerOptions->multiSegmentSlugsEnabled) {

View File

@ -3,12 +3,15 @@
namespace ShlinkioTest\Shlink\Core\RedirectRule\Entity; namespace ShlinkioTest\Shlink\Core\RedirectRule\Entity;
use Laminas\Diactoros\ServerRequestFactory; use Laminas\Diactoros\ServerRequestFactory;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\TestWith; use PHPUnit\Framework\Attributes\TestWith;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use Shlinkio\Shlink\Common\Middleware\IpAddressMiddlewareFactory; use Shlinkio\Shlink\Common\Middleware\IpAddressMiddlewareFactory;
use Shlinkio\Shlink\Core\Model\DeviceType; use Shlinkio\Shlink\Core\Model\DeviceType;
use Shlinkio\Shlink\Core\RedirectRule\Entity\RedirectCondition; use Shlinkio\Shlink\Core\RedirectRule\Entity\RedirectCondition;
use Shlinkio\Shlink\Core\Visit\Entity\VisitLocation;
use Shlinkio\Shlink\IpGeolocation\Model\Location;
use const ShlinkioTest\Shlink\ANDROID_USER_AGENT; use const ShlinkioTest\Shlink\ANDROID_USER_AGENT;
use const ShlinkioTest\Shlink\DESKTOP_USER_AGENT; use const ShlinkioTest\Shlink\DESKTOP_USER_AGENT;
@ -93,4 +96,33 @@ class RedirectConditionTest extends TestCase
self::assertEquals($expected, $result); self::assertEquals($expected, $result);
} }
#[Test, DataProvider('provideVisits')]
public function matchesGeolocationCountryCode(
Location|VisitLocation|null $location,
string $countryCodeToMatch,
bool $expected,
): void {
$request = ServerRequestFactory::fromGlobals()->withAttribute(Location::class, $location);
$result = RedirectCondition::forGeolocationCountryCode($countryCodeToMatch)->matchesRequest($request);
self::assertEquals($expected, $result);
}
public static function provideVisits(): iterable
{
yield 'no location' => [null, 'US', false];
yield 'non-matching location' => [new Location(countryCode: 'ES'), 'US', false];
yield 'matching location' => [new Location(countryCode: 'US'), 'US', true];
yield 'matching case-insensitive' => [new Location(countryCode: 'US'), 'us', true];
yield 'matching visit location' => [
VisitLocation::fromGeolocation(new Location(countryCode: 'US')),
'US',
true,
];
yield 'matching visit case-insensitive' => [
VisitLocation::fromGeolocation(new Location(countryCode: 'es')),
'ES',
true,
];
}
} }

View File

@ -63,6 +63,18 @@ class RedirectRulesDataTest extends TestCase
], ],
], ],
]]])] ]]])]
#[TestWith([['redirectRules' => [
[
'longUrl' => 'https://example.com',
'conditions' => [
[
'type' => 'geolocation-country-code',
'matchKey' => null,
'matchValue' => 'not an country code',
],
],
],
]]])]
public function throwsWhenProvidedDataIsInvalid(array $invalidData): void public function throwsWhenProvidedDataIsInvalid(array $invalidData): void
{ {
$this->expectException(ValidationException::class); $this->expectException(ValidationException::class);
@ -118,6 +130,18 @@ class RedirectRulesDataTest extends TestCase
], ],
], ],
]]], 'in-between IP wildcard pattern')] ]]], 'in-between IP wildcard pattern')]
#[TestWith([['redirectRules' => [
[
'longUrl' => 'https://example.com',
'conditions' => [
[
'type' => 'geolocation-country-code',
'matchKey' => null,
'matchValue' => 'US',
],
],
],
]]], 'country code')]
public function allowsValidDataToBeSet(array $validData): void public function allowsValidDataToBeSet(array $validData): void
{ {
$result = RedirectRulesData::fromRawData($validData); $result = RedirectRulesData::fromRawData($validData);

View File

@ -9,6 +9,7 @@ use Laminas\Diactoros\ServerRequestFactory;
use Laminas\Diactoros\Uri; use Laminas\Diactoros\Uri;
use Mezzio\Router\Route; use Mezzio\Router\Route;
use Mezzio\Router\RouteResult; use Mezzio\Router\RouteResult;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\MockObject\MockObject;
@ -26,6 +27,7 @@ use Shlinkio\Shlink\Core\ShortUrl\Model\ShortUrlIdentifier;
use Shlinkio\Shlink\Core\ShortUrl\ShortUrlResolverInterface; use Shlinkio\Shlink\Core\ShortUrl\ShortUrlResolverInterface;
use Shlinkio\Shlink\Core\Util\RedirectResponseHelperInterface; use Shlinkio\Shlink\Core\Util\RedirectResponseHelperInterface;
use Shlinkio\Shlink\Core\Visit\RequestTrackerInterface; use Shlinkio\Shlink\Core\Visit\RequestTrackerInterface;
use Shlinkio\Shlink\IpGeolocation\Model\Location;
use function Laminas\Stratigility\middleware; use function Laminas\Stratigility\middleware;
use function str_starts_with; use function str_starts_with;
@ -153,7 +155,10 @@ class ExtraPathRedirectMiddlewareTest extends TestCase
); );
$this->redirectionBuilder->expects($this->once())->method('buildShortUrlRedirect')->with( $this->redirectionBuilder->expects($this->once())->method('buildShortUrlRedirect')->with(
$shortUrl, $shortUrl,
$this->isInstanceOf(ServerRequestInterface::class), $this->callback(function (ServerRequestInterface $req) {
Assert::assertArrayHasKey(Location::class, $req->getAttributes());
return true;
}),
$expectedExtraPath, $expectedExtraPath,
)->willReturn('the_built_long_url'); )->willReturn('the_built_long_url');
$this->redirectResponseHelper->expects($this->once())->method('buildRedirectResponse')->with( $this->redirectResponseHelper->expects($this->once())->method('buildRedirectResponse')->with(

View File

@ -96,6 +96,20 @@ class SetRedirectRulesTest extends ApiTestCase
], ],
], ],
]], 'invalid IP address')] ]], 'invalid IP address')]
#[TestWith([[
'redirectRules' => [
[
'longUrl' => 'https://example.com',
'conditions' => [
[
'type' => 'geolocation-country-code',
'matchKey' => null,
'matchValue' => 'not a country code',
],
],
],
],
]], 'invalid country code')]
public function errorIsReturnedWhenInvalidDataIsProvided(array $bodyPayload): void public function errorIsReturnedWhenInvalidDataIsProvided(array $bodyPayload): void
{ {
$response = $this->callApiWithKey(self::METHOD_POST, '/short-urls/abc123/redirect-rules', [ $response = $this->callApiWithKey(self::METHOD_POST, '/short-urls/abc123/redirect-rules', [