| 1 |
from unittest.mock import Mock |
| 2 |
|
| 3 |
import pytest |
| 4 |
from django.utils.asyncio import async_unsafe |
| 5 |
|
| 6 |
from ninja import NinjaAPI |
| 7 |
from ninja.errors import AuthorizationError, ConfigError |
| 8 |
from ninja.security import ( |
| 9 |
APIKeyCookie, |
| 10 |
APIKeyHeader, |
| 11 |
APIKeyQuery, |
| 12 |
HttpBasicAuth, |
| 13 |
HttpBearer, |
| 14 |
django_auth, |
| 15 |
django_auth_is_staff, |
| 16 |
django_auth_superuser, |
| 17 |
) |
| 18 |
from ninja.security.base import AuthBase |
| 19 |
from ninja.testing import TestClient |
| 20 |
from ninja.testing.client import TestAsyncClient |
| 21 |
|
| 22 |
|
| 23 |
def callable_auth(request): |
| 24 |
return request.GET.get("auth") |
| 25 |
|
| 26 |
|
| 27 |
class KeyQuery(APIKeyQuery): |
| 28 |
def authenticate(self, request, key): |
| 29 |
if key == "keyquerysecret": |
| 30 |
return key |
| 31 |
|
| 32 |
|
| 33 |
class KeyHeader(APIKeyHeader): |
| 34 |
def authenticate(self, request, key): |
| 35 |
if key == "keyheadersecret": |
| 36 |
return key |
| 37 |
|
| 38 |
|
| 39 |
class CustomException(Exception): |
| 40 |
pass |
| 41 |
|
| 42 |
|
| 43 |
class KeyHeaderCustomException(APIKeyHeader): |
| 44 |
def authenticate(self, request, key): |
| 45 |
if key != "keyheadersecret": |
| 46 |
raise CustomException |
| 47 |
return key |
| 48 |
|
| 49 |
|
| 50 |
class KeyCookie(APIKeyCookie): |
| 51 |
def authenticate(self, request, key): |
| 52 |
if key == "keycookiersecret": |
| 53 |
return key |
| 54 |
|
| 55 |
|
| 56 |
class BasicAuth(HttpBasicAuth): |
| 57 |
def authenticate(self, request, username, password): |
| 58 |
if username == "admin" and password == "secret": |
| 59 |
return username |
| 60 |
|
| 61 |
|
| 62 |
class BearerAuth(HttpBearer): |
| 63 |
def authenticate(self, request, token): |
| 64 |
if token == "bearertoken": |
| 65 |
return token |
| 66 |
if token == "nottherightone": |
| 67 |
raise AuthorizationError |
| 68 |
|
| 69 |
|
| 70 |
class AsyncBearerAuth(HttpBearer): |
| 71 |
""" |
| 72 |
This one is async but in fact no awaits inside authenticate |
| 73 |
which led to an await error |
| 74 |
""" |
| 75 |
|
| 76 |
async def authenticate(self, request, token): |
| 77 |
if token == "bearertoken": |
| 78 |
return token |
| 79 |
if token == "nottherightone": |
| 80 |
raise AuthorizationError |
| 81 |
|
| 82 |
|
| 83 |
def demo_operation(request): |
| 84 |
return {"auth": request.auth} |
| 85 |
|
| 86 |
|
| 87 |
api = NinjaAPI() |
| 88 |
|
| 89 |
|
| 90 |
@api.exception_handler(CustomException) |
| 91 |
def on_custom_error(request, exc): |
| 92 |
return api.create_response(request, {"custom": True}, status=401) |
| 93 |
|
| 94 |
|
| 95 |
for path, auth in [ |
| 96 |
("django_auth", django_auth), |
| 97 |
("django_auth_superuser", django_auth_superuser), |
| 98 |
("django_auth_is_staff", django_auth_is_staff), |
| 99 |
("callable", callable_auth), |
| 100 |
("apikeyquery", KeyQuery()), |
| 101 |
("apikeyheader", KeyHeader()), |
| 102 |
("apikeycookie", KeyCookie()), |
| 103 |
("basic", BasicAuth()), |
| 104 |
("bearer", BearerAuth()), |
| 105 |
("async_bearer", AsyncBearerAuth()), |
| 106 |
("customexception", KeyHeaderCustomException()), |
| 107 |
]: |
| 108 |
api.get(f"/{path}", auth=auth, operation_id=path)(demo_operation) |
| 109 |
|
| 110 |
|
| 111 |
client = TestClient(api) |
| 112 |
|
| 113 |
|
| 114 |
class MockUser(str): |
| 115 |
is_authenticated = True |
| 116 |
is_superuser = False |
| 117 |
is_staff = False |
| 118 |
|
| 119 |
|
| 120 |
class MockSuperUser(str): |
| 121 |
is_authenticated = True |
| 122 |
is_superuser = True |
| 123 |
is_staff = True |
| 124 |
|
| 125 |
|
| 126 |
class MockStaffUser(str): |
| 127 |
is_authenticated = True |
| 128 |
is_superuser = False |
| 129 |
is_staff = True |
| 130 |
|
| 131 |
|
| 132 |
BODY_UNAUTHORIZED_DEFAULT = dict(detail="Unauthorized") |
| 133 |
BODY_FORBIDDEN_DEFAULT = dict(detail="Forbidden") |
| 134 |
|
| 135 |
|
| 136 |
@pytest.mark.parametrize( |
| 137 |
"path,kwargs,expected_code,expected_body", |
| 138 |
[ |
| 139 |
("/django_auth", {}, 401, BODY_UNAUTHORIZED_DEFAULT), |
| 140 |
("/django_auth", dict(user=MockUser("admin")), 200, dict(auth="admin")), |
| 141 |
("/django_auth_superuser", {}, 401, BODY_UNAUTHORIZED_DEFAULT), |
| 142 |
( |
| 143 |
"/django_auth_superuser", |
| 144 |
dict(user=MockUser("admin")), |
| 145 |
401, |
| 146 |
BODY_UNAUTHORIZED_DEFAULT, |
| 147 |
), |
| 148 |
( |
| 149 |
"/django_auth_superuser", |
| 150 |
dict(user=MockSuperUser("admin")), |
| 151 |
200, |
| 152 |
dict(auth="admin"), |
| 153 |
), |
| 154 |
("/django_auth_is_staff", {}, 401, BODY_UNAUTHORIZED_DEFAULT), |
| 155 |
( |
| 156 |
"/django_auth_is_staff", |
| 157 |
dict(user=MockUser("admin")), |
| 158 |
401, |
| 159 |
BODY_UNAUTHORIZED_DEFAULT, |
| 160 |
), |
| 161 |
( |
| 162 |
"/django_auth_is_staff", |
| 163 |
dict(user=MockSuperUser("admin")), |
| 164 |
200, |
| 165 |
dict(auth="admin"), |
| 166 |
), |
| 167 |
( |
| 168 |
"/django_auth_is_staff", |
| 169 |
dict(user=MockStaffUser("admin")), |
| 170 |
200, |
| 171 |
dict(auth="admin"), |
| 172 |
), |
| 173 |
("/callable", {}, 401, BODY_UNAUTHORIZED_DEFAULT), |
| 174 |
("/callable?auth=demo", {}, 200, dict(auth="demo")), |
| 175 |
("/apikeyquery", {}, 401, BODY_UNAUTHORIZED_DEFAULT), |
| 176 |
("/apikeyquery?key=keyquerysecret", {}, 200, dict(auth="keyquerysecret")), |
| 177 |
("/apikeyheader", {}, 401, BODY_UNAUTHORIZED_DEFAULT), |
| 178 |
( |
| 179 |
"/apikeyheader", |
| 180 |
dict(headers={"key": "keyheadersecret"}), |
| 181 |
200, |
| 182 |
dict(auth="keyheadersecret"), |
| 183 |
), |
| 184 |
("/apikeycookie", {}, 401, BODY_UNAUTHORIZED_DEFAULT), |
| 185 |
( |
| 186 |
"/apikeycookie", |
| 187 |
dict(COOKIES={"key": "keycookiersecret"}), |
| 188 |
200, |
| 189 |
dict(auth="keycookiersecret"), |
| 190 |
), |
| 191 |
("/basic", {}, 401, BODY_UNAUTHORIZED_DEFAULT), |
| 192 |
( |
| 193 |
"/basic", |
| 194 |
dict(headers={"Authorization": "Basic YWRtaW46c2VjcmV0"}), |
| 195 |
200, |
| 196 |
dict(auth="admin"), |
| 197 |
), |
| 198 |
( |
| 199 |
"/basic", |
| 200 |
dict(headers={"Authorization": "YWRtaW46c2VjcmV0"}), |
| 201 |
200, |
| 202 |
dict(auth="admin"), |
| 203 |
), |
| 204 |
( |
| 205 |
"/basic", |
| 206 |
dict(headers={"Authorization": "Basic invalid"}), |
| 207 |
401, |
| 208 |
BODY_UNAUTHORIZED_DEFAULT, |
| 209 |
), |
| 210 |
( |
| 211 |
"/basic", |
| 212 |
dict(headers={"Authorization": "some invalid value"}), |
| 213 |
401, |
| 214 |
BODY_UNAUTHORIZED_DEFAULT, |
| 215 |
), |
| 216 |
("/bearer", {}, 401, BODY_UNAUTHORIZED_DEFAULT), |
| 217 |
( |
| 218 |
"/bearer", |
| 219 |
dict(headers={"Authorization": "Bearer bearertoken"}), |
| 220 |
200, |
| 221 |
dict(auth="bearertoken"), |
| 222 |
), |
| 223 |
( |
| 224 |
"/bearer", |
| 225 |
dict(headers={"Authorization": "Invalid bearertoken"}), |
| 226 |
401, |
| 227 |
BODY_UNAUTHORIZED_DEFAULT, |
| 228 |
), |
| 229 |
( |
| 230 |
"/bearer", |
| 231 |
dict(headers={"Authorization": "Bearer nonexistingtoken"}), |
| 232 |
401, |
| 233 |
BODY_UNAUTHORIZED_DEFAULT, |
| 234 |
), |
| 235 |
( |
| 236 |
"/async_bearer", |
| 237 |
dict(headers={"Authorization": "Bearer nonexistingtoken"}), |
| 238 |
401, |
| 239 |
BODY_UNAUTHORIZED_DEFAULT, |
| 240 |
), |
| 241 |
( |
| 242 |
"/async_bearer", |
| 243 |
dict(headers={}), |
| 244 |
401, |
| 245 |
BODY_UNAUTHORIZED_DEFAULT, |
| 246 |
), |
| 247 |
( |
| 248 |
"/bearer", |
| 249 |
dict(headers={"Authorization": "Bearer nottherightone"}), |
| 250 |
403, |
| 251 |
BODY_FORBIDDEN_DEFAULT, |
| 252 |
), |
| 253 |
("/customexception", {}, 401, dict(custom=True)), |
| 254 |
( |
| 255 |
"/customexception", |
| 256 |
dict(headers={"key": "keyheadersecret"}), |
| 257 |
200, |
| 258 |
dict(auth="keyheadersecret"), |
| 259 |
), |
| 260 |
], |
| 261 |
) |
| 262 |
def test_auth(path, kwargs, expected_code, expected_body, settings): |
| 263 |
for debug in (False, True): |
| 264 |
settings.DEBUG = debug |
| 265 |
response = client.get(path, **kwargs) |
| 266 |
assert response.status_code == expected_code |
| 267 |
assert response.json() == expected_body |
| 268 |
|
| 269 |
|
| 270 |
def test_schema(): |
| 271 |
schema = api.get_openapi_schema() |
| 272 |
assert schema["components"]["securitySchemes"] == { |
| 273 |
"BasicAuth": {"scheme": "basic", "type": "http"}, |
| 274 |
"BearerAuth": {"scheme": "bearer", "type": "http"}, |
| 275 |
"AsyncBearerAuth": {"scheme": "bearer", "type": "http"}, |
| 276 |
"KeyCookie": {"in": "cookie", "name": "key", "type": "apiKey"}, |
| 277 |
"KeyHeader": {"in": "header", "name": "key", "type": "apiKey"}, |
| 278 |
"KeyHeaderCustomException": {"in": "header", "name": "key", "type": "apiKey"}, |
| 279 |
"KeyQuery": {"in": "query", "name": "key", "type": "apiKey"}, |
| 280 |
"SessionAuth": {"in": "cookie", "name": "sessionid", "type": "apiKey"}, |
| 281 |
"SessionAuthSuperUser": {"in": "cookie", "name": "sessionid", "type": "apiKey"}, |
| 282 |
"SessionAuthIsStaff": {"in": "cookie", "name": "sessionid", "type": "apiKey"}, |
| 283 |
} |
| 284 |
|
| 285 |
|
| 286 |
|
| 287 |
|
| 288 |
def test_invalid_setup(): |
| 289 |
request = Mock() |
| 290 |
headers = {"Authorization": "Bearer test"} |
| 291 |
request.META = {"HTTP_" + k: v for k, v in headers.items()} |
| 292 |
request.headers = headers |
| 293 |
|
| 294 |
class MyAuth1(AuthBase): |
| 295 |
def __call__(self, *args, **kwargs): |
| 296 |
pass |
| 297 |
|
| 298 |
class MyAuth2(AuthBase): |
| 299 |
openapi_type = "my" |
| 300 |
|
| 301 |
with pytest.raises(ConfigError): |
| 302 |
MyAuth1()(request) |
| 303 |
with pytest.raises(TypeError): |
| 304 |
MyAuth2()(request) |
| 305 |
with pytest.raises(TypeError): |
| 306 |
APIKeyCookie()(request) |
| 307 |
with pytest.raises(TypeError): |
| 308 |
APIKeyHeader()(request) |
| 309 |
with pytest.raises(TypeError): |
| 310 |
APIKeyQuery()(request) |
| 311 |
with pytest.raises(TypeError): |
| 312 |
HttpBearer()(request) |
| 313 |
|
| 314 |
headers = {"Authorization": "Basic YWRtaW46c2VjcmV0"} |
| 315 |
request.META = {"HTTP_" + k: v for k, v in headers.items()} |
| 316 |
request.headers = headers |
| 317 |
|
| 318 |
with pytest.raises(TypeError): |
| 319 |
HttpBasicAuth()(request) |
| 320 |
|
| 321 |
|
| 322 |
@pytest.mark.asyncio |
| 323 |
async def test_async_auth(): |
| 324 |
_sync_auth_called = False |
| 325 |
_async_auth_called = False |
| 326 |
_async_unsafe_func_called = False |
| 327 |
|
| 328 |
|
| 329 |
|
| 330 |
|
| 331 |
@async_unsafe("called without sync_to_async") |
| 332 |
def async_unsafe_function(): |
| 333 |
nonlocal _async_unsafe_func_called |
| 334 |
_async_unsafe_func_called = True |
| 335 |
|
| 336 |
class AsyncAuth(APIKeyQuery): |
| 337 |
async def authenticate(self, request, key): |
| 338 |
nonlocal _async_auth_called |
| 339 |
_async_auth_called = True |
| 340 |
return False |
| 341 |
|
| 342 |
class SyncAuth(APIKeyQuery): |
| 343 |
def authenticate(self, request, key): |
| 344 |
async_unsafe_function() |
| 345 |
nonlocal _sync_auth_called |
| 346 |
_sync_auth_called = True |
| 347 |
return True |
| 348 |
|
| 349 |
async def handle_request(request): |
| 350 |
return {"ok": True} |
| 351 |
|
| 352 |
api = NinjaAPI() |
| 353 |
api.get("/foobar", auth=[AsyncAuth(), SyncAuth()])(handle_request) |
| 354 |
|
| 355 |
client = TestAsyncClient(api) |
| 356 |
response = await client.get("/foobar") |
| 357 |
assert response.status_code == 200 |
| 358 |
assert response.json() == {"ok": True} |
| 359 |
|
| 360 |
assert _sync_auth_called is True |
| 361 |
assert _async_auth_called is True |
| 362 |
assert _async_unsafe_func_called is True |