-
Notifications
You must be signed in to change notification settings - Fork 351
Bugzilla webhook authorization #6786
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
ayoubdiourin7
wants to merge
9
commits into
mozilla:master
Choose a base branch
from
ayoubdiourin7:bugzilla-webhook-authorization
base: master
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 all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
bc01b46
Restrict Bugzilla webhook triggers to editbugs users
ayoubdiourin7 7c518e9
update the doc
ayoubdiourin7 1ede4fa
Remove implementation details from the Bugzilla webhook docs
ayoubdiourin7 465f2f2
Move the Bugzilla group lookup into BugzillaAuthorize
ayoubdiourin7 a7e5ed4
move the Bugzilla API URL to the main settings
ayoubdiourin7 26dccb5
Rename actor_login to user_login to match Bugzilla
ayoubdiourin7 913532a
Delete unnecessary comments.
ayoubdiourin7 b8f7358
Use Bugzilla group name for webhook authorization
ayoubdiourin7 2cbd6d9
Remove global lock from Bugzilla authorization
ayoubdiourin7 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,62 @@ | ||
| """Authorization checks for Bugzilla webhook actors.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import httpx | ||
| from cachetools import TTLCache | ||
|
|
||
| AUTHORIZED_GROUP_NAME = "editbugs" | ||
|
|
||
| _REQUEST_TIMEOUT_SECONDS = 30 | ||
|
|
||
|
|
||
| class BugzillaAuthorizer: | ||
| """Cache-backed per-user authorization checks against a Bugzilla group.""" | ||
|
|
||
| def __init__( | ||
| self, | ||
| api_url: str, | ||
| api_key: str, | ||
| authorized_group_name: str, | ||
| *, | ||
| cache_ttl_seconds: int = 300, | ||
| cache_maxsize: int = 4096, | ||
| ) -> None: | ||
| self._api_url = api_url.rstrip("/") | ||
| self._api_key = api_key | ||
| self._authorized_group_name = authorized_group_name | ||
| self._cache: TTLCache[str, bool] = TTLCache( | ||
| maxsize=cache_maxsize, | ||
| ttl=cache_ttl_seconds, | ||
| ) | ||
|
|
||
| async def is_authorized(self, login: str) -> bool: | ||
| """Return whether a Bugzilla login belongs to the authorized group.""" | ||
| login = login.lower() | ||
|
|
||
| cached = self._cache.get(login) | ||
| if cached is not None: | ||
| return cached | ||
|
|
||
| authorized = await self._is_user_in_group(login, self._authorized_group_name) | ||
| self._cache[login] = authorized | ||
| return authorized | ||
|
|
||
| # TODO: Move this REST call to a shared Bugzilla client library (#6459). | ||
| async def _is_user_in_group(self, login: str, group_name: str) -> bool: | ||
| """Return whether a Bugzilla account exists and belongs to a group.""" | ||
| async with httpx.AsyncClient(timeout=_REQUEST_TIMEOUT_SECONDS) as client: | ||
| response = await client.get( | ||
| f"{self._api_url}/user", | ||
| params={ | ||
| "names": login, | ||
| "groups": group_name, | ||
| "include_fields": "name", | ||
| # Report an unknown login in ``faults`` instead of failing | ||
| # the request, so it maps to "not authorized", not a 500. | ||
| "permissive": "1", | ||
| }, | ||
| headers={"X-Bugzilla-API-Key": self._api_key}, | ||
| ) | ||
| response.raise_for_status() | ||
| return bool(response.json().get("users")) | ||
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
115 changes: 115 additions & 0 deletions
115
services/hackbot-api/tests/test_bugzilla_authorization.py
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,115 @@ | ||
| """Tests for Bugzilla webhook actor authorization.""" | ||
|
|
||
| from unittest.mock import AsyncMock | ||
|
|
||
| import httpx | ||
| from app.bugzilla_authorization import AUTHORIZED_GROUP_NAME, BugzillaAuthorizer | ||
|
|
||
| BUGZILLA_API_KEY = "test-bugzilla-api-key" | ||
|
|
||
|
|
||
| def _authorizer(member: bool) -> tuple[BugzillaAuthorizer, AsyncMock]: | ||
| """An authorizer whose membership lookup is stubbed to ``member``.""" | ||
| authorizer = BugzillaAuthorizer( | ||
| "https://bugzilla.example.com/rest", | ||
| BUGZILLA_API_KEY, | ||
| AUTHORIZED_GROUP_NAME, | ||
| ) | ||
| lookup = AsyncMock(return_value=member) | ||
| authorizer._is_user_in_group = lookup | ||
| return authorizer, lookup | ||
|
|
||
|
|
||
| async def test_is_authorized_caches_positive_lookup(): | ||
| authorizer, lookup = _authorizer(member=True) | ||
|
|
||
| assert await authorizer.is_authorized("dev@mozilla.com") is True | ||
| assert await authorizer.is_authorized("dev@mozilla.com") is True | ||
| lookup.assert_awaited_once_with("dev@mozilla.com", AUTHORIZED_GROUP_NAME) | ||
|
|
||
|
|
||
| async def test_is_authorized_caches_negative_lookup(): | ||
| authorizer, lookup = _authorizer(member=False) | ||
|
|
||
| assert await authorizer.is_authorized("someone@example.com") is False | ||
| assert await authorizer.is_authorized("someone@example.com") is False | ||
| lookup.assert_awaited_once_with("someone@example.com", AUTHORIZED_GROUP_NAME) | ||
|
|
||
|
|
||
| async def test_is_authorized_normalizes_login_case(): | ||
| authorizer, lookup = _authorizer(member=True) | ||
|
|
||
| assert await authorizer.is_authorized("Dev@Mozilla.com") is True | ||
| assert await authorizer.is_authorized("dev@mozilla.com") is True | ||
| lookup.assert_awaited_once_with("dev@mozilla.com", AUTHORIZED_GROUP_NAME) | ||
|
|
||
|
|
||
| # --- the membership lookup itself, on BMO's captured payload shapes --- | ||
|
|
||
|
|
||
| def _http_authorizer( | ||
| monkeypatch, json_body: dict | ||
| ) -> tuple[BugzillaAuthorizer, list[httpx.Request]]: | ||
| """An authorizer whose HTTP layer replays ``json_body``, capturing requests.""" | ||
| requests: list[httpx.Request] = [] | ||
|
|
||
| def handler(request: httpx.Request) -> httpx.Response: | ||
| requests.append(request) | ||
| return httpx.Response(200, json=json_body) | ||
|
|
||
| real_async_client = httpx.AsyncClient | ||
| monkeypatch.setattr( | ||
| httpx, | ||
| "AsyncClient", | ||
| lambda **kwargs: real_async_client( | ||
| transport=httpx.MockTransport(handler), **kwargs | ||
| ), | ||
| ) | ||
| authorizer = BugzillaAuthorizer( | ||
| "https://bugzilla.example.com/rest", | ||
| BUGZILLA_API_KEY, | ||
| AUTHORIZED_GROUP_NAME, | ||
| ) | ||
| return authorizer, requests | ||
|
|
||
|
|
||
| async def test_lookup_authorizes_group_member(monkeypatch): | ||
| authorizer, requests = _http_authorizer( | ||
| monkeypatch, {"users": [{"name": "dev@mozilla.com"}], "faults": []} | ||
| ) | ||
|
|
||
| assert await authorizer.is_authorized("dev@mozilla.com") is True | ||
|
|
||
| request = requests[0] | ||
| assert request.url.host == "bugzilla.example.com" | ||
| assert request.url.path == "/rest/user" | ||
| assert request.url.params["names"] == "dev@mozilla.com" | ||
| assert request.url.params["groups"] == AUTHORIZED_GROUP_NAME | ||
| assert request.url.params["permissive"] == "1" | ||
| assert request.headers["X-Bugzilla-API-Key"] == BUGZILLA_API_KEY | ||
|
|
||
|
|
||
| async def test_lookup_rejects_non_member(monkeypatch): | ||
| # An existing account outside the group is filtered out server-side | ||
| # (live BMO shape: empty ``users``, empty ``faults``). | ||
| authorizer, _ = _http_authorizer(monkeypatch, {"users": [], "faults": []}) | ||
| assert await authorizer.is_authorized("outsider@example.com") is False | ||
|
|
||
|
|
||
| async def test_lookup_rejects_unknown_user(monkeypatch): | ||
| # With permissive=1, BMO reports an unknown login as a 200 with the error | ||
| # in ``faults`` and an empty ``users`` list (live BMO shape). | ||
| authorizer, _ = _http_authorizer( | ||
| monkeypatch, | ||
| { | ||
| "users": [], | ||
| "faults": [ | ||
| { | ||
| "error": True, | ||
| "name": "ghost@example.com", | ||
| "message": "There is no user named 'ghost@example.com'.", | ||
| } | ||
| ], | ||
| }, | ||
| ) | ||
| assert await authorizer.is_authorized("ghost@example.com") is False |
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.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: I would use the
GET /rest/user/(id_or_name)since we need one user only.