File: AuthorizationTest.php

package info (click to toggle)
php-symfony-mercure 0.6.5-3
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 388 kB
  • sloc: php: 1,519; makefile: 12
file content (214 lines) | stat: -rw-r--r-- 8,268 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
<?php

/*
 * This file is part of the Mercure Component project.
 *
 * (c) Kévin Dunglas <dunglas@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Symfony\Component\Mercure\Tests;

use Lcobucci\JWT\Signer\Key\InMemory;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mercure\Authorization;
use Symfony\Component\Mercure\Exception\RuntimeException;
use Symfony\Component\Mercure\HubRegistry;
use Symfony\Component\Mercure\Jwt\LcobucciFactory;
use Symfony\Component\Mercure\Jwt\StaticTokenProvider;
use Symfony\Component\Mercure\Jwt\TokenFactoryInterface;
use Symfony\Component\Mercure\MockHub;
use Symfony\Component\Mercure\Update;

/**
 * @author Kévin Dunglas <kevin@dunglas.fr>
 */
class AuthorizationTest extends TestCase
{
    public function testJwtLifetime(): void
    {
        if (!class_exists(InMemory::class)) {
            $this->markTestSkipped('"lcobucci/jwt" is not installed');
        }

        $registry = new HubRegistry(new MockHub(
            'https://example.com/.well-known/mercure',
            new StaticTokenProvider('foo.bar.baz'),
            function (Update $u): string { return 'dummy'; },
            new LcobucciFactory('looooooooooooongenoughtestsecret', 'hmac.sha256', 3600)
        ));

        $authorization = new Authorization($registry);
        $cookie = $authorization->createCookie(Request::create('https://example.com'));

        $payload = json_decode(base64_decode(explode('.', $cookie->getValue())[1], true), true);
        $this->assertArrayHasKey('exp', $payload);
        $this->assertIsNumeric($payload['exp']);
    }

    public function testSetCookie(): void
    {
        $tokenFactory = $this->createMock(TokenFactoryInterface::class);
        $tokenFactory
            ->expects($this->once())
            ->method('create')
            ->with($this->equalTo(['foo']), $this->equalTo(['bar']), $this->arrayHasKey('x-foo'))
        ;

        $registry = new HubRegistry(new MockHub(
            'https://example.com/.well-known/mercure',
            new StaticTokenProvider('foo.bar.baz'),
            function (Update $u): string { return 'dummy'; },
            $tokenFactory
        ));

        $request = Request::create('https://example.com');
        $authorization = new Authorization($registry, 0, Cookie::SAMESITE_LAX);
        $authorization->setCookie($request, ['foo'], ['bar'], ['x-foo' => 'bar']);

        $cookie = $request->attributes->get('_mercure_authorization_cookies')[null];
        $this->assertNotNull($cookie->getValue());
        $this->assertSame(0, $cookie->getExpiresTime());
        $this->assertSame(Cookie::SAMESITE_LAX, $cookie->getSameSite());
    }

    public function testClearCookie(): void
    {
        $registry = new HubRegistry(new MockHub(
            'https://example.com/.well-known/mercure',
            new StaticTokenProvider('foo.bar.baz'),
            function (Update $u): string { return 'dummy'; },
            new class() implements TokenFactoryInterface {
                public function create(?array $subscribe = [], ?array $publish = [], array $additionalClaims = []): string
                {
                    return '';
                }
            }
        ));

        $authorization = new Authorization($registry);
        $request = Request::create('https://example.com');
        $authorization->clearCookie($request);

        $cookie = $request->attributes->get('_mercure_authorization_cookies')[null];
        $this->assertNull($cookie->getValue());
        $this->assertSame(1, $cookie->getExpiresTime());
    }

    /**
     * @dataProvider provideApplicableCookieDomains
     */
    #[DataProvider('provideApplicableCookieDomains')]
    public function testApplicableCookieDomains(?string $expected, string $hubUrl, string $requestUrl): void
    {
        if (!class_exists(InMemory::class)) {
            $this->markTestSkipped('"lcobucci/jwt" is not installed');
        }

        $registry = new HubRegistry(new MockHub(
            $hubUrl,
            new StaticTokenProvider('foo.bar.baz'),
            function (Update $u): string { return 'dummy'; },
            new LcobucciFactory('looooooooooooongenoughtestsecret', 'hmac.sha256', 3600)
        ));

        $authorization = new Authorization($registry);
        $cookie = $authorization->createCookie(Request::create($requestUrl));

        $this->assertSame($expected, $cookie->getDomain());
    }

    public static function provideApplicableCookieDomains(): iterable
    {
        yield ['.example.com', 'https://foo.bar.baz.example.com', 'https://foo.bar.baz.qux.example.com'];
        yield ['.foo.bar.baz.example.com', 'https://mercure.foo.bar.baz.example.com', 'https://app.foo.bar.baz.example.com'];
        yield ['example.com', 'https://demo.example.com', 'https://example.com'];
        yield ['.example.com', 'https://mercure.example.com', 'https://app.example.com'];
        yield ['.example.com', 'https://example.com/.well-known/mercure', 'https://app.example.com'];
        yield [null, 'https://example.com/.well-known/mercure', 'https://example.com'];
    }

    /**
     * @dataProvider provideNonApplicableCookieDomains
     */
    #[DataProvider('provideNonApplicableCookieDomains')]
    public function testNonApplicableCookieDomains(string $hubUrl, string $requestUrl): void
    {
        if (!class_exists(InMemory::class)) {
            $this->markTestSkipped('"lcobucci/jwt" is not installed');
        }

        $registry = new HubRegistry(new MockHub(
            $hubUrl,
            new StaticTokenProvider('foo.bar.baz'),
            function (Update $u): string { return 'dummy'; },
            new LcobucciFactory('looooooooooooongenoughtestsecret', 'hmac.sha256', 3600)
        ));

        $authorization = new Authorization($registry);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('Unable to create authorization cookie for a hub on the different second-level domain');

        $authorization->createCookie(Request::create($requestUrl));
    }

    public static function provideNonApplicableCookieDomains(): iterable
    {
        yield ['https://demo.mercure.com', 'https://example.com'];
        yield ['https://mercure.internal.com', 'https://external.com'];
    }

    public function testSetMultipleCookies(): void
    {
        $this->expectException(RuntimeException::class);

        $registry = new HubRegistry(new MockHub(
            'https://example.com/.well-known/mercure',
            new StaticTokenProvider('foo.bar.baz'),
            function (Update $u): string { return 'dummy'; },
            new class() implements TokenFactoryInterface {
                public function create(?array $subscribe = [], ?array $publish = [], array $additionalClaims = []): string
                {
                    return '';
                }
            }
        ));

        $authorization = new Authorization($registry);
        $request = Request::create('https://example.com');
        $authorization->setCookie($request);
        $authorization->clearCookie($request);
    }

    public function testSetNullCookieTopics(): void
    {
        $tokenFactory = $this->createMock(TokenFactoryInterface::class);
        $tokenFactory
            ->expects($this->once())
            ->method('create')
            ->with($this->isNull(), $this->isNull(), $this->arrayHasKey('x-foo'))
        ;

        $registry = new HubRegistry(new MockHub(
            'https://example.com/.well-known/mercure',
            new StaticTokenProvider('foo.bar.baz'),
            function (Update $u): string { return 'dummy'; },
            $tokenFactory
        ));

        $request = Request::create('https://example.com');
        $authorization = new Authorization($registry);
        $authorization->setCookie($request, null, null, ['x-foo' => 'bar']);

        $cookie = $request->attributes->get('_mercure_authorization_cookies')[null];
        $this->assertNotNull($cookie->getValue());
    }
}