HttpDigest::process()   B
last analyzed

Complexity

Conditions 7
Paths 5

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 7

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 7
eloc 13
c 1
b 0
f 1
nc 5
nop 1
dl 0
loc 21
ccs 14
cts 14
cp 1
crap 7
rs 8.8333
1
<?php
2
3
namespace kalanis\kw_auth\Methods;
4
5
6
use ArrayAccess;
7
use kalanis\kw_accounts\Interfaces\IAuthCert;
8
9
10
/**
11
 * Class HttpDigest
12
 * @package kalanis\kw_auth\AuthMethods
13
 * Authenticate via digest http method
14
 * @link https://serverpilot.io/docs/how-to-perform-http-digest-authentication-with-php/
15
 * @link https://www.php.net/manual/en/features.http-auth.php
16
 */
17
class HttpDigest extends AMethods
18
{
19
    public const INPUT_METHOD = 'REQUEST_METHOD';
20
    public const INPUT_DIGEST = 'PHP_AUTH_DIGEST';
21
22
    protected string $realm = 'KWCMS_Http_Digest';
23
    protected IAuthCert $certAuthenticator;
24
    /** @var ArrayAccess<string, string|int> */
25
    protected ArrayAccess $server;
26
27
    /**
28
     * @param IAuthCert $authenticator
29
     * @param AMethods|null $nextOne
30
     * @param ArrayAccess<string, string|int> $server
31
     */
32 6
    public function __construct(IAuthCert $authenticator, ?AMethods $nextOne, ArrayAccess $server)
33
    {
34 6
        parent::__construct($authenticator, $nextOne);
35 6
        $this->certAuthenticator = $authenticator;
36 6
        $this->server = $server;
37 6
    }
38
39 6
    public function process(ArrayAccess $credentials): void
40
    {
41 6
        if (!$this->server->offsetExists(static::INPUT_DIGEST) || empty($this->server->offsetGet(static::INPUT_DIGEST))) {
42 2
            return;
43
        }
44 4
        $data = $this->httpDigestParse(strval($this->server->offsetGet(static::INPUT_DIGEST)));
45 4
        if (!empty($data)) {
46 3
            $wantedUser = $this->certAuthenticator->getDataOnly(strval($data['username']));
47 3
            $wantedCert = $this->certAuthenticator->getCertData(strval($data['username']));
48 3
            if (!$wantedCert || !$wantedUser) {
49 1
                return;
50
            }
51
52
            // verify
53 2
            $A1 = md5($data['username'] . ':' . $this->realm . ':' . $wantedCert->getPubKey()); // @todo: srsly, pubkey?! have nothing better?
54 2
            $A2 = md5($this->server->offsetGet(static::INPUT_METHOD) . ':' . $data['uri']);
55 2
            $valid_response = md5($A1 . ':' . $data['nonce'] . ':' . $data['nc'] . ':' . $data['cnonce'] . ':' . $data['qop'] . ':' . $A2);
56
57 2
            if ($data['response'] == $valid_response) {
58
                // OK
59 2
                $this->loggedUser = $wantedUser;
60
            }
61
        }
62 3
    }
63
64
    /**
65
     * @codeCoverageIgnore headers
66
     */
67
    public function remove(): void
68
    {
69
        $this->authNotExists();
70
    }
71
72
    /**
73
     * @codeCoverageIgnore headers
74
     */
75
    public function authNotExists(): void
76
    {
77
        header('HTTP/1.1 401 Unauthorized');
78
        header('WWW-Authenticate: Digest realm="' . $this->realm . '",qop="auth",nonce="' . uniqid() . '",opaque="' . md5($this->realm) . '"');
79
    }
80
81
    /**
82
     * Parse the http auth header
83
     * @param string $txt
84
     * @return array<string, string>
85
     */
86 4
    protected function httpDigestParse(string $txt): array
87
    {
88
        // protect against missing data
89 4
        $needed_parts = ['nonce' => 1, 'nc' => 1, 'cnonce' => 1, 'qop' => 1, 'username' => 1, 'uri' => 1, 'response' => 1];
90 4
        $data = [];
91 4
        $keys = implode('|', array_keys($needed_parts));
92
93 4
        preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]*?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);
94
95 4
        foreach ($matches as $m) {
96 3
            $data[strval($m[1])] = strval($m[3] ?: ( $m[4] ?? '' ));
97 3
            unset($needed_parts[$m[1]]);
98
        }
99
100
        // can be and shall be due that unset a few lines above
101 4
        return empty($needed_parts) ? $data : [];
102
    }
103
}
104