Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add simple response #214

Merged
merged 1 commit into from
Jul 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions testsuite/objects/sections.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,7 @@ class Responses(abc.ABC):
@abc.abstractmethod
def add(self, response, **common_features):
"""Add response to AuthConfig"""

@abc.abstractmethod
def add_simple(self, auth_json, name="auth-json", key="data", **common_features):
"""Add simple response to AuthConfig"""
3 changes: 3 additions & 0 deletions testsuite/openshift/objects/auth_config/sections.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,9 @@ def uma_metadata(self, name, endpoint, credentials, **common_features):
class ResponsesSection(Section, Responses):
"""Section which contains response configuration"""

def add_simple(self, auth_json, name="simple", key="data", **common_features):
averevki marked this conversation as resolved.
Show resolved Hide resolved
self.add({"name": name, "json": {"properties": [{"name": key, "valueFrom": {"authJSON": auth_json}}]}})

@modify
def add(self, response, **common_features):
"""Adds response section to AuthConfig."""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ def expectation_path(mockserver, module_label):
@pytest.fixture(scope="module")
def authorization(authorization):
"""Adds `aut.metadata` to the AuthJson"""
authorization.responses.add(
{"name": "auth-json", "json": {"properties": [{"name": "auth", "valueFrom": {"authJSON": "auth.metadata"}}]}}
)
authorization.responses.add_simple("auth.metadata")
return authorization


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import pytest

from testsuite.objects import Cache, Value
from testsuite.utils import extract_from_response
from testsuite.utils import extract_response


@pytest.fixture(scope="module")
Expand All @@ -28,21 +28,25 @@ def test_cached(client, auth, module_label, mockserver):
- only single external value evaluation occurs. The second response contains cached (in-memory) value
"""
response = client.get("/get", auth=auth)
data = extract_from_response(response, module_label, "uuid")
data = extract_response(response)[module_label]["uuid"] % None
response = client.get("/get", auth=auth)
cached_data = extract_from_response(response, module_label, "uuid")
cached_data = extract_response(response)[module_label]["uuid"] % None

assert cached_data is not None
assert data is not None
assert data == cached_data
assert len(mockserver.retrieve_requests(module_label)) == 1


def test_cached_ttl(client, auth, module_label, cache_ttl, mockserver):
"""Tests that cached value expires after ttl"""
response = client.get("/get", auth=auth)
data = extract_from_response(response, module_label, "uuid")
data = extract_response(response)[module_label]["uuid"] % None
sleep(cache_ttl)
response = client.get("/get", auth=auth)
cached_data = extract_from_response(response, module_label, "uuid")
cached_data = extract_response(response)[module_label]["uuid"] % None

assert cached_data is not None
assert data is not None
assert data != cached_data
pehala marked this conversation as resolved.
Show resolved Hide resolved
assert len(mockserver.retrieve_requests(module_label)) == 2
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Tests for metadata without caching feature"""
import pytest

from testsuite.utils import extract_from_response
from testsuite.utils import extract_response


@pytest.fixture(scope="module")
Expand All @@ -13,9 +13,13 @@ def authorization(authorization, module_label, expectation_path):

def test_no_caching(client, auth, module_label, mockserver):
"""Tests value is not cached for metadata without caching feature"""
response = client.get("/get", auth=auth)
data = extract_from_response(response, module_label, "uuid")
response = client.get("/get", auth=auth)
response1 = client.get("/get", auth=auth)
data = extract_response(response1)[module_label]["uuid"] % None

assert extract_from_response(response, module_label, "uuid") != data
response2 = client.get("/get", auth=auth)
cached_data = extract_response(response2)[module_label]["uuid"] % None

assert cached_data is not None
assert data is not None
assert cached_data != data
assert len(mockserver.retrieve_requests(module_label)) == 2
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@
import pytest

from testsuite.objects import Rule
from testsuite.utils import extract_from_response
from testsuite.utils import extract_response


@pytest.fixture(scope="module")
def authorization(authorization):
"""Add to the AuthConfig response, which will only trigger on POST requests"""
authorization.responses.add(
{
"name": "auth-json",
"name": "simple",
"json": {
"properties": [
{"name": "auth", "value": "response"},
{"name": "data", "value": "response"},
]
},
},
Expand All @@ -31,10 +31,10 @@ def test_skip_response(client, auth):
assert response.status_code == 200

# verify that response was not returned on a GET request
with pytest.raises(KeyError, match="Auth-Json"):
extract_from_response(response)
assert "simple" not in response.json()["headers"]
Copy link
Contributor

@azgabur azgabur Nov 9, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found a bug. This string should be Simple because HTTP headers capitalize first letter of header name. As this PR is already merged, can you create a new small one with this fix @pehala ? Opened #272


response = client.post("/post", auth=auth)
assert response.status_code == 200
# verify that response is returned on a POST request
assert extract_from_response(response)
value = extract_response(response) % None
assert value == "response"
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
"""Test for anonymous identity context"""
import json

import pytest

from testsuite.utils import extract_response


@pytest.fixture(scope="module")
def authorization(authorization):
"""Setup AuthConfig for test"""
authorization.identity.anonymous("anonymous")
authorization.responses.add(
{
"name": "auth-json",
"json": {"properties": [{"name": "auth", "valueFrom": {"authJSON": "auth.identity.anonymous"}}]},
}
)
authorization.responses.add_simple("auth.identity.anonymous")
return authorization


Expand All @@ -25,4 +20,4 @@ def test_anonymous_context(client):
"""
response = client.get("/get")
assert response.status_code == 200
assert json.loads(response.json()["headers"]["Auth-Json"])["auth"]
assert extract_response(response) % None
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
"""Test for API key identity context"""
import json

import pytest

from testsuite.utils import extract_response


@pytest.fixture(scope="module")
def authorization(authorization, module_label):
"""Setup AuthConfig for test"""
authorization.identity.api_key("api_key", match_label=module_label)
authorization.responses.add(
{"name": "auth-json", "json": {"properties": [{"name": "auth", "valueFrom": {"authJSON": "auth.identity"}}]}}
)
authorization.responses.add_simple("auth.identity")
return authorization


Expand All @@ -22,7 +20,7 @@ def tests_api_key_context(client, auth, api_key, module_label, testconfig):
"""
response = client.get("get", auth=auth)
assert response.status_code == 200
identity = json.loads(response.json()["headers"]["Auth-Json"])["auth"]
assert identity["data"]["api_key"] == api_key.model.data.api_key
assert identity["metadata"]["namespace"] == testconfig["openshift"].project
assert identity["metadata"]["labels"]["group"] == module_label
identity = extract_response(response)
assert identity["data"]["api_key"] % None == api_key.model.data.api_key
assert identity["metadata"]["namespace"] % None == testconfig["openshift"].project
assert identity["metadata"]["labels"]["group"] % None == module_label
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import pytest

from testsuite.utils import ContentType, extract_from_response
from testsuite.utils import ContentType, extract_response


MULTI_ELEMENT_JSON = '{"foo": "bar"}\n{"blah": "bleh"}'
Expand All @@ -24,18 +24,13 @@ def authorization(authorization, json_mock_expectation):
Adds auth metadata HTTP endpoint and header 'Auth-Json' inspecting parsed metadata value.
"""
authorization.metadata.http_metadata("mock", json_mock_expectation, "GET")
authorization.responses.add(
{
"name": "auth-json",
"json": {"properties": [{"name": "mock", "valueFrom": {"authJSON": "auth.metadata.mock"}}]},
}
)
authorization.responses.add_simple("auth.metadata.mock")
return authorization


def test_metadata_contents(client, auth):
"""This test exports parsed metadata value from headers and checks if it is a list of size two."""
response = client.get("/get", auth=auth)
extracted = extract_from_response(response, section="mock")
extracted = extract_response(response) % None
assert isinstance(extracted, list)
assert len(extracted) == 2
11 changes: 1 addition & 10 deletions testsuite/tests/kuadrant/authorino/priority/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,5 @@ def authorization(authorization):
Add to the AuthConfig response with *auth* key from AuthJson,
to test used identity and resolved metadata dependencies
"""
authorization.responses.add(
{
"name": "auth-json",
"json": {
"properties": [
{"name": "auth", "valueFrom": {"authJSON": "auth"}},
]
},
}
)
authorization.responses.add_simple("auth")
return authorization
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Test for evaluators dependencies resolving according to their priorities"""
import pytest

from testsuite.utils import extract_from_response
from testsuite.utils import extract_response


@pytest.fixture(scope="module")
Expand Down Expand Up @@ -29,7 +29,9 @@ def test_dependency(client, auth):
"""Test metadata dependency resolving according to it's priority"""
response = client.get("/get", auth=auth)
assert response.status_code == 200
metadata = extract_from_response(response)["metadata"]
metadata = extract_response(response)["metadata"] % {}

assert len(metadata) > 0

first_uuid = metadata["first"]["uuid"]
second_uuid = metadata["second"]["uuid"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"""
import pytest

from testsuite.utils import extract_from_response
from testsuite.utils import extract_response


@pytest.fixture(scope="module")
Expand All @@ -21,8 +21,10 @@ def test_priority_anonymous(client, auth, oidc_provider):
"""
response = client.get("/get", auth=auth)
assert response.status_code == 200
assert extract_from_response(response)["identity"]["iss"] == oidc_provider.well_known["issuer"]
iss = extract_response(response)["identity"]["iss"] % None
assert iss == oidc_provider.well_known["issuer"]

response = client.get("/get")
assert response.status_code == 200
assert extract_from_response(response)["identity"] == {"anonymous": True}
identity = extract_response(response)["identity"] % None
assert identity == {"anonymous": True}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Test for api key identities, with different credential methods, sequential trigger according to their priorities"""
import pytest

from testsuite.utils import extract_from_response
from testsuite.utils import extract_response


@pytest.fixture(scope="module")
Expand Down Expand Up @@ -48,13 +48,13 @@ def test_priority_api_key(client, first_api_key, second_api_key, first_label, se
# verify that first API key is available to identify with and is used for identification
response = client.get("/get", headers={"authorization": "APIKEY " + first_api_key})
assert response.status_code == 200
label = extract_from_response(response)["identity"]["metadata"]["labels"]["group"]
label = extract_response(response)["identity"]["metadata"]["labels"]["group"] % None
assert label == first_label

# verify that second API key is available to identify with and is used for identification
response = client.get("/get", params={"APIKEY": second_api_key})
assert response.status_code == 200
label = extract_from_response(response)["identity"]["metadata"]["labels"]["group"]
label = extract_response(response)["identity"]["metadata"]["labels"]["group"] % None
assert label == second_label

# verify that if both keys credential methods are used at the same time,
Expand All @@ -63,5 +63,5 @@ def test_priority_api_key(client, first_api_key, second_api_key, first_label, se
"/get", headers={"authorization": "APIKEY " + first_api_key}, params={"APIKEY": second_api_key}
)
assert response.status_code == 200
label = extract_from_response(response)["identity"]["metadata"]["labels"]["group"]
label = extract_response(response)["identity"]["metadata"]["labels"]["group"] % None
assert label == first_label
16 changes: 7 additions & 9 deletions testsuite/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from urllib.parse import urlparse, ParseResult

import httpx
from weakget import weakget

from testsuite.certificates import Certificate, CFSSLClient, CertInfo
from testsuite.config import settings
Expand Down Expand Up @@ -139,15 +140,12 @@ def fire_requests(client, max_requests, period, grace_requests=0, iterations=1,
assert httpx.get(url).status_code == 200, f"Iteration {iteration + 1} failed to reset limits"


def extract_from_response(response, *path, section="auth"):
def extract_response(response, header="Simple", key="data"):
"""
Gets required value from the response
:param response: Client response
:param path: Key sequence associated with required value
:param section: Default section for extraction
Extracts response added by Authorino from header
:param key: Response key section
:param header: Name of the header
:param response: http response
:return: Extracted value
"""
result = json.loads(response.json()["headers"]["Auth-Json"])[section]
for item in path:
result = result[item]
return result
return weakget(json.loads(response.json()["headers"][header]))[key]