Skip to content
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

Propagate Reporter Errors #243

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
6 changes: 6 additions & 0 deletions src/mainframe/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@
from mainframe.rules import Rules


@cache
def get_http_client() -> httpx.Client:
http_client = httpx.Client()
return http_client


@cache
def get_pypi_client() -> PyPIServices:
http_client = httpx.Client()
Expand Down
14 changes: 11 additions & 3 deletions src/mainframe/endpoints/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

from mainframe.constants import mainframe_settings
from mainframe.database import get_db
from mainframe.dependencies import get_pypi_client, validate_token
from mainframe.dependencies import get_http_client, get_pypi_client, validate_token
from mainframe.json_web_token import AuthenticationData
from mainframe.models.orm import Scan
from mainframe.models.schemas import (
Expand Down Expand Up @@ -159,6 +159,7 @@ def report_package(
session: Annotated[Session, Depends(get_db)],
auth: Annotated[AuthenticationData, Depends(validate_token)],
pypi_client: Annotated[PyPIServices, Depends(get_pypi_client)],
http_client: Annotated[httpx.Client, Depends(get_http_client)],
):
"""
Report a package to PyPI.
Expand Down Expand Up @@ -218,7 +219,14 @@ def report_package(
additional_information=body.additional_information,
)

httpx.post(f"{mainframe_settings.reporter_url}/report/email", json=jsonable_encoder(report))
response = http_client.post(f"{mainframe_settings.reporter_url}/report/email", json=jsonable_encoder(report))
try:
response.raise_for_status()
except httpx.HTTPStatusError as err:
Comment on lines +223 to +225
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
try:
response.raise_for_status()
except httpx.HTTPStatusError as err:
if not response.is_success:

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's extract the logic for error checking and sending the request to a new function so it's easier to test.

detail = "Dragonfly Reporter service failed"
log.error(detail, status=err.response.status_code, message=err.response.text)
raise HTTPException(502, detail=detail)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change

else:
# We previously checked this condition, but the typechecker isn't smart
# enough to figure that out
Expand All @@ -231,7 +239,7 @@ def report_package(
extra=dict(yara_rules=rules_matched),
)

httpx.post(f"{mainframe_settings.reporter_url}/report/{name}", json=jsonable_encoder(report))
http_client.post(f"{mainframe_settings.reporter_url}/report/{name}", json=jsonable_encoder(report))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't we want to check for success here also?


log.info(
"Sent report",
Expand Down
49 changes: 44 additions & 5 deletions tests/test_report.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from datetime import datetime, timedelta
from datetime import UTC, datetime, timedelta
from typing import Optional
from unittest.mock import MagicMock
from unittest.mock import Mock

import httpx
import pytest
Expand Down Expand Up @@ -105,11 +105,12 @@ def test_report(
db_session.add(scan)
db_session.commit()

httpx.post = MagicMock()
mock_http_client = Mock(spec=httpx.Client)
mock_http_client.post = Mock()

report_package(body, db_session, auth, pypi_client)
report_package(body, db_session, auth, pypi_client, mock_http_client)

httpx.post.assert_called_once_with(url, json=jsonable_encoder(expected))
mock_http_client.post.assert_called_once_with(url, json=jsonable_encoder(expected))

scan = db_session.scalar(select(Scan).where(Scan.name == "c").where(Scan.version == "1.0.0"))

Expand Down Expand Up @@ -412,3 +413,41 @@ def test_report_lookup_package(db_session: Session):
res = _lookup_package("c", "1.0.0", db_session)

assert res == scan


def test_reporter_service_fail(db_session: Session, auth: AuthenticationData, pypi_client: PyPIServices):
scan = Scan(
name="abc",
version="1.0.0",
status=Status.FINISHED,
inspector_url="test inspector URL",
score=25,
queued_at=datetime.now(UTC) - timedelta(seconds=30),
queued_by="remmy",
)
db_session.add(scan)
db_session.commit()

mock_http_client = Mock(spec=httpx.Client)
mock_response = Mock(spec=httpx.Response)
mock_response.status_code = 400

def side_effect():
raise httpx.HTTPStatusError("Error", request=Mock(), response=mock_response)

mock_response.raise_for_status = Mock(side_effect=side_effect)
mock_http_client.post = Mock(return_value=mock_response)

body = ReportPackageBody(
name="abc",
version="1.0.0",
recipient=None,
inspector_url="test inspector url",
additional_information="this is a bad package",
use_email=True,
)

with pytest.raises(HTTPException) as err:
report_package(body, db_session, auth, pypi_client, mock_http_client)

assert err.value.status_code == 502