Coverage for src/retrospeedlab/backend/github/router.py: 100%

53 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-12-04 00:01 +0000

1import json 

2from typing import Annotated 

3 

4import httpx 

5from fastapi import APIRouter, Header, HTTPException, Request, status 

6from loguru import logger 

7from sqlalchemy.orm import Session 

8 

9from ..alerts.bugsink import BugsinkAlerts 

10from ..alerts.ci import RED, SUCCESS, CiRun 

11from ..alerts.rules import ALERTS 

12from ..config import GITHUB_TOKEN, GITHUB_WEBHOOK_SECRET 

13from ..database import engine, utc_now 

14from .fixes import resolve_fixed 

15from .payload import Payload, repository 

16from .security import security_alert 

17from .signature import signed 

18 

19WORKFLOW_RUN = "workflow_run" 

20PULL_REQUEST = "pull_request" 

21MAIN = "main" 

22MAIN_EVENTS = frozenset({"push", "schedule", "workflow_dispatch"}) 

23JOBS_PAGE = 100 

24REQUEST_TIMEOUT_SECONDS = 10.0 

25 

26 

27def main_run(payload: Payload) -> bool: 

28 run = payload["workflow_run"] 

29 return ( 

30 payload["action"] == "completed" 

31 and run["head_branch"] == MAIN 

32 and run["event"] in MAIN_EVENTS 

33 and run["conclusion"] in RED | {SUCCESS} 

34 ) 

35 

36 

37async def failed_jobs(url: str) -> list[str]: 

38 headers = {"Authorization": f"Bearer {GITHUB_TOKEN}"} 

39 async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT_SECONDS, headers=headers) as client: 

40 response = await client.get(url, params={"filter": "latest", "per_page": JOBS_PAGE}) 

41 response.raise_for_status() 

42 return [job["name"] for job in response.json()["jobs"] if job["conclusion"] in RED] 

43 

44 

45async def record_ci(payload: Payload) -> None: 

46 run = payload["workflow_run"] 

47 jobs = [] if run["conclusion"] == SUCCESS else await failed_jobs(run["jobs_url"]) 

48 with Session(engine) as session: 

49 session.merge( 

50 CiRun( 

51 repository=repository(payload), 

52 workflow=run["name"], 

53 conclusion=run["conclusion"], 

54 failed_jobs=jobs, 

55 url=run["html_url"], 

56 ) 

57 ) 

58 session.commit() 

59 logger.info(f"GitHub: {run['name']} on main of {repository(payload)}: {run['conclusion']}") 

60 

61 

62def github_router(bugsink: BugsinkAlerts) -> APIRouter: 

63 router = APIRouter(prefix="/github", tags=["github"]) 

64 

65 @router.post("/webhook", status_code=status.HTTP_204_NO_CONTENT) 

66 async def receive( 

67 request: Request, 

68 x_github_event: Annotated[str, Header()], 

69 x_hub_signature_256: Annotated[str, Header()], 

70 ) -> None: 

71 body = await request.body() 

72 if not signed(body, x_hub_signature_256, GITHUB_WEBHOOK_SECRET): 

73 raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid signature") 

74 payload = json.loads(body) 

75 if x_github_event == WORKFLOW_RUN and main_run(payload): 

76 await record_ci(payload) 

77 security = security_alert(ALERTS.rules.security_alert, x_github_event, payload) 

78 if security is not None: 

79 await bugsink.track(security.finding, security.opened, utc_now()) 

80 if x_github_event == PULL_REQUEST: 

81 await resolve_fixed(bugsink, payload) 

82 

83 return router