File: WebAuthnTest.php

package info (click to toggle)
phpmyadmin 4%3A5.2.2-really%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 140,312 kB
  • sloc: javascript: 228,447; php: 166,904; xml: 17,847; sql: 504; sh: 275; makefile: 209; python: 205
file content (299 lines) | stat: -rw-r--r-- 12,848 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
<?php

declare(strict_types=1);

namespace PhpMyAdmin\Tests\Plugins\TwoFactor;

use PhpMyAdmin\Http\ServerRequest;
use PhpMyAdmin\Plugins\TwoFactor\WebAuthn;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Tests\AbstractTestCase;
use PhpMyAdmin\TwoFactor;
use PhpMyAdmin\WebAuthn\Server;
use PhpMyAdmin\WebAuthn\WebAuthnException;
use Psr\Http\Message\UriInterface;

use function array_column;
use function json_decode;

/**
 * @covers \PhpMyAdmin\Plugins\TwoFactor\WebAuthn
 * @covers \PhpMyAdmin\Plugins\TwoFactorPlugin
 * @covers \PhpMyAdmin\WebAuthn\WebAuthnException
 */
#[\PHPUnit\Framework\Attributes\CoversClass(\PhpMyAdmin\Plugins\TwoFactor\WebAuthn::class)]
#[\PHPUnit\Framework\Attributes\CoversClass(\PhpMyAdmin\Plugins\TwoFactorPlugin::class)]
#[\PHPUnit\Framework\Attributes\CoversClass(\PhpMyAdmin\WebAuthn\WebAuthnException::class)]
class WebAuthnTest extends AbstractTestCase
{
    public function testIdNameAndDescription(): void
    {
        self::assertSame('WebAuthn', WebAuthn::$id);
        self::assertSame('Hardware Security Key (WebAuthn/FIDO2)', WebAuthn::getName());
        self::assertSame(
            'Provides authentication using hardware security tokens supporting the WebAuthn/FIDO2 protocol,'
            . ' such as a YubiKey.',
            WebAuthn::getDescription()
        );
    }

    public function testRender(): void
    {
        $GLOBALS['lang'] = 'en';
        $GLOBALS['server'] = 1;
        $GLOBALS['text_dir'] = 'ltr';
        $GLOBALS['PMA_PHP_SELF'] = 'index.php';

        $uri = $this->createStub(UriInterface::class);
        $uri->method('getHost')->willReturn('test.localhost');
        $request = $this->createStub(ServerRequest::class);
        $request->method('getUri')->willReturn($uri);
        $GLOBALS['request'] = $request;

        $twoFactor = $this->createStub(TwoFactor::class);
        $twoFactor->user = 'test_user';
        $twoFactor->config = [
            'backend' => 'WebAuthn',
            'settings' => [
                'credentials' => [
                    // base64 of publicKeyCredentialId1
                    'cHVibGljS2V5Q3JlZGVudGlhbElkMQ==' => [
                        // base64url of publicKeyCredentialId1
                        'publicKeyCredentialId' => 'cHVibGljS2V5Q3JlZGVudGlhbElkMQ',
                        'type' => 'public-key',
                    ],
                    // base64 of publicKeyCredentialId2
                    'cHVibGljS2V5Q3JlZGVudGlhbElkMg==' => ['publicKeyCredentialId' => '', 'type' => ''],
                ],
            ],
        ];

        $expectedRequestOptions = [
            'challenge' => 'challenge',
            'allowCredentials' => [['type' => 'public-key', 'id' => 'cHVibGljS2V5Q3JlZGVudGlhbElkMQ']],
            'timeout' => 60000,
        ];
        $server = $this->createMock(Server::class);
        $server->expects($this->once())->method('getCredentialRequestOptions')->with(
            $this->equalTo('test_user'),
            $this->anything(),
            $this->equalTo('test.localhost'),
            $this->equalTo([['type' => 'public-key', 'id' => 'cHVibGljS2V5Q3JlZGVudGlhbElkMQ']])
        )->willReturn($expectedRequestOptions);

        $webAuthn = new WebAuthn($twoFactor);
        $webAuthn->setServer($server);
        $actual = $webAuthn->render();

        $optionsFromSession = $_SESSION['WebAuthnCredentialRequestOptions'] ?? null;
        self::assertIsString($optionsFromSession);
        self::assertJson($optionsFromSession);
        self::assertSame($expectedRequestOptions, json_decode($optionsFromSession, true));

        self::assertStringContainsString('id="webauthn_request_response"', $actual);
        self::assertStringContainsString('name="webauthn_request_response"', $actual);
        self::assertStringContainsString('value=""', $actual);
        self::assertStringContainsString('data-request-options="', $actual);
        self::assertSame('', $webAuthn->getError());

        $files = ResponseRenderer::getInstance()->getHeader()->getScripts()->getFiles();
        self::assertContains('webauthn.js', array_column($files, 'name'));
    }

    public function testSetup(): void
    {
        $GLOBALS['lang'] = 'en';
        $GLOBALS['server'] = 1;
        $GLOBALS['text_dir'] = 'ltr';
        $GLOBALS['PMA_PHP_SELF'] = 'index.php';

        $uri = $this->createStub(UriInterface::class);
        $uri->method('getHost')->willReturn('test.localhost');
        $request = $this->createStub(ServerRequest::class);
        $request->method('getUri')->willReturn($uri);
        $GLOBALS['request'] = $request;

        $twoFactor = $this->createStub(TwoFactor::class);
        $twoFactor->user = 'test_user';

        $expectedCreationOptions = [
            'challenge' => 'challenge',
            'rp' => ['name' => 'phpMyAdmin (test.localhost)', 'id' => 'test.localhost'],
            'user' => ['id' => 'user_id', 'name' => 'test_user', 'displayName' => 'test_user'],
            'pubKeyCredParams' => [['alg' => -8, 'type' => 'public-key']],
            'authenticatorSelection' => ['authenticatorAttachment' => 'cross-platform'],
            'timeout' => 60000,
            'attestation' => 'none',
        ];
        $server = $this->createMock(Server::class);
        $server->expects($this->once())->method('getCredentialCreationOptions')->with(
            $this->equalTo('test_user'),
            $this->anything(),
            $this->equalTo('test.localhost')
        )->willReturn($expectedCreationOptions);

        $webAuthn = new WebAuthn($twoFactor);
        $webAuthn->setServer($server);
        $actual = $webAuthn->setup();

        $optionsFromSession = $_SESSION['WebAuthnCredentialCreationOptions'] ?? null;
        self::assertIsString($optionsFromSession);
        self::assertJson($optionsFromSession);
        self::assertSame($expectedCreationOptions, json_decode($optionsFromSession, true));

        self::assertStringContainsString('id="webauthn_creation_response"', $actual);
        self::assertStringContainsString('name="webauthn_creation_response"', $actual);
        self::assertStringContainsString('value=""', $actual);
        self::assertStringContainsString('data-creation-options="', $actual);
        self::assertSame('', $webAuthn->getError());

        $files = ResponseRenderer::getInstance()->getHeader()->getScripts()->getFiles();
        self::assertContains('webauthn.js', array_column($files, 'name'));
    }

    public function testConfigure(): void
    {
        $_SESSION = [];
        $request = $this->createStub(ServerRequest::class);
        $request->method('getParsedBodyParam')->willReturnMap([['webauthn_creation_response', '', '']]);
        $GLOBALS['request'] = $request;
        $webAuthn = new WebAuthn($this->createStub(TwoFactor::class));
        self::assertFalse($webAuthn->configure());
        self::assertSame('', $webAuthn->getError());
    }

    public function testConfigure2(): void
    {
        $_SESSION['WebAuthnCredentialCreationOptions'] = '';
        $request = $this->createStub(ServerRequest::class);
        $request->method('getParsedBodyParam')->willReturnMap([['webauthn_creation_response', '', '{}']]);
        $GLOBALS['request'] = $request;
        $webAuthn = new WebAuthn($this->createStub(TwoFactor::class));
        self::assertFalse($webAuthn->configure());
        self::assertStringContainsString('Two-factor authentication failed:', $webAuthn->getError());
    }

    public function testConfigure3(): void
    {
        $_SESSION['WebAuthnCredentialCreationOptions'] = '{}';
        $request = $this->createStub(ServerRequest::class);
        $request->method('getParsedBodyParam')->willReturnMap([['webauthn_creation_response', '', '{}']]);
        $GLOBALS['request'] = $request;

        $server = $this->createMock(Server::class);
        $server->expects($this->once())->method('parseAndValidateAttestationResponse')
            ->willThrowException(new WebAuthnException());

        $webAuthn = new WebAuthn($this->createStub(TwoFactor::class));
        $webAuthn->setServer($server);
        self::assertFalse($webAuthn->configure());
        self::assertStringContainsString('Two-factor authentication failed.', $webAuthn->getError());
    }

    public function testConfigure4(): void
    {
        $_SESSION['WebAuthnCredentialCreationOptions'] = '{}';
        $request = $this->createStub(ServerRequest::class);
        $request->method('getParsedBodyParam')->willReturnMap([['webauthn_creation_response', '', '{}']]);
        $GLOBALS['request'] = $request;

        $twoFactor = $this->createStub(TwoFactor::class);
        $twoFactor->config = ['backend' => '', 'settings' => []];

        // base64url of publicKeyCredentialId1
        $credential = ['publicKeyCredentialId' => 'cHVibGljS2V5Q3JlZGVudGlhbElkMQ', 'userHandle' => 'userHandle'];
        $server = $this->createMock(Server::class);
        $server->expects($this->once())->method('parseAndValidateAttestationResponse')->with(
            $this->equalTo('{}'),
            $this->equalTo('{}'),
            $this->equalTo($request)
        )->willReturn($credential);

        $webAuthn = new WebAuthn($twoFactor);
        $webAuthn->setServer($server);
        self::assertTrue($webAuthn->configure());
        /** @psalm-var array{backend: string, settings: mixed[]} $config */
        $config = $twoFactor->config;
        self::assertSame([
            'backend' => '',
            'settings' => [
                'userHandle' => 'userHandle',
                'credentials' => ['cHVibGljS2V5Q3JlZGVudGlhbElkMQ==' => $credential],
            ],
        ], $config);
    }

    public function testCheck(): void
    {
        $_SESSION = [];
        $request = $this->createStub(ServerRequest::class);
        $request->method('getParsedBodyParam')->willReturnMap([['webauthn_request_response', '', '']]);
        $GLOBALS['request'] = $request;
        $webAuthn = new WebAuthn($this->createStub(TwoFactor::class));
        self::assertFalse($webAuthn->check());
        self::assertSame('', $webAuthn->getError());
    }

    public function testCheck2(): void
    {
        $_SESSION['WebAuthnCredentialRequestOptions'] = '';
        $request = $this->createStub(ServerRequest::class);
        $request->method('getParsedBodyParam')->willReturnMap([['webauthn_request_response', '', '{}']]);
        $GLOBALS['request'] = $request;
        $webAuthn = new WebAuthn($this->createStub(TwoFactor::class));
        self::assertFalse($webAuthn->check());
        self::assertStringContainsString('Two-factor authentication failed:', $webAuthn->getError());
    }

    public function testCheck3(): void
    {
        $_SESSION['WebAuthnCredentialRequestOptions'] = '{"challenge":"challenge"}';
        $request = $this->createStub(ServerRequest::class);
        $request->method('getParsedBodyParam')->willReturnMap([['webauthn_request_response', '', '{}']]);
        $GLOBALS['request'] = $request;

        $server = $this->createMock(Server::class);
        $server->expects($this->once())->method('parseAndValidateAssertionResponse')
            ->willThrowException(new WebAuthnException());

        $webAuthn = new WebAuthn($this->createStub(TwoFactor::class));
        $webAuthn->setServer($server);
        self::assertFalse($webAuthn->check());
        self::assertStringContainsString('Two-factor authentication failed.', $webAuthn->getError());
    }

    public function testCheck4(): void
    {
        $_SESSION['WebAuthnCredentialRequestOptions'] = '{"challenge":"challenge"}';
        $request = $this->createStub(ServerRequest::class);
        $request->method('getParsedBodyParam')->willReturnMap([['webauthn_request_response', '', '{}']]);
        $GLOBALS['request'] = $request;

        $twoFactor = $this->createStub(TwoFactor::class);
        $twoFactor->config = [
            'backend' => 'WebAuthn',
            'settings' => [
                'credentials' => [
                    // base64 of publicKeyCredentialId1
                    'cHVibGljS2V5Q3JlZGVudGlhbElkMQ==' => [
                        // base64url of publicKeyCredentialId1
                        'publicKeyCredentialId' => 'cHVibGljS2V5Q3JlZGVudGlhbElkMQ',
                        'type' => 'public-key',
                    ],
                ],
            ],
        ];

        $server = $this->createMock(Server::class);
        $server->expects($this->once())->method('parseAndValidateAssertionResponse')->with(
            $this->equalTo('{}'),
            $this->equalTo([['type' => 'public-key', 'id' => 'cHVibGljS2V5Q3JlZGVudGlhbElkMQ']]),
            $this->equalTo('challenge'),
            $this->equalTo($request)
        );

        $webAuthn = new WebAuthn($twoFactor);
        $webAuthn->setServer($server);
        self::assertTrue($webAuthn->check());
    }
}