-
Notifications
You must be signed in to change notification settings - Fork 14
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
Draft
tpoliaw
wants to merge
8
commits into
main
Choose a base branch
from
opa-client
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
30a75f1
WIP opa client
tpoliaw e68c467
Stop the machines complaining
tpoliaw b6cced2
Add aiohttp dependency
tpoliaw 240042a
Update config + tests
tpoliaw d513ffa
Check tiled config at startup
tpoliaw 6109427
Move HTTPException to auth_check
tpoliaw b25a9aa
Refactor opa checks
tpoliaw ab6a11f
Close opa client session
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| import logging | ||
| import re | ||
| from collections.abc import Mapping | ||
| from typing import Any | ||
|
|
||
| import aiohttp | ||
| from aiohttp import ClientSession | ||
| from fastapi import HTTPException | ||
| from starlette.status import HTTP_401_UNAUTHORIZED | ||
|
|
||
| from blueapi.config import OpaConfig | ||
| from blueapi.service.model import TaskRequest | ||
|
|
||
| LOGGER = logging.getLogger(__name__) | ||
|
|
||
| INSTRUMENT_SESSION_RE = re.compile(r"^[a-z]{2}(?P<proposal>\d+)-(?P<visit>\d+)$") | ||
|
|
||
|
|
||
| class OpaClient: | ||
| client: aiohttp.ClientSession | ||
|
|
||
| def __init__(self, instrument: str, config: OpaConfig): | ||
| LOGGER.info("Creating OpaClient for %s with config %s", instrument, config) | ||
| self._instrument = instrument | ||
| self._conf = config | ||
| self._session = ClientSession(base_url=config.root.encoded_string()) | ||
|
|
||
| def for_token(self, token: str) -> "OpaUserClient": | ||
| return OpaUserClient(self, token) | ||
|
|
||
| async def close(self): | ||
| await self._session.close() | ||
|
|
||
| async def _call_opa(self, endpoint, data: Mapping[str, Any]) -> bool: | ||
| try: | ||
| resp = await self._session.post( | ||
| endpoint, | ||
| json={"input": {"beamline": self._instrument, **data}}, | ||
| ) | ||
| return (await resp.json())["result"] | ||
| except Exception: | ||
| LOGGER.exception("Failed to run check", exc_info=True) | ||
| raise | ||
|
|
||
| async def require_tiled_service_account(self, token: str): | ||
| if not await self._call_opa( | ||
| self._conf.tiled_service_account_check, | ||
| {"token": token, "beamline": self._instrument}, | ||
| ): | ||
| raise ValueError( | ||
| f"Tiled service account is not valid for '{self._instrument}'" | ||
| ) | ||
|
|
||
| async def submit_plan_check(self, token: str, instrument_session: str): | ||
| if not (match := INSTRUMENT_SESSION_RE.match(instrument_session)): | ||
| raise ValueError("Invalid instrument session") | ||
|
|
||
| if not await self._call_opa( | ||
| self._conf.submit_plan_check, | ||
| { | ||
| "token": token, | ||
| "audience": "account", | ||
| "proposal": int(match["proposal"]), | ||
| "visit": int(match["visit"]), | ||
| }, | ||
| ): | ||
| raise HTTPException(status_code=HTTP_401_UNAUTHORIZED) | ||
|
|
||
|
|
||
| class OpaUserClient: | ||
| client: OpaClient | ||
| token: str | ||
|
|
||
| def __init__(self, client: OpaClient, token: str): | ||
| self.client = client | ||
| self.token = token | ||
|
|
||
| async def check_submit_plan(self, task: TaskRequest): | ||
| LOGGER.info("Checking permissions to run task: %s", task) | ||
| await self.client.submit_plan_check( | ||
| token=self.token, instrument_session=task.instrument_session | ||
| ) |
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.