-
Notifications
You must be signed in to change notification settings - Fork 2
DBC22-5426: token based auth for RabbitMQ connection #1313
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
Open
bcgov-brwang
wants to merge
10
commits into
main
Choose a base branch
from
feature/DBC22-5426
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.
Open
Changes from 5 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
3b62369
DBC22-5426: token based auth
bcgov-brwang be40d8c
DBC22-5426: fixed github-code-quality alerts
bcgov-brwang fe0b424
DBC22-5426: fixed broken test cases
bcgov-brwang 0119a22
DBC22-5426: fixed broken test cases 2
bcgov-brwang c567308
DBC22-5426: fixed broken test cases 3
bcgov-brwang f377710
DBC22-5426: fixed broken test cases 4
bcgov-brwang 4722705
DBC22-5426: removed commented out code
bcgov-brwang ebddcbd
DBC22-5426: fixed sonarcube alerts
bcgov-brwang 13bfe7c
DBC22-5426: removed commented out code 2
bcgov-brwang 2ba3cbb
DBC22-5426: fixed sonarcube alerts 3
bcgov-brwang 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| import httpx | ||
| import os | ||
| import aio_pika | ||
| import logging | ||
| from datetime import datetime, timedelta, timezone | ||
|
|
||
| RABBITMQ_HEARTBEAT = int(os.getenv("RABBITMQ_HEARTBEAT", "60")) | ||
| RABBITMQ_TIMEOUT = int(os.getenv("RABBITMQ_TIMEOUT", "30")) | ||
| RABBITMQ_RECONNECT_INTERVAL = int(os.getenv("RABBITMQ_RECONNECT_INTERVAL", "5")) | ||
| RABBITMQ_HOST = os.getenv("RABBITMQ_HOST") | ||
| RABBITMQ_PORT = int(os.getenv("RABBITMQ_PORT", "5672")) | ||
| RABBITMQ_VHOST = os.getenv("RABBITMQ_VHOST") | ||
| OAUTH2_TOKEN_URL = os.getenv("OAUTH2_TOKEN_URL") | ||
| OAUTH2_CLIENT_ID = os.getenv("OAUTH2_CLIENT_ID") | ||
| OAUTH2_SCOPE = os.getenv("OAUTH2_SCOPE", "") | ||
| OAUTH2_DRIVEBC_RABBITMQ_USERNAME = os.getenv("OAUTH2_DRIVEBC_RABBITMQ_USERNAME") | ||
| OAUTH2_DRIVEBC_RABBITMQ_PASSWORD = os.getenv("OAUTH2_DRIVEBC_RABBITMQ_PASSWORD") | ||
|
|
||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| class RabbitMQTokenConnection: | ||
| def __init__(self): | ||
| self._connection = None | ||
| self._token = None | ||
| self._token_expiry = None | ||
|
|
||
| async def _fetch_token(self) -> str: | ||
| now = datetime.now(timezone.utc) | ||
| if self._token and self._token_expiry and now < self._token_expiry: | ||
| return self._token | ||
|
|
||
| payload = { | ||
| "grant_type": "password", | ||
| "client_id": OAUTH2_CLIENT_ID, | ||
| "username": OAUTH2_DRIVEBC_RABBITMQ_USERNAME, | ||
| "password": OAUTH2_DRIVEBC_RABBITMQ_PASSWORD, | ||
| } | ||
|
|
||
| async with httpx.AsyncClient() as client: | ||
| response = await client.post(OAUTH2_TOKEN_URL, data=payload) | ||
| response.raise_for_status() | ||
| data = response.json() | ||
|
|
||
| self._token = data["access_token"] | ||
| expires_in = data.get("expires_in", 300) | ||
| self._token_expiry = now + timedelta(seconds=expires_in - 60) | ||
| return self._token | ||
|
|
||
| async def connect(self, host: str, port: int) -> aio_pika.RobustConnection: | ||
| token = await self._fetch_token() | ||
|
|
||
| self._connection = await aio_pika.connect_robust( | ||
| host=host, | ||
| port=port, | ||
| virtualhost=RABBITMQ_VHOST, | ||
| login="", | ||
| password=token, | ||
| heartbeat=RABBITMQ_HEARTBEAT, | ||
| timeout=RABBITMQ_TIMEOUT, | ||
| reconnect_interval=RABBITMQ_RECONNECT_INTERVAL, | ||
| ) | ||
|
|
||
|
|
||
| # Re-fetch token on every reconnect attempt | ||
| self._connection.reconnect_callbacks.add(self._on_reconnect) | ||
| return self._connection | ||
|
|
||
| async def _on_reconnect(self, connection): | ||
| """Called by aio_pika before each reconnect β refresh token.""" | ||
| logger.info("RabbitMQ reconnecting β refreshing OAuth2 token...") | ||
| try: | ||
| token = await self._fetch_token() | ||
| connection.password = token # inject fresh token | ||
| except Exception as e: | ||
| logger.error(f"Failed to refresh RabbitMQ token: {e}") |
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
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.