-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtest_guard.py
More file actions
210 lines (178 loc) · 6.16 KB
/
Copy pathtest_guard.py
File metadata and controls
210 lines (178 loc) · 6.16 KB
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
import pytest
from starlette.status import HTTP_401_UNAUTHORIZED
from ellar.common import Req, get, guards
from ellar.core import AppFactory, TestClient
from ellar.core.guard import (
APIKeyCookie,
APIKeyHeader,
APIKeyQuery,
HttpBasicAuth,
HttpBearerAuth,
HttpDigestAuth,
)
from ellar.exceptions import APIException
from ellar.openapi import OpenAPIDocumentBuilder
from ellar.serializer import serialize_object
class CustomException(APIException):
pass
class QuerySecretKey(APIKeyQuery):
async def authenticate(self, connection, key):
if key == "querysecretkey":
return key
class HeaderSecretKey(APIKeyHeader):
async def authenticate(self, connection, key):
if key == "headersecretkey":
return key
class HeaderSecretKeyCustomException(HeaderSecretKey):
exception_class = CustomException
class CookieSecretKey(APIKeyCookie):
openapi_name = "API Key Auth"
async def authenticate(self, connection, key):
if key == "cookiesecretkey":
return key
class BasicAuth(HttpBasicAuth):
openapi_name = "API Authentication"
async def authenticate(self, connection, credentials):
if credentials.username == "admin" and credentials.password == "secret":
return credentials.username
class BearerAuth(HttpBearerAuth):
openapi_name = "JWT Authentication"
async def authenticate(self, connection, credentials):
if credentials.credentials == "bearertoken":
return credentials.credentials
class DigestAuth(HttpDigestAuth):
async def authenticate(self, connection, credentials):
if credentials.credentials == "digesttoken":
return credentials.credentials
app = AppFactory.create_app()
for _path, auth in [
("apikeyquery", QuerySecretKey()),
("apikeyheader", HeaderSecretKey()),
("apikeycookie", CookieSecretKey()),
("basic", BasicAuth()),
("bearer", BearerAuth()),
("digest", DigestAuth()),
("customexception", HeaderSecretKeyCustomException()),
]:
@get(f"/{_path}")
@guards(auth)
def auth_demo_endpoint(request: Req()):
return {"authentication": request.user}
app.router.append(auth_demo_endpoint)
client = TestClient(app)
BODY_UNAUTHORIZED_DEFAULT = {"detail": "Not authenticated"}
@pytest.mark.parametrize(
"path,kwargs,expected_code,expected_body",
[
("/apikeyquery", {}, HTTP_401_UNAUTHORIZED, BODY_UNAUTHORIZED_DEFAULT),
(
"/apikeyquery?key=querysecretkey",
{},
200,
dict(authentication="querysecretkey"),
),
("/apikeyheader", {}, HTTP_401_UNAUTHORIZED, BODY_UNAUTHORIZED_DEFAULT),
(
"/apikeyheader",
dict(headers={"key": "headersecretkey"}),
200,
dict(authentication="headersecretkey"),
),
("/apikeycookie", {}, HTTP_401_UNAUTHORIZED, BODY_UNAUTHORIZED_DEFAULT),
(
"/apikeycookie",
dict(cookies={"key": "cookiesecretkey"}),
200,
dict(authentication="cookiesecretkey"),
),
("/basic", {}, HTTP_401_UNAUTHORIZED, BODY_UNAUTHORIZED_DEFAULT),
(
"/basic",
dict(headers={"Authorization": "Basic YWRtaW46c2VjcmV0"}),
200,
dict(authentication="admin"),
),
(
"/basic",
dict(headers={"Authorization": "YWRtaW46c2VjcmV0"}),
200,
dict(authentication="admin"),
),
(
"/basic",
dict(headers={"Authorization": "Basic invalid"}),
HTTP_401_UNAUTHORIZED,
{"detail": "Invalid authentication credentials"},
),
(
"/basic",
dict(headers={"Authorization": "some invalid value"}),
HTTP_401_UNAUTHORIZED,
BODY_UNAUTHORIZED_DEFAULT,
),
("/bearer", {}, 401, BODY_UNAUTHORIZED_DEFAULT),
(
"/bearer",
dict(headers={"Authorization": "Bearer bearertoken"}),
200,
dict(authentication="bearertoken"),
),
(
"/bearer",
dict(headers={"Authorization": "Invalid bearertoken"}),
HTTP_401_UNAUTHORIZED,
{"detail": "Invalid authentication credentials"},
),
("/digest", {}, 401, BODY_UNAUTHORIZED_DEFAULT),
(
"/digest",
dict(headers={"Authorization": "Digest digesttoken"}),
200,
dict(authentication="digesttoken"),
),
(
"/digest",
dict(headers={"Authorization": "Invalid digesttoken"}),
HTTP_401_UNAUTHORIZED,
{"detail": "Invalid authentication credentials"},
),
("/customexception", {}, HTTP_401_UNAUTHORIZED, BODY_UNAUTHORIZED_DEFAULT),
(
"/customexception",
dict(headers={"key": "headersecretkey"}),
200,
dict(authentication="headersecretkey"),
),
],
)
def test_auth(path, kwargs, expected_code, expected_body):
response = client.get(path, **kwargs)
assert response.status_code == expected_code
assert response.json() == expected_body
def test_auth_schema():
document = serialize_object(OpenAPIDocumentBuilder().build_document(app))
assert document["components"]["securitySchemes"] == {
"API Key Auth": {"type": "apiKey", "in": "cookie", "name": "API Key Auth"},
"HeaderSecretKey": {
"type": "apiKey",
"in": "header",
"name": "HeaderSecretKey",
},
"QuerySecretKey": {"type": "apiKey", "in": "query", "name": "QuerySecretKey"},
"API Authentication": {
"type": "http",
"scheme": "basic",
"name": "API Authentication",
},
"JWT Authentication": {
"type": "http",
"scheme": "bearer",
"name": "JWT Authentication",
},
"HeaderSecretKeyCustomException": {
"type": "apiKey",
"in": "header",
"name": "HeaderSecretKeyCustomException",
},
"DigestAuth": {"type": "http", "scheme": "digest", "name": "DigestAuth"},
}