async def test_opa_decision_auto_error_allowed(make_mock_async_client, mock_request): mock_async_client = make_mock_async_client({ "result": True, "decision_id": "hoi" }) opa_decision_security = opa_decision( "https://opa_url.test", None, opa_kwargs={"extra": 3}, auto_error=False # type:ignore ) result = await opa_decision_security(mock_request, user_info_matching, mock_async_client) assert result is True opa_input = { "input": { "extra": 3, **user_info_matching, "resource": "/test/path", "method": "GET", "arguments": { "path": {}, "query": {}, "json": {} }, } } mock_async_client.post.assert_called_with("https://opa_url.test", json=opa_input)
async def test_opa_decision_user_not_allowed(make_mock_async_client, mock_request): mock_async_client = make_mock_async_client({ "result": False, "decision_id": "hoi" }) opa_decision_security = opa_decision("https://opa_url.test", None) # type:ignore with pytest.raises(HTTPException) as exception: await opa_decision_security(mock_request, user_info_matching, mock_async_client) assert exception.value.status_code == 403 opa_input = { "input": { **user_info_matching, "resource": "/test/path", "method": "GET", "arguments": { "path": {}, "query": {}, "json": {} }, } } mock_async_client.post.assert_called_with("https://opa_url.test", json=opa_input)
async def test_opa_decision_network_or_type_error(make_mock_async_client, mock_request): mock_async_client = make_mock_async_client(error=TypeError()) opa_decision_security = opa_decision("https://opa_url.test", None) # type:ignore with pytest.raises(HTTPException) as exception: await opa_decision_security(mock_request, user_info_matching, mock_async_client) assert exception.value.status_code == 503
async def test_opa_decision_auto_error(): def mock_user_info(): return {} opa_decision_security = opa_decision("https://opa_url.test", cast(OIDCUser, mock_user_info), enabled=False) mock_request = mock.MagicMock(spec=Request) assert await opa_decision_security(mock_request, {}, None) is None # type:ignore
from authlib.integrations.starlette_client import OAuth from nwastdlib.url import URL from oauth2_lib.fastapi import OIDCUser, opa_decision from orchestrator.settings import oauth2_settings oauth_client_credentials = OAuth() well_known_endpoint = URL(oauth2_settings.OIDC_CONF_WELL_KNOWN_URL) oauth_client_credentials.register( "connext", server_metadata_url=well_known_endpoint / ".well-known" / "openid-configuration", client_id=oauth2_settings.OAUTH2_RESOURCE_SERVER_ID, client_secret=oauth2_settings.OAUTH2_RESOURCE_SERVER_SECRET, request_token_params={"grant_type": "client_credentials"}, ) oidc_user = OIDCUser( oauth2_settings.OIDC_CONF_WELL_KNOWN_URL, oauth2_settings.OAUTH2_RESOURCE_SERVER_ID, oauth2_settings.OAUTH2_RESOURCE_SERVER_SECRET, enabled=oauth2_settings.OAUTH2_ACTIVE, ) opa_security_default = opa_decision(oauth2_settings.OPA_URL, oidc_user, enabled=oauth2_settings.OAUTH2_ACTIVE)