Lines 100.00% 9 / 9
Functions and Methods 100.00% 2 / 2
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
UnauthorizedRequestWarnings 100.00% 9 / 9 100.00% 2 / 2 3 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 recordRefusedRequest 100.00% 8 / 8 100.00% 1 / 1 2
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Http;
6
7use Amp\Http\Server\Request;
8use Psr\Log\LoggerInterface;
9use Stewart\Runtime\Logging\EveryNthOccurrence;
10
11// A scanner or a misconfigured scraper repeats the same refusal, so the warnings are sampled.
12final class UnauthorizedRequestWarnings
13{
14    private int $refused = 0;
15
16    private readonly EveryNthOccurrence $reports;
17
18    public function __construct(
19        private readonly HttpListenerRole $role,
20        private readonly LoggerInterface $logger,
21    ) {
22        $this->reports = EveryNthOccurrence::forRepeatedWarnings();
23    }
24
25    public function recordRefusedRequest(Request $request): void
26    {
27        ++$this->refused;
28
29        if ($this->reports->includesOccurrence($this->refused)) {
30            $this->logger->warning('HTTP request refused: no valid bearer token', [
31                'listener' => $this->role->value,
32                'client' => $request->getClient()->getRemoteAddress()->toString(),
33                'path' => $request->getUri()->getPath(),
34                'refused' => $this->refused,
35            ]);
36        }
37    }
38}