さすがにServiceからHttpExceptionは雑すぎたか

This commit is contained in:
shibafu 2020-07-23 13:08:20 +09:00
parent 16b5fb3533
commit 0a9920b11c
4 changed files with 41 additions and 2 deletions

View File

@ -2,6 +2,7 @@
namespace App\Http\Controllers\Api;
use App\MetadataResolver\DeniedHostException;
use App\Services\MetadataResolveService;
use Illuminate\Http\Request;
@ -13,7 +14,11 @@ class CardController
'url:required|url'
]);
$metadata = $service->execute($request->input('url'));
try {
$metadata = $service->execute($request->input('url'));
} catch (DeniedHostException $e) {
abort(403, $e->getMessage());
}
$metadata->load('tags');
$response = response($metadata);

View File

@ -3,6 +3,7 @@
namespace App\Listeners;
use App\Events\LinkDiscovered;
use App\MetadataResolver\DeniedHostException;
use App\Services\MetadataResolveService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
@ -32,6 +33,8 @@ class LinkCollector
{
try {
$this->metadataResolveService->execute($event->url);
} catch (DeniedHostException $e) {
// ignored
} catch (\Exception $e) {
// 今のところこのイベントは同期実行されるので、上流をクラッシュさせないために雑catchする
report($e);

View File

@ -0,0 +1,30 @@
<?php
namespace App\MetadataResolver;
use Exception;
use Throwable;
/**
* メタデータの解決を禁止しているホストに対して取得を試み、ブロックされたことを表します。
*/
class DeniedHostException extends Exception
{
private $url;
public function __construct(string $url, Throwable $previous = null)
{
parent::__construct("Access denied by system policy: $url", 0, $previous);
$this->url = $url;
}
public function getUrl(): string
{
return $this->url;
}
public function getHost(): string
{
return parse_url($this->url, PHP_URL_HOST);
}
}

View File

@ -3,6 +3,7 @@
namespace App\Services;
use App\Metadata;
use App\MetadataResolver\DeniedHostException;
use App\MetadataResolver\MetadataResolver;
use App\Tag;
use App\Utilities\Formatter;
@ -29,7 +30,7 @@ class MetadataResolveService
// 自分自身は解決しない
if (parse_url($url, PHP_URL_HOST) === parse_url(config('app.url'), PHP_URL_HOST)) {
abort(403);
throw new DeniedHostException($url);
}
// 無かったら取得