You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
pixelfed/app/Services/ActivityPubFetchService.php

286 lines
7.1 KiB
PHTML

<?php
namespace App\Services;
1 month ago
use App\Util\ActivityPub\Helpers;
use App\Util\ActivityPub\HttpSignature;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
4 weeks ago
use League\Uri\BaseUri;
1 month ago
use Psr\Http\Message\ResponseInterface;
class ActivityPubFetchService
{
const CACHE_KEY = 'pf:services:apfetchs:';
1 month ago
private const MAX_REDIRECTS = 2;
private const MAX_RESPONSE_SIZE = 2 * 1024 * 1024;
public static function get($url, $validateUrl = true)
{
1 month ago
$url = Helpers::validateUrl($url);
if (! $url) {
return false;
}
1 month ago
$host = parse_url($url, PHP_URL_HOST);
if (! $host) {
return false;
}
1 month ago
$domainKey = base64_encode(strtolower($host));
$urlKey = hash('sha256', $url);
$key = self::CACHE_KEY.$domainKey.':'.$urlKey;
return Cache::remember($key, 450, function () use ($url) {
return self::fetchRequest($url);
});
}
public static function validateUrl($url)
{
1 month ago
return Helpers::validateUrl($url);
}
1 month ago
public static function fetchRequest($url, $returnJsonFormat = false)
{
$currentUrl = $url;
1 month ago
for ($redirects = 0; $redirects <= self::MAX_REDIRECTS; $redirects++) {
$currentUrl = Helpers::validateUrl($currentUrl);
1 month ago
if (! $currentUrl) {
return;
}
1 month ago
$host = parse_url($currentUrl, PHP_URL_HOST);
$port = parse_url($currentUrl, PHP_URL_PORT) ?: 443;
1 month ago
if (! $host) {
return;
}
1 month ago
$ips = Helpers::resolvePublicIps($host);
1 month ago
if (empty($ips)) {
return;
}
1 month ago
$headers = self::signedHeaders($currentUrl);
1 month ago
try {
$res = Http::withOptions([
'allow_redirects' => false,
'curl' => [
CURLOPT_RESOLVE => [
self::buildResolveEntry(
$host,
$port,
$ips
),
],
CURLOPT_FRESH_CONNECT => true,
CURLOPT_FORBID_REUSE => true,
],
'on_headers' => function (ResponseInterface $response) {
$length = $response->getHeaderLine('Content-Length');
if (
$length !== '' &&
ctype_digit($length) &&
(int) $length > self::MAX_RESPONSE_SIZE
) {
throw new \RuntimeException(
'ActivityPub response exceeds maximum size'
);
}
},
])
->withHeaders($headers)
->timeout(15)
->connectTimeout(5)
->retry(2, 250)
->get($currentUrl);
} catch (RequestException $e) {
return;
} catch (ConnectionException $e) {
return;
} catch (\Throwable $e) {
return;
}
if (in_array($res->status(), [301, 302, 303, 307, 308], true)) {
if ($redirects >= self::MAX_REDIRECTS) {
return;
}
$location = $res->header('Location');
if (! $location) {
return;
}
$nextUrl = self::resolveRedirect($currentUrl, $location);
if (! $nextUrl) {
return;
}
$currentUrl = $nextUrl;
continue;
}
1 month ago
if (! $res->ok()) {
return;
}
if (! self::hasValidContentType($res)) {
return;
}
$body = $res->body();
if (
$body === '' ||
strlen($body) > self::MAX_RESPONSE_SIZE
) {
return;
}
if (! $returnJsonFormat) {
return $body;
}
try {
return json_decode(
$body,
true,
64,
JSON_THROW_ON_ERROR
);
} catch (\JsonException $e) {
return;
}
}
}
1 month ago
private static function signedHeaders(string $url): array
{
$baseHeaders = [
'Accept' => 'application/activity+json',
];
1 month ago
$headers = HttpSignature::instanceActorSign(
$url,
false,
$baseHeaders,
'get'
);
$headers['Accept'] = 'application/activity+json';
1 month ago
$headers['User-Agent'] =
'PixelFedBot/1.0.0 (Pixelfed/'.
config('pixelfed.version').
'; +'.
config('app.url').
1 month ago
')';
1 month ago
return $headers;
}
private static function buildResolveEntry(
string $host,
int $port,
array $ips
): string {
$addresses = array_map(function ($ip) {
return str_contains($ip, ':')
? '['.$ip.']'
1 month ago
: $ip;
}, $ips);
return $host.':'.$port.':'.implode(',', $addresses);
1 month ago
}
private static function resolveRedirect(
string $baseUrl,
string $location
): ?string {
$location = trim($location);
if (
$location === '' ||
preg_match('/[\x00-\x20\x7f]/', $location)
) {
return null;
}
1 month ago
try {
4 weeks ago
$resolved = BaseUri::from($baseUrl)->resolve($location);
1 month ago
$url = (string) $resolved;
return Helpers::validateUrl($url)
? $url
: null;
} catch (\Throwable $e) {
return null;
}
1 month ago
}
1 month ago
private static function hasValidContentType($res): bool
{
$contentType = $res->header('Content-Type');
if (! $contentType) {
1 month ago
return false;
}
1 month ago
$contentTypeParts = array_map(
'trim',
explode(';', $contentType)
);
$mediaType = strtolower($contentTypeParts[0]);
1 month ago
if (! in_array($mediaType, [
'application/activity+json',
'application/ld+json',
1 month ago
], true)) {
return false;
}
1 month ago
if ($mediaType !== 'application/ld+json') {
return true;
}
1 month ago
foreach (array_slice($contentTypeParts, 1) as $param) {
if (stripos($param, 'profile=') !== 0) {
continue;
}
1 month ago
$profile = trim(
substr($param, strlen('profile=')),
" \"'"
);
if ($profile === 'https://www.w3.org/ns/activitystreams') {
return true;
}
}
1 month ago
return false;
}
}