Skip to content

Commit

Permalink
Merge pull request #2257 from acelaya-forks/feature/geolocation-count…
Browse files Browse the repository at this point in the history
…ry-code-redirects

Add new geolocatio-country-code redirect condition type
  • Loading branch information
acelaya authored Nov 14, 2024
2 parents a444ed0 + 7ddb3e7 commit dbef32f
Show file tree
Hide file tree
Showing 15 changed files with 168 additions and 19 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

* [#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
* [#2193](https://github.com/shlinkio/shlink/issues/2193) API keys are now hashed using SHA256, instead of being saved in plain text.

Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
"shlinkio/shlink-event-dispatcher": "^4.1",
"shlinkio/shlink-importer": "^5.3.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",
"spiral/roadrunner": "^2024.1",
"spiral/roadrunner-cli": "^2.6",
Expand Down
2 changes: 1 addition & 1 deletion docs/swagger/definitions/SetShortUrlRedirectRule.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"properties": {
"type": {
"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"
},
"matchKey": {
Expand Down
3 changes: 3 additions & 0 deletions module/CLI/src/RedirectRule/RedirectRuleHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ private function addRule(ShortUrl $shortUrl, StyleInterface $io, array $currentR
RedirectConditionType::IP_ADDRESS => RedirectCondition::forIpAddress(
$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?');
Expand Down
5 changes: 5 additions & 0 deletions module/CLI/test/RedirectRule/RedirectRuleHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ public function newRulesCanBeAdded(
'Query param name?' => 'foo',
'Query param value?' => 'bar',
'IP address, CIDR block or wildcard-pattern (1.2.*.*)' => '1.2.3.4',
'Country code to match?' => 'FR',
default => '',
},
);
Expand Down Expand Up @@ -165,6 +166,10 @@ public static function provideDeviceConditions(): iterable
true,
];
yield 'IP address' => [RedirectConditionType::IP_ADDRESS, [RedirectCondition::forIpAddress('1.2.3.4')]];
yield 'Geolocation country code' => [
RedirectConditionType::GEOLOCATION_COUNTRY_CODE,
[RedirectCondition::forGeolocationCountryCode('FR')],
];
}

#[Test]
Expand Down
8 changes: 6 additions & 2 deletions module/Core/src/Action/AbstractTrackingAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Shlinkio\Shlink\Core\ShortUrl\Model\ShortUrlIdentifier;
use Shlinkio\Shlink\Core\ShortUrl\ShortUrlResolverInterface;
use Shlinkio\Shlink\Core\Visit\RequestTrackerInterface;
use Shlinkio\Shlink\IpGeolocation\Model\Location;

abstract class AbstractTrackingAction implements MiddlewareInterface, RequestMethodInterface
{
Expand All @@ -30,9 +31,12 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface

try {
$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) {
return $this->createErrorResp($request, $handler);
}
Expand Down
3 changes: 1 addition & 2 deletions module/Core/src/Action/RedirectAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

namespace Shlinkio\Shlink\Core\Action;

use Fig\Http\Message\StatusCodeInterface;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface;
use Shlinkio\Shlink\Core\ShortUrl\Entity\ShortUrl;
Expand All @@ -13,7 +12,7 @@
use Shlinkio\Shlink\Core\Util\RedirectResponseHelperInterface;
use Shlinkio\Shlink\Core\Visit\RequestTrackerInterface;

class RedirectAction extends AbstractTrackingAction implements StatusCodeInterface
class RedirectAction extends AbstractTrackingAction
{
public function __construct(
ShortUrlResolverInterface $urlResolver,
Expand Down
24 changes: 22 additions & 2 deletions module/Core/src/RedirectRule/Entity/RedirectCondition.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,16 @@
use Shlinkio\Shlink\Core\RedirectRule\Model\RedirectConditionType;
use Shlinkio\Shlink\Core\RedirectRule\Model\Validation\RedirectRulesInputFilter;
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\ArrayUtils\some;
use function Shlinkio\Shlink\Core\ipAddressFromRequest;
use function Shlinkio\Shlink\Core\normalizeLocale;
use function Shlinkio\Shlink\Core\splitLocale;
use function sprintf;
use function strtolower;
use function strcasecmp;
use function trim;

class RedirectCondition extends AbstractEntity implements JsonSerializable
Expand Down Expand Up @@ -52,6 +54,11 @@ public static function forIpAddress(string $ipAddressPattern): self
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
{
$type = RedirectConditionType::from($rawData[RedirectRulesInputFilter::CONDITION_TYPE]);
Expand All @@ -71,6 +78,7 @@ public function matchesRequest(ServerRequestInterface $request): bool
RedirectConditionType::LANGUAGE => $this->matchesLanguage($request),
RedirectConditionType::DEVICE => $this->matchesDevice($request),
RedirectConditionType::IP_ADDRESS => $this->matchesRemoteIpAddress($request),
RedirectConditionType::GEOLOCATION_COUNTRY_CODE => $this->matchesGeolocationCountryCode($request),
};
}

Expand Down Expand Up @@ -109,7 +117,7 @@ static function (string $lang) use ($matchLanguage, $matchCountryCode): bool {
private function matchesDevice(ServerRequestInterface $request): bool
{
$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
Expand All @@ -118,6 +126,17 @@ private function matchesRemoteIpAddress(ServerRequestInterface $request): bool
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
{
return [
Expand All @@ -138,6 +157,7 @@ public function toHumanFriendly(): string
$this->matchValue,
),
RedirectConditionType::IP_ADDRESS => sprintf('IP address matches %s', $this->matchValue),
RedirectConditionType::GEOLOCATION_COUNTRY_CODE => sprintf('country code is %s', $this->matchValue),
};
}
}
39 changes: 39 additions & 0 deletions module/Core/src/RedirectRule/Model/RedirectConditionType.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,49 @@

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
{
case DEVICE = 'device';
case LANGUAGE = 'language';
case QUERY_PARAM = 'query-param';
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,
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,9 @@
use Laminas\Validator\Callback;
use Laminas\Validator\InArray;
use Shlinkio\Shlink\Common\Validation\InputFactory;
use Shlinkio\Shlink\Core\Model\DeviceType;
use Shlinkio\Shlink\Core\RedirectRule\Model\RedirectConditionType;
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;

/** @extends InputFilter<mixed> */
Expand Down Expand Up @@ -80,11 +77,9 @@ private static function createRedirectConditionInputFilter(): InputFilter

$value = InputFactory::basic(self::CONDITION_MATCH_VALUE, required: true);
$value->getValidatorChain()->attach(new Callback(
fn (string $value, array $context) => match ($context[self::CONDITION_TYPE]) {
RedirectConditionType::DEVICE->value => contains($value, enumValues(DeviceType::class)),
RedirectConditionType::IP_ADDRESS->value => IpAddressUtils::isStaticIpCidrOrWildcard($value),
// RedirectConditionType::LANGUAGE->value => TODO,
default => true,
function (string $value, array $context): bool {
$conditionType = RedirectConditionType::tryFrom($context[self::CONDITION_TYPE]);
return $conditionType === null || $conditionType->isValid($value);
},
));
$redirectConditionInputFilter->add($value);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Shlinkio\Shlink\Core\ShortUrl\ShortUrlResolverInterface;
use Shlinkio\Shlink\Core\Util\RedirectResponseHelperInterface;
use Shlinkio\Shlink\Core\Visit\RequestTrackerInterface;
use Shlinkio\Shlink\IpGeolocation\Model\Location;

use function array_slice;
use function count;
Expand Down Expand Up @@ -73,9 +74,13 @@ private function tryToResolveRedirect(

try {
$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);
} catch (ShortUrlNotFoundException) {
if ($extraPath === null || ! $this->urlShortenerOptions->multiSegmentSlugsEnabled) {
Expand Down
32 changes: 32 additions & 0 deletions module/Core/test/RedirectRule/Entity/RedirectConditionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@
namespace ShlinkioTest\Shlink\Core\RedirectRule\Entity;

use Laminas\Diactoros\ServerRequestFactory;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\TestWith;
use PHPUnit\Framework\TestCase;
use Shlinkio\Shlink\Common\Middleware\IpAddressMiddlewareFactory;
use Shlinkio\Shlink\Core\Model\DeviceType;
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\DESKTOP_USER_AGENT;
Expand Down Expand Up @@ -93,4 +96,33 @@ public function matchesRemoteIpAddress(string|null $remoteIp, string $ipToMatch,

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,
];
}
}
24 changes: 24 additions & 0 deletions module/Core/test/RedirectRule/Model/RedirectRulesDataTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
$this->expectException(ValidationException::class);
Expand Down Expand Up @@ -118,6 +130,18 @@ public function throwsWhenProvidedDataIsInvalid(array $invalidData): void
],
],
]]], '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
{
$result = RedirectRulesData::fromRawData($validData);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Laminas\Diactoros\Uri;
use Mezzio\Router\Route;
use Mezzio\Router\RouteResult;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\MockObject\MockObject;
Expand All @@ -26,6 +27,7 @@
use Shlinkio\Shlink\Core\ShortUrl\ShortUrlResolverInterface;
use Shlinkio\Shlink\Core\Util\RedirectResponseHelperInterface;
use Shlinkio\Shlink\Core\Visit\RequestTrackerInterface;
use Shlinkio\Shlink\IpGeolocation\Model\Location;

use function Laminas\Stratigility\middleware;
use function str_starts_with;
Expand Down Expand Up @@ -153,7 +155,10 @@ function () use ($shortUrl, &$currentIteration, $expectedResolveCalls): ShortUrl
);
$this->redirectionBuilder->expects($this->once())->method('buildShortUrlRedirect')->with(
$shortUrl,
$this->isInstanceOf(ServerRequestInterface::class),
$this->callback(function (ServerRequestInterface $req) {
Assert::assertArrayHasKey(Location::class, $req->getAttributes());
return true;
}),
$expectedExtraPath,
)->willReturn('the_built_long_url');
$this->redirectResponseHelper->expects($this->once())->method('buildRedirectResponse')->with(
Expand Down
Loading

0 comments on commit dbef32f

Please sign in to comment.