Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 13 additions & 14 deletions services/hackbot-api/app/bugzilla_authorization.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,38 +21,37 @@ def __init__(
self._api_url = api_url.rstrip("/")
self._api_key = api_key
self._authorized_group_name = authorized_group_name
self._cache: TTLCache[str, bool] = TTLCache(
self._cache: TTLCache[str, str | None] = 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."""
async def is_authorized(self, login: str) -> str | None:
"""Return the nickname of a login in the authorized group, else None."""
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
if login not in self._cache:
self._cache[login] = await self._is_user_in_group(
login, self._authorized_group_name
)
return self._cache[login]

# 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 def _is_user_in_group(self, login: str, group_name: str) -> str | None:
"""Return the nickname of a Bugzilla account in a group, else None."""
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",
"include_fields": "name,nick",
# 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"))
users = response.json().get("users")
return users[0]["nick"] if users else None
7 changes: 6 additions & 1 deletion services/hackbot-api/app/bugzilla_webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class BugzillaNeedinfoEvent:
bug_id: int
flag_id: int
comment: str
user_id: int
user_login: str


Expand Down Expand Up @@ -85,5 +86,9 @@ def detect_needinfo_request(
"bug context if none exists."
)
return BugzillaNeedinfoEvent(
bug_id=bug_id, flag_id=flag_id, comment=comment, user_login=actor_login
bug_id=bug_id,
flag_id=flag_id,
comment=comment,
user_id=event["user"]["id"],
user_login=actor_login,
)
9 changes: 8 additions & 1 deletion services/hackbot-api/app/routers/webhooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,8 @@ async def bugzilla_webhook(
if detected is None:
return {"status": "ignored", "reason": "no actionable Hackbot needinfo"}

if not await authorizer.is_authorized(detected.user_login):
nick = await authorizer.is_authorized(detected.user_login)
if nick is None:
log.info(
"Ignored Bugzilla needinfo webhook for bug %s: %s is not authorized",
detected.bug_id,
Expand All @@ -244,6 +245,12 @@ async def bugzilla_webhook(
"comment": detected.comment,
},
dedupe_key=f"ni{detected.flag_id}",
source=Source.bugzilla,
identity=Identity(
identity_provider=IdentityProvider.bugzilla,
user_id=str(detected.user_id),
username=nick,
),
)
if not run.is_new:
log.info(
Expand Down
30 changes: 16 additions & 14 deletions services/hackbot-api/tests/test_bugzilla_authorization.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
BUGZILLA_API_KEY = "test-bugzilla-api-key"


def _authorizer(member: bool) -> tuple[BugzillaAuthorizer, AsyncMock]:
def _authorizer(member: str | None) -> tuple[BugzillaAuthorizer, AsyncMock]:
"""An authorizer whose membership lookup is stubbed to ``member``."""
authorizer = BugzillaAuthorizer(
"https://bugzilla.example.com/rest",
Expand All @@ -23,26 +23,26 @@ def _authorizer(member: bool) -> tuple[BugzillaAuthorizer, AsyncMock]:


async def test_is_authorized_caches_positive_lookup():
authorizer, lookup = _authorizer(member=True)
authorizer, lookup = _authorizer(member="dev")

assert await authorizer.is_authorized("dev@mozilla.com") is True
assert await authorizer.is_authorized("dev@mozilla.com") is True
assert await authorizer.is_authorized("dev@mozilla.com") == "dev"
assert await authorizer.is_authorized("dev@mozilla.com") == "dev"
lookup.assert_awaited_once_with("dev@mozilla.com", AUTHORIZED_GROUP_NAME)


async def test_is_authorized_caches_negative_lookup():
authorizer, lookup = _authorizer(member=False)
authorizer, lookup = _authorizer(member=None)

assert await authorizer.is_authorized("someone@example.com") is False
assert await authorizer.is_authorized("someone@example.com") is False
assert await authorizer.is_authorized("someone@example.com") is None
assert await authorizer.is_authorized("someone@example.com") is None
lookup.assert_awaited_once_with("someone@example.com", AUTHORIZED_GROUP_NAME)


async def test_is_authorized_normalizes_login_case():
authorizer, lookup = _authorizer(member=True)
authorizer, lookup = _authorizer(member="dev")

assert await authorizer.is_authorized("Dev@Mozilla.com") is True
assert await authorizer.is_authorized("dev@mozilla.com") is True
assert await authorizer.is_authorized("Dev@Mozilla.com") == "dev"
assert await authorizer.is_authorized("dev@mozilla.com") == "dev"
lookup.assert_awaited_once_with("dev@mozilla.com", AUTHORIZED_GROUP_NAME)


Expand Down Expand Up @@ -77,16 +77,18 @@ def handler(request: httpx.Request) -> httpx.Response:

async def test_lookup_authorizes_group_member(monkeypatch):
authorizer, requests = _http_authorizer(
monkeypatch, {"users": [{"name": "dev@mozilla.com"}], "faults": []}
monkeypatch,
{"users": [{"name": "dev@mozilla.com", "nick": "dev"}], "faults": []},
)

assert await authorizer.is_authorized("dev@mozilla.com") is True
assert await authorizer.is_authorized("dev@mozilla.com") == "dev"

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["include_fields"] == "name,nick"
assert request.url.params["permissive"] == "1"
assert request.headers["X-Bugzilla-API-Key"] == BUGZILLA_API_KEY

Expand All @@ -95,7 +97,7 @@ 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
assert await authorizer.is_authorized("outsider@example.com") is None


async def test_lookup_rejects_unknown_user(monkeypatch):
Expand All @@ -114,4 +116,4 @@ async def test_lookup_rejects_unknown_user(monkeypatch):
],
},
)
assert await authorizer.is_authorized("ghost@example.com") is False
assert await authorizer.is_authorized("ghost@example.com") is None
34 changes: 30 additions & 4 deletions services/hackbot-api/tests/test_webhooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,13 @@
)
from app.routers import webhooks
from fastapi.testclient import TestClient
from hackbot_client import RunStatus, TriggeredRun
from hackbot_client import (
Identity,
IdentityProvider,
RunStatus,
Source,
TriggeredRun,
)
from sqlalchemy.dialects import postgresql

SECRET = "test-secret"
Expand Down Expand Up @@ -569,9 +575,13 @@ class _FakeHackbotClient:
def __init__(self):
self.calls = []
self.dedupe_keys = []
self.identities = []

async def trigger_run(self, agent_name, inputs, *, dedupe_key=None):
async def trigger_run(
self, agent_name, inputs, *, dedupe_key=None, source=None, identity=None
):
self.calls.append((agent_name, inputs))
self.identities.append((source, identity))
# Like the API's unique index: a key seen before resolves to the
# existing run and is not new to this request.
is_new = dedupe_key is None or dedupe_key not in self.dedupe_keys
Expand Down Expand Up @@ -599,9 +609,15 @@ def authorizer():
return _FakeAuthorizer()


class _FakeBugzillaAuthorizer(_FakeAuthorizer):
async def is_authorized(self, actor):
self.checked.append(actor)
return "sparky" if self.allowed else None


@pytest.fixture
def bugzilla_authorizer():
return _FakeAuthorizer()
return _FakeBugzillaAuthorizer()


@pytest.fixture
Expand Down Expand Up @@ -894,6 +910,16 @@ def test_bugzilla_route_triggers_run(client, bugzilla_authorizer):
},
)
]
assert fake_api.identities == [
(
Source.bugzilla,
Identity(
identity_provider=IdentityProvider.bugzilla,
user_id="560562",
username="sparky",
),
)
]
assert bugzilla_authorizer.checked == ["gmierzwinski@mozilla.com"]


Expand Down Expand Up @@ -935,7 +961,7 @@ def test_bugzilla_route_keys_retry_same_but_later_event_differently(client):

def test_bugzilla_route_surfaces_failed_dispatch(client):
class _FailingClient:
async def trigger_run(self, agent_name, inputs, *, dedupe_key=None):
async def trigger_run(self, agent_name, inputs, **kwargs):
raise RuntimeError("run creation failed")

app.dependency_overrides[get_hackbot_client] = lambda: _FailingClient()
Expand Down