Skip to content

Commit

Permalink
use client from fixtures in auth tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Leobouloc committed Nov 15, 2023
1 parent 9d8d6eb commit 1fe8b22
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 37 deletions.
47 changes: 29 additions & 18 deletions tests/api/auth/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@
import pytest
from fastapi.exceptions import HTTPException
from fastapi.security import HTTPBasicCredentials
from fastapi.testclient import TestClient

from ralph.api import app
from ralph.api.auth.basic import (
ServerUsersCredentials,
UserCredentials,
Expand All @@ -33,9 +31,6 @@
)


client = TestClient(app)


def test_api_auth_basic_model_serveruserscredentials():
"""Test api.auth ServerUsersCredentials model."""

Expand Down Expand Up @@ -148,23 +143,28 @@ def test_api_auth_basic_no_credential_file_found(fs, monkeypatch):
get_basic_auth_user(credentials)


def test_api_auth_basic_get_whoami_no_credentials():
@pytest.mark.anyio
async def test_api_auth_basic_get_whoami_no_credentials(client):
"""Whoami route returns a 401 error when no credentials are sent."""
response = client.get("/whoami")
response = await client.get("/whoami")
assert response.status_code == 401
assert response.headers["www-authenticate"] == "Basic"
assert response.json() == {"detail": "Invalid authentication credentials"}


def test_api_auth_basic_get_whoami_credentials_encoding_error():
@pytest.mark.anyio
async def test_api_auth_basic_get_whoami_credentials_encoding_error(client):
"""Whoami route returns a 401 error when the credentials encoding is broken."""
response = client.get("/whoami", headers={"Authorization": "Basic not-base64"})
response = await client.get(
"/whoami", headers={"Authorization": "Basic not-base64"}
)
assert response.status_code == 401
assert response.headers["www-authenticate"] == "Basic"
assert response.json() == {"detail": "Invalid authentication credentials"}


def test_api_auth_basic_get_whoami_username_not_found(fs):
@pytest.mark.anyio
async def test_api_auth_basic_get_whoami_username_not_found(fs, client):
"""Whoami route returns a 401 error when the username cannot be found."""
credential_bytes = base64.b64encode("john:admin".encode("utf-8"))
credentials = str(credential_bytes, "utf-8")
Expand All @@ -173,14 +173,17 @@ def test_api_auth_basic_get_whoami_username_not_found(fs):
auth_file_path = settings.APP_DIR / "auth.json"
fs.create_file(auth_file_path, contents=STORED_CREDENTIALS)

response = client.get("/whoami", headers={"Authorization": f"Basic {credentials}"})
response = await client.get(
"/whoami", headers={"Authorization": f"Basic {credentials}"}
)

assert response.status_code == 401
assert response.headers["www-authenticate"] == "Basic"
assert response.json() == {"detail": "Invalid authentication credentials"}


def test_api_auth_basic_get_whoami_wrong_password(fs):
@pytest.mark.anyio
async def test_api_auth_basic_get_whoami_wrong_password(fs, client):
"""Whoami route returns a 401 error when the password is wrong."""
credential_bytes = base64.b64encode("john:not-admin".encode("utf-8"))
credentials = str(credential_bytes, "utf-8")
Expand All @@ -189,18 +192,21 @@ def test_api_auth_basic_get_whoami_wrong_password(fs):
fs.create_file(auth_file_path, contents=STORED_CREDENTIALS)
get_basic_auth_user.cache_clear()

response = client.get("/whoami", headers={"Authorization": f"Basic {credentials}"})
response = await client.get(
"/whoami", headers={"Authorization": f"Basic {credentials}"}
)

assert response.status_code == 401
assert response.json() == {"detail": "Invalid authentication credentials"}


@pytest.mark.anyio
@pytest.mark.parametrize(
"runserver_auth_backends",
[[AuthBackend.BASIC, AuthBackend.OIDC], [AuthBackend.BASIC]],
)
def test_api_auth_basic_get_whoami_correct_credentials(
fs, monkeypatch, runserver_auth_backends
async def test_api_auth_basic_get_whoami_correct_credentials(
fs, monkeypatch, runserver_auth_backends, client
):
"""Whoami returns a 200 response when the credentials are correct.
Expand All @@ -215,7 +221,9 @@ def test_api_auth_basic_get_whoami_correct_credentials(
fs.create_file(auth_file_path, contents=STORED_CREDENTIALS)
get_basic_auth_user.cache_clear()

response = client.get("/whoami", headers={"Authorization": f"Basic {credentials}"})
response = await client.get(
"/whoami", headers={"Authorization": f"Basic {credentials}"}
)

assert response.status_code == 200

Expand All @@ -227,7 +235,8 @@ def test_api_auth_basic_get_whoami_correct_credentials(
]


def test_api_auth_basic_get_whoami_invalid_backend(fs, monkeypatch):
@pytest.mark.anyio
async def test_api_auth_basic_get_whoami_invalid_backend(fs, monkeypatch, client):
"""Check for an exception when providing valid credentials when Basic
authentication is not supported.
"""
Expand All @@ -240,7 +249,9 @@ def test_api_auth_basic_get_whoami_invalid_backend(fs, monkeypatch):
fs.create_file(auth_file_path, contents=STORED_CREDENTIALS)
get_basic_auth_user.cache_clear()

response = client.get("/whoami", headers={"Authorization": f"Basic {credentials}"})
response = await client.get(
"/whoami", headers={"Authorization": f"Basic {credentials}"}
)

assert response.status_code == 401
assert response.json() == {"detail": "Invalid authentication credentials"}
42 changes: 24 additions & 18 deletions tests/api/auth/test_oidc.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,33 @@
"""Tests for the api.auth.oidc module."""
import pytest
import responses
from fastapi.testclient import TestClient
from pydantic import parse_obj_as

from ralph.api import app
from ralph.api.auth.oidc import discover_provider, get_public_keys
from ralph.conf import AuthBackend
from ralph.models.xapi.base.agents import BaseXapiAgentWithOpenId

from tests.fixtures.auth import ISSUER_URI, mock_oidc_user
from tests.helpers import configure_env_for_mock_oidc_auth

client = TestClient(app)


@pytest.mark.anyio
@pytest.mark.parametrize(
"runserver_auth_backends",
[[AuthBackend.BASIC, AuthBackend.OIDC], [AuthBackend.OIDC]],
)
@responses.activate
def test_api_auth_oidc_get_whoami_valid(monkeypatch, runserver_auth_backends):
async def test_api_auth_oidc_get_whoami_valid(
client, monkeypatch, runserver_auth_backends
):
"""Test a valid OpenId Connect authentication."""

configure_env_for_mock_oidc_auth(monkeypatch, runserver_auth_backends)

oidc_token = mock_oidc_user(scopes=["all", "profile/read"])

headers = {"Authorization": f"Bearer {oidc_token}"}
response = client.get(
response = await client.get(
"/whoami",
headers=headers,
)
Expand All @@ -39,17 +38,18 @@ def test_api_auth_oidc_get_whoami_valid(monkeypatch, runserver_auth_backends):
assert sorted(response.json()["scopes"]) == ["all", "profile/read"]


@pytest.mark.anyio
@responses.activate
def test_api_auth_oidc_get_whoami_invalid_token(
monkeypatch, mock_discovery_response, mock_oidc_jwks
async def test_api_auth_oidc_get_whoami_invalid_token(
client, monkeypatch, mock_discovery_response, mock_oidc_jwks
):
"""Test API with an invalid audience."""

configure_env_for_mock_oidc_auth(monkeypatch)

mock_oidc_user()

response = client.get(
response = await client.get(
"/whoami",
headers={"Authorization": "Bearer wrong_token"},
)
Expand All @@ -59,8 +59,11 @@ def test_api_auth_oidc_get_whoami_invalid_token(
assert response.json() == {"detail": "Could not validate credentials"}


@pytest.mark.anyio
@responses.activate
def test_api_auth_oidc_get_whoami_invalid_discovery(monkeypatch, encoded_token):
async def test_api_auth_oidc_get_whoami_invalid_discovery(
client, monkeypatch, encoded_token
):
"""Test API with an invalid provider discovery."""

configure_env_for_mock_oidc_auth(monkeypatch)
Expand All @@ -77,7 +80,7 @@ def test_api_auth_oidc_get_whoami_invalid_discovery(monkeypatch, encoded_token):
status=500,
)

response = client.get(
response = await client.get(
"/whoami",
headers={"Authorization": f"Bearer {encoded_token}"},
)
Expand All @@ -87,9 +90,10 @@ def test_api_auth_oidc_get_whoami_invalid_discovery(monkeypatch, encoded_token):
assert response.json() == {"detail": "Could not validate credentials"}


@pytest.mark.anyio
@responses.activate
def test_api_auth_oidc_get_whoami_invalid_keys(
monkeypatch, mock_discovery_response, mock_oidc_jwks, encoded_token
async def test_api_auth_oidc_get_whoami_invalid_keys(
client, monkeypatch, mock_discovery_response, mock_oidc_jwks, encoded_token
):
"""Test API with an invalid request for keys."""

Expand All @@ -115,7 +119,7 @@ def test_api_auth_oidc_get_whoami_invalid_keys(
status=500,
)

response = client.get(
response = await client.get(
"/whoami",
headers={"Authorization": f"Bearer {encoded_token}"},
)
Expand All @@ -125,15 +129,16 @@ def test_api_auth_oidc_get_whoami_invalid_keys(
assert response.json() == {"detail": "Could not validate credentials"}


@pytest.mark.anyio
@responses.activate
def test_api_auth_oidc_get_whoami_invalid_header(monkeypatch):
async def test_api_auth_oidc_get_whoami_invalid_header(client, monkeypatch):
"""Test API with an invalid request header."""

configure_env_for_mock_oidc_auth(monkeypatch)

oidc_token = mock_oidc_user()

response = client.get(
response = await client.get(
"/whoami",
headers={"Authorization": f"Wrong header {oidc_token}"},
)
Expand All @@ -143,7 +148,8 @@ def test_api_auth_oidc_get_whoami_invalid_header(monkeypatch):
assert response.json() == {"detail": "Invalid authentication credentials"}


def test_api_auth_oidc_get_whoami_invalid_backend(fs, monkeypatch):
@pytest.mark.anyio
async def test_api_auth_oidc_get_whoami_invalid_backend(client, fs, monkeypatch):
"""Check for an exception when providing valid OIDC credentials while
OIDC authentication is not supported.
"""
Expand All @@ -153,7 +159,7 @@ def test_api_auth_oidc_get_whoami_invalid_backend(fs, monkeypatch):
oidc_token = mock_oidc_user(scopes=["all", "profile/read"])

headers = {"Authorization": f"Bearer {oidc_token}"}
response = client.get(
response = await client.get(
"/whoami",
headers=headers,
)
Expand Down
2 changes: 1 addition & 1 deletion tests/api/test_statements_post.py
Original file line number Diff line number Diff line change
Expand Up @@ -720,7 +720,7 @@ async def test_api_statements_post_scopes( # noqa: PLR0913
oidc_token = mock_oidc_user(sub=sub, scopes=scopes)
headers = {"Authorization": f"Bearer {oidc_token}"}

monkeypatch.setenv("RUNSERVER_AUTH_BACKENDS", [AuthBackend.OIDC])
monkeypatch.setenv("RUNSERVER_AUTH_BACKENDS", "oidc")
monkeypatch.setattr(
"ralph.api.auth.settings.RUNSERVER_AUTH_BACKENDS", [AuthBackend.OIDC]
)
Expand Down

0 comments on commit 1fe8b22

Please sign in to comment.