Repository navigation
feat: Add OpaClient to wrap auth checks #1541
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
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
36f077c
Use Depends injection to extract user name
tpoliaw a44a6bd
feat: Add OpaConfig for authorization configuration
tpoliaw 072a466
Add OpaClient to wrap OPA interactions
tpoliaw f0eae24
Create OpaClient as part of server lifecycle
tpoliaw d390a18
Move instrument requirement into OpaClient init
tpoliaw f048b05
Add tests for OpaClient
tpoliaw File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| import logging | ||
| from collections.abc import Mapping | ||
| from contextlib import AbstractAsyncContextManager, aclosing, nullcontext | ||
| from typing import Any, Self | ||
|
|
||
| from aiohttp import ClientSession | ||
|
|
||
| from blueapi.config import OpaConfig | ||
|
|
||
| LOGGER = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class OpaClient: | ||
| def __init__(self, instrument: str, config: OpaConfig): | ||
| LOGGER.info("Creating OpaClient for %s with config %s", instrument, config) | ||
| self._instrument = instrument | ||
| self._config = config | ||
| self._session = ClientSession(base_url=config.root.encoded_string()) | ||
| self._audience = config.audience | ||
|
|
||
| async def aclose(self): | ||
| LOGGER.info("Closing OPA session") | ||
| await self._session.close() | ||
|
|
||
| async def _call_opa(self, endpoint: str, data: Mapping[str, Any]) -> bool: | ||
| resp = await self._session.post( | ||
| endpoint, | ||
| json={ | ||
| "input": { | ||
| "beamline": self._instrument, | ||
| "audience": self._audience, | ||
| **data, | ||
| } | ||
| }, | ||
| ) | ||
| return (await resp.json())["result"] | ||
|
ZohebShaikh marked this conversation as resolved.
Resolved
|
||
|
|
||
| @classmethod | ||
| def for_config( | ||
| cls, instrument: str | None, config: OpaConfig | None | ||
| ) -> AbstractAsyncContextManager[Self | None]: | ||
| if config: | ||
| if not instrument: | ||
| raise ValueError("Instrument name is required for OPA client") | ||
| return aclosing(cls(instrument, config)) | ||
| LOGGER.info("No OPA config provided - not creating OpaClient") | ||
| return nullcontext() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| from unittest.mock import AsyncMock, MagicMock, patch | ||
|
|
||
| import pytest | ||
| from pydantic import HttpUrl | ||
|
|
||
| from blueapi.config import OpaConfig | ||
| from blueapi.service.authorization import ( | ||
| OpaClient, | ||
| ) | ||
|
|
||
| # Reusable client patch decorator | ||
| patch_client_session = patch( | ||
| "blueapi.service.authorization.ClientSession", | ||
| name="mock_client_session", | ||
| spec=True, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.fixture(scope="module") | ||
| def opa_config() -> OpaConfig: | ||
| return OpaConfig( | ||
| root=HttpUrl("http://auth.example.com"), | ||
| ) | ||
|
|
||
|
|
||
| @patch_client_session | ||
| async def test_session_closed(session: MagicMock, opa_config: OpaConfig): | ||
| async with OpaClient.for_config("p45", opa_config): | ||
| pass | ||
| session().close.assert_called_once() | ||
|
|
||
|
|
||
| @patch_client_session | ||
| async def test_opa_client_for_config(session: MagicMock, opa_config: OpaConfig): | ||
| async with OpaClient.for_config("p45", opa_config) as opa: | ||
| assert opa is not None | ||
| session.assert_called_once_with(base_url="http://auth.example.com/") | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("instrument", [None, "p99"]) | ||
| async def test_opa_client_without_config(instrument: str | None): | ||
| async with OpaClient.for_config(instrument, None) as opa: | ||
| assert opa is None | ||
|
|
||
|
|
||
| async def test_opa_fails_without_instrument(opa_config: OpaConfig): | ||
| with pytest.raises(ValueError, match="Instrument name is required"): | ||
| OpaClient.for_config(None, opa_config) | ||
|
|
||
|
|
||
| @patch_client_session | ||
| async def test_opa_adds_input_fields(session: MagicMock, opa_config: OpaConfig): | ||
| session.return_value.post = AsyncMock() | ||
| async with OpaClient.for_config("p45", opa_config) as opa: | ||
| assert opa is not None | ||
| await opa._call_opa("foo/bar", data={"foo": "bar"}) | ||
|
|
||
| session.assert_called_once() | ||
| session().post.assert_called_once_with( | ||
| "foo/bar", | ||
| json={"input": {"beamline": "p45", "audience": "account", "foo": "bar"}}, | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.