File: OidcTokenHandlerTest.php

package info (click to toggle)
symfony 7.3.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 129,560 kB
  • sloc: php: 1,503,693; xml: 6,816; javascript: 1,043; sh: 586; makefile: 241; pascal: 70
file content (199 lines) | stat: -rw-r--r-- 6,532 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
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\AccessToken\Oidc;

use Jose\Component\Core\AlgorithmManager;
use Jose\Component\Core\JWK;
use Jose\Component\Core\JWKSet;
use Jose\Component\Signature\Algorithm\ES256;
use Jose\Component\Signature\JWSBuilder;
use Jose\Component\Signature\Serializer\CompactSerializer;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\User\OidcUser;
use Symfony\Component\Security\Http\AccessToken\Oidc\OidcTokenHandler;
use Symfony\Component\Security\Http\Authenticator\FallbackUserLoader;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;

/**
 * @requires extension openssl
 */
class OidcTokenHandlerTest extends TestCase
{
    private const AUDIENCE = 'Symfony OIDC';

    /**
     * @dataProvider getClaims
     * @group jwt
     */
    public function testGetsUserIdentifierFromSignedToken(string $claim, string $expected)
    {
        $time = time();
        $claims = [
            'iat' => $time,
            'nbf' => $time,
            'exp' => $time + 3600,
            'iss' => 'https://www.example.com',
            'aud' => self::AUDIENCE,
            'sub' => 'e21bf182-1538-406e-8ccb-e25a17aba39f',
            'email' => 'foo@example.com',
        ];
        $token = $this->buildJWS(json_encode($claims));
        $expectedUser = new OidcUser(...$claims, userIdentifier: $claims[$claim]);

        $loggerMock = $this->createMock(LoggerInterface::class);
        $loggerMock->expects($this->never())->method('error');

        $userBadge = (new OidcTokenHandler(
            new AlgorithmManager([new ES256()]),
            $this->getJWKSet(),
            self::AUDIENCE,
            ['https://www.example.com'],
            $claim,
            $loggerMock,
        ))->getUserBadgeFrom($token);
        $actualUser = $userBadge->getUserLoader()();

        $this->assertEquals(new UserBadge($expected, new FallbackUserLoader(fn () => $expectedUser), $claims), $userBadge);
        $this->assertInstanceOf(OidcUser::class, $actualUser);
        $this->assertEquals($expectedUser, $actualUser);
        $this->assertEquals($claims, $userBadge->getAttributes());
        $this->assertEquals($claims[$claim], $actualUser->getUserIdentifier());
    }

    public static function getClaims(): iterable
    {
        yield ['sub', 'e21bf182-1538-406e-8ccb-e25a17aba39f'];
        yield ['email', 'foo@example.com'];
    }

    /**
     * @group jwt
     */
    public function testThrowsAnErrorIfTokenIsInvalid(string $token)
    {
        $loggerMock = $this->createMock(LoggerInterface::class);
        $loggerMock->expects($this->once())->method('error');

        $this->expectException(BadCredentialsException::class);
        $this->expectExceptionMessage('Invalid credentials.');

        (new OidcTokenHandler(
            new AlgorithmManager([new ES256()]),
            $this->getJWKSet(),
            self::AUDIENCE,
            ['https://www.example.com'],
            'sub',
            $loggerMock,
        ))->getUserBadgeFrom($token);
    }

    public static function getInvalidTokens(): iterable
    {
        // Invalid token
        yield ['invalid'];
        // Token is expired
        yield [
            self::buildJWS(json_encode([
                'iat' => time() - 3600,
                'nbf' => time() - 3600,
                'exp' => time() - 3590,
                'iss' => 'https://www.example.com',
                'aud' => self::AUDIENCE,
                'sub' => 'e21bf182-1538-406e-8ccb-e25a17aba39f',
                'email' => 'foo@example.com',
            ])),
        ];
        // Invalid audience
        yield [
            self::buildJWS(json_encode([
                'iat' => time(),
                'nbf' => time(),
                'exp' => time() + 3590,
                'iss' => 'https://www.example.com',
                'aud' => 'invalid',
                'sub' => 'e21bf182-1538-406e-8ccb-e25a17aba39f',
                'email' => 'foo@example.com',
            ])),
        ];
    }

    /**
     * @group jwt
     */
    public function testThrowsAnErrorIfUserPropertyIsMissing()
    {
        $loggerMock = $this->createMock(LoggerInterface::class);
        $loggerMock->expects($this->once())->method('error');

        $time = time();
        $claims = [
            'iat' => $time,
            'nbf' => $time,
            'exp' => $time + 3600,
            'iss' => 'https://www.example.com',
            'aud' => self::AUDIENCE,
            'sub' => 'e21bf182-1538-406e-8ccb-e25a17aba39f',
        ];
        $token = $this->buildJWS(json_encode($claims));

        $this->expectException(BadCredentialsException::class);
        $this->expectExceptionMessage('Invalid credentials.');

        (new OidcTokenHandler(
            new AlgorithmManager([new ES256()]),
            self::getJWKSet(),
            self::AUDIENCE,
            ['https://www.example.com'],
            'email',
            $loggerMock,
        ))->getUserBadgeFrom($token);
    }

    private static function buildJWS(string $payload): string
    {
        return (new CompactSerializer())->serialize((new JWSBuilder(new AlgorithmManager([
            new ES256(),
        ])))->create()
            ->withPayload($payload)
            ->addSignature(self::getJWK(), ['alg' => 'ES256'])
            ->build()
        );
    }

    private static function getJWK(): JWK
    {
        // tip: use https://mkjwk.org/ to generate a JWK
        return new JWK([
            'kty' => 'EC',
            'crv' => 'P-256',
            'x' => '0QEAsI1wGI-dmYatdUZoWSRWggLEpyzopuhwk-YUnA4',
            'y' => 'KYl-qyZ26HobuYwlQh-r0iHX61thfP82qqEku7i0woo',
            'd' => 'iA_TV2zvftni_9aFAQwFO_9aypfJFCSpcCyevDvz220',
        ]);
    }

    private static function getJWKSet(): JWKSet
    {
        return new JWKSet([
            new JWK([
                'kty' => 'EC',
                'crv' => 'P-256',
                'x' => 'FtgMtrsKDboRO-Zo0XC7tDJTATHVmwuf9GK409kkars',
                'y' => 'rWDE0ERU2SfwGYCo1DWWdgFEbZ0MiAXLRBBOzBgs_jY',
                'd' => '4G7bRIiKih0qrFxc0dtvkHUll19tTyctoCR3eIbOrO0',
            ]),
            self::getJWK(),
        ]);
    }
}