File: test_base_authentication_middleware.py

package info (click to toggle)
litestar 2.21.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 12,568 kB
  • sloc: python: 70,588; makefile: 254; javascript: 104; sh: 60
file content (261 lines) | stat: -rw-r--r-- 8,644 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
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Dict

import pytest

from litestar import Litestar, get, websocket
from litestar.connection import Request, WebSocket
from litestar.enums import HttpMethod
from litestar.exceptions import PermissionDeniedException, WebSocketDisconnect
from litestar.middleware.authentication import (
    AbstractAuthenticationMiddleware,
    AuthenticationResult,
)
from litestar.middleware.base import DefineMiddleware
from litestar.status_codes import (
    HTTP_200_OK,
    HTTP_403_FORBIDDEN,
    HTTP_500_INTERNAL_SERVER_ERROR,
)
from litestar.testing import create_test_client

if TYPE_CHECKING:
    from litestar.connection import ASGIConnection


async def dummy_app(scope: Any, receive: Any, send: Any) -> None:
    return None


@dataclass
class User:
    name: str
    id: int


@dataclass
class Auth:
    props: str


user = User(name="moishe", id=100)
auth = Auth(props="abc")

state: Dict[str, AuthenticationResult] = {}


class AuthMiddleware(AbstractAuthenticationMiddleware):
    async def authenticate_request(self, connection: "ASGIConnection") -> AuthenticationResult:
        param = connection.headers.get("Authorization")
        if param in state:
            return state.pop(param)
        raise PermissionDeniedException("unauthenticated")


def test_authentication_middleware_http_routes() -> None:
    @get(path="/")
    def http_route_handler(request: Request[User, Auth, Any]) -> None:
        assert isinstance(request.user, User)
        assert isinstance(request.auth, Auth)

    client = create_test_client(route_handlers=[http_route_handler], middleware=[AuthMiddleware])
    token = "abc"
    error_response = client.get("/", headers={"Authorization": token})
    assert error_response.status_code == HTTP_403_FORBIDDEN
    state[token] = AuthenticationResult(user=user, auth=auth)
    success_response = client.get("/", headers={"Authorization": token})
    assert success_response.status_code == HTTP_200_OK


def test_authentication_middleware_not_installed_raises_for_user_scope_http() -> None:
    @get(path="/")
    def http_route_handler_user_scope(request: Request[User, None, Any]) -> None:
        assert request.user

    client = create_test_client(route_handlers=[http_route_handler_user_scope])
    error_response = client.get("/", headers={"Authorization": "nope"})
    assert error_response.status_code == HTTP_500_INTERNAL_SERVER_ERROR


def test_authentication_middleware_not_installed_raises_for_auth_scope_http() -> None:
    @get(path="/")
    def http_route_handler_auth_scope(request: Request[None, Auth, Any]) -> None:
        assert request.auth

    client = create_test_client(route_handlers=[http_route_handler_auth_scope])
    error_response = client.get("/", headers={"Authorization": "nope"})
    assert error_response.status_code == HTTP_500_INTERNAL_SERVER_ERROR


@websocket(path="/")
async def websocket_route_handler(socket: WebSocket[User, Auth, Any]) -> None:
    await socket.accept()
    assert isinstance(socket.user, User)
    assert isinstance(socket.auth, Auth)
    assert isinstance(socket.app, Litestar)
    await socket.send_json({"data": "123"})
    await socket.close()


def test_authentication_middleware_websocket_routes() -> None:
    token = "abc"
    client = create_test_client(route_handlers=websocket_route_handler, middleware=[AuthMiddleware])
    with pytest.raises(WebSocketDisconnect), client.websocket_connect("/", headers={"Authorization": token}) as ws:
        assert ws.receive_json()
    state[token] = AuthenticationResult(user=user, auth=auth)
    with client.websocket_connect("/", headers={"Authorization": token}) as ws:
        assert ws.receive_json()


def test_authentication_middleware_not_installed_raises_for_user_scope_websocket() -> None:
    @websocket(path="/")
    async def route_handler(socket: WebSocket[User, Auth, Any]) -> None:
        await socket.accept()
        assert isinstance(socket.user, User)

    client = create_test_client(route_handlers=route_handler)
    with pytest.raises(WebSocketDisconnect), client.websocket_connect("/", headers={"Authorization": "yep"}) as ws:
        ws.receive_json()


def test_authentication_middleware_not_installed_raises_for_auth_scope_websocket() -> None:
    @websocket(path="/")
    async def route_handler(socket: WebSocket[User, Auth, Any]) -> None:
        await socket.accept()
        assert isinstance(socket.auth, Auth)

    client = create_test_client(route_handlers=route_handler)
    with pytest.raises(WebSocketDisconnect), client.websocket_connect("/", headers={"Authorization": "yep"}) as ws:
        ws.receive_json()


def test_authentication_middleware_exclude() -> None:
    auth_mw = DefineMiddleware(AuthMiddleware, exclude=["north", "south"])

    @get("/north/{value:int}")
    def north_handler(value: int) -> Dict[str, int]:
        return {"value": value}

    @get("/south")
    def south_handler() -> None:
        return None

    @get("/west")
    def west_handler() -> None:
        return None

    with create_test_client(
        route_handlers=[north_handler, south_handler, west_handler],
        middleware=[auth_mw],
    ) as client:
        response = client.get("/north/1")
        assert response.status_code == HTTP_200_OK

        response = client.get("/south")
        assert response.status_code == HTTP_200_OK

        response = client.get("/west")
        assert response.status_code == HTTP_403_FORBIDDEN


def test_authentication_middleware_exclude_from_auth() -> None:
    auth_mw = DefineMiddleware(AuthMiddleware, exclude=["south", "east"])

    @get("/north/{value:int}", exclude_from_auth=True)
    def north_handler(value: int) -> Dict[str, int]:
        return {"value": value}

    @get("/south")
    def south_handler() -> None:
        return None

    @get("/west")
    def west_handler() -> None:
        return None

    @get("/east", exclude_from_auth=True)
    def east_handler() -> None:
        return None

    with create_test_client(
        route_handlers=[north_handler, south_handler, west_handler, east_handler],
        middleware=[auth_mw],
    ) as client:
        response = client.get("/north/1")
        assert response.status_code == HTTP_200_OK

        response = client.get("/south")
        assert response.status_code == HTTP_200_OK

        response = client.get("/east")
        assert response.status_code == HTTP_200_OK

        response = client.get("/west")
        assert response.status_code == HTTP_403_FORBIDDEN


def test_authentication_middleware_exclude_from_auth_custom_key() -> None:
    auth_mw = DefineMiddleware(AuthMiddleware, exclude=["south", "east"], exclude_from_auth_key="my_exclude_key")

    @get("/north/{value:int}", my_exclude_key=True)
    def north_handler(value: int) -> Dict[str, int]:
        return {"value": value}

    @get("/south")
    def south_handler() -> None:
        return None

    @get("/west")
    def west_handler() -> None:
        return None

    @get("/east", my_exclude_key=True)
    def east_handler() -> None:
        return None

    with create_test_client(
        route_handlers=[north_handler, south_handler, west_handler, east_handler],
        middleware=[auth_mw],
    ) as client:
        response = client.get("/north/1")
        assert response.status_code == HTTP_200_OK

        response = client.get("/south")
        assert response.status_code == HTTP_200_OK

        response = client.get("/east")
        assert response.status_code == HTTP_200_OK

        response = client.get("/west")
        assert response.status_code == HTTP_403_FORBIDDEN


def test_authentication_exclude_http_methods() -> None:
    auth_mw = DefineMiddleware(AuthMiddleware, exclude_http_methods=[HttpMethod.GET])

    @get("/")
    def exclude_get_handler() -> None:
        return None

    with create_test_client(route_handlers=[exclude_get_handler], middleware=[auth_mw]) as client:
        response = client.get("/")
        assert response.status_code == HTTP_200_OK

        response = client.options("/")
        assert response.status_code == HTTP_403_FORBIDDEN


def test_authentication_exclude_http_methods_default() -> None:
    auth_mw = DefineMiddleware(AuthMiddleware)

    @get("/")
    def exclude_get_handler() -> None:
        return None

    with create_test_client(route_handlers=[exclude_get_handler], middleware=[auth_mw]) as client:
        response = client.get("/")
        assert response.status_code == HTTP_403_FORBIDDEN

        # OPTIONS should be excluded by default
        response = client.options("/")
        assert response.is_success