|
| 1 | +"""API router for External Results — session endpoints (BGSTM#300). |
| 2 | +
|
| 3 | +Implements: |
| 4 | + POST /external-results/session – start a run (201 Created) |
| 5 | + PATCH /external-results/session/{id} – finish a run |
| 6 | + GET /external-results/session/{id} – read a session (runner OR user JWT) |
| 7 | +
|
| 8 | +Case-result endpoints → BGSTM#303 |
| 9 | +Artifact endpoints → BGSTM#298 |
| 10 | +Audit-log integration → BGSTM#297 |
| 11 | +""" |
| 12 | + |
| 13 | +from uuid import UUID |
| 14 | + |
| 15 | +from fastapi import APIRouter, Depends, Header, HTTPException, status |
| 16 | +from sqlalchemy.ext.asyncio import AsyncSession |
| 17 | + |
| 18 | +from app.auth.dependencies import ( |
| 19 | + get_current_runner_token, # noqa: F401 — used inside _get_session_auth |
| 20 | + require_runner_scope, |
| 21 | +) |
| 22 | +from app.crud.external_results import create_session, finish_session_db, get_session |
| 23 | +from app.db.session import get_db |
| 24 | +from app.models.runner_token import RunnerToken |
| 25 | +from app.schemas.external_results import SessionCreate, SessionFinish, SessionResponse |
| 26 | + |
| 27 | +router = APIRouter() |
| 28 | + |
| 29 | +_WRITE_SCOPE = "external_results:write" |
| 30 | +_READ_SCOPE = "external_results:read" |
| 31 | + |
| 32 | + |
| 33 | +def _session_to_response(session) -> SessionResponse: |
| 34 | + """Map an ExternalRunSession ORM row to a SessionResponse. |
| 35 | +
|
| 36 | + The ci_url column stores a plain string; SessionResponse expects an |
| 37 | + HttpUrl-compatible value. We pass it through as-is — Pydantic will |
| 38 | + validate and coerce it when constructing the model. |
| 39 | + """ |
| 40 | + return SessionResponse( |
| 41 | + id=session.id, |
| 42 | + status=session.status, |
| 43 | + started_at=session.started_at, |
| 44 | + finished_at=session.finished_at, |
| 45 | + runner=session.runner, |
| 46 | + project_id=session.project_id, |
| 47 | + git_sha=session.git_sha, |
| 48 | + git_branch=session.git_branch, |
| 49 | + ci_url=session.ci_url, |
| 50 | + metadata=session.run_metadata or {}, |
| 51 | + ) |
| 52 | + |
| 53 | + |
| 54 | +# --------------------------------------------------------------------------- |
| 55 | +# POST /external-results/session — start a run |
| 56 | +# --------------------------------------------------------------------------- |
| 57 | + |
| 58 | + |
| 59 | +@router.post( |
| 60 | + "/external-results/session", |
| 61 | + response_model=SessionResponse, |
| 62 | + status_code=status.HTTP_201_CREATED, |
| 63 | +) |
| 64 | +async def create_external_session( |
| 65 | + payload: SessionCreate, |
| 66 | + db: AsyncSession = Depends(get_db), |
| 67 | + token: RunnerToken = Depends(require_runner_scope(_WRITE_SCOPE)), |
| 68 | +) -> SessionResponse: |
| 69 | + """Start a new external test-run session. |
| 70 | +
|
| 71 | + Returns the existing session if an identical session was created within the |
| 72 | + last 60 seconds (idempotency window). |
| 73 | + """ |
| 74 | + session = await create_session(db, payload=payload, runner_token_id=token.id) |
| 75 | + return _session_to_response(session) |
| 76 | + |
| 77 | + |
| 78 | +# --------------------------------------------------------------------------- |
| 79 | +# PATCH /external-results/session/{session_id} — finish a run |
| 80 | +# --------------------------------------------------------------------------- |
| 81 | + |
| 82 | + |
| 83 | +@router.patch( |
| 84 | + "/external-results/session/{session_id}", |
| 85 | + response_model=SessionResponse, |
| 86 | +) |
| 87 | +async def finish_external_session( |
| 88 | + session_id: UUID, |
| 89 | + payload: SessionFinish, |
| 90 | + db: AsyncSession = Depends(get_db), |
| 91 | + token: RunnerToken = Depends(require_runner_scope(_WRITE_SCOPE)), # noqa: ARG001 |
| 92 | +) -> SessionResponse: |
| 93 | + """Set the terminal status of a session. |
| 94 | +
|
| 95 | + Returns 404 if the session does not exist. |
| 96 | + Returns 409 if the status transition is not allowed (e.g. already finished). |
| 97 | + """ |
| 98 | + try: |
| 99 | + session = await finish_session_db(db, session_id=session_id, payload=payload) |
| 100 | + except ValueError as exc: |
| 101 | + detail = exc.args[0] |
| 102 | + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=detail) from exc |
| 103 | + |
| 104 | + if session is None: |
| 105 | + raise HTTPException( |
| 106 | + status_code=status.HTTP_404_NOT_FOUND, |
| 107 | + detail={"code": "session.not_found", "message": f"Session {session_id} does not exist.", "details": None}, |
| 108 | + ) |
| 109 | + |
| 110 | + return _session_to_response(session) |
| 111 | + |
| 112 | + |
| 113 | +# --------------------------------------------------------------------------- |
| 114 | +# GET /external-results/session/{session_id} — read a session |
| 115 | +# --------------------------------------------------------------------------- |
| 116 | + |
| 117 | + |
| 118 | +async def _get_session_auth( |
| 119 | + authorization: str | None = Header(None), |
| 120 | + db: AsyncSession = Depends(get_db), |
| 121 | +): |
| 122 | + """Accept either a runner token or a user JWT for read access. |
| 123 | +
|
| 124 | + We attempt runner-token resolution first; on failure we fall back to user |
| 125 | + JWT. A 401 is raised only when both paths fail. |
| 126 | + """ |
| 127 | + # Try runner-token path |
| 128 | + if authorization and authorization.lower().startswith("bearer bgstm_runner_"): |
| 129 | + from app.auth.dependencies import get_current_runner_token as _get_runner |
| 130 | + |
| 131 | + try: |
| 132 | + return await _get_runner(authorization=authorization, db=db) |
| 133 | + except HTTPException: |
| 134 | + pass |
| 135 | + |
| 136 | + # Fall back to user-JWT path via the bearer scheme |
| 137 | + |
| 138 | + from app.auth.security import decode_access_token |
| 139 | + from app.crud.user import get_user |
| 140 | + |
| 141 | + if authorization and authorization.lower().startswith("bearer "): |
| 142 | + raw_token = authorization.split(" ", 1)[1] |
| 143 | + payload = decode_access_token(raw_token) |
| 144 | + if payload is not None: |
| 145 | + user_id = payload.get("sub") |
| 146 | + if user_id: |
| 147 | + user = await get_user(db, user_id) |
| 148 | + if user and user.is_active: |
| 149 | + return user |
| 150 | + |
| 151 | + raise HTTPException( |
| 152 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 153 | + detail={"code": "runner_token.invalid", "message": "Missing or invalid credentials.", "details": None}, |
| 154 | + ) |
| 155 | + |
| 156 | + |
| 157 | +@router.get( |
| 158 | + "/external-results/session/{session_id}", |
| 159 | + response_model=SessionResponse, |
| 160 | +) |
| 161 | +async def get_external_session( |
| 162 | + session_id: UUID, |
| 163 | + db: AsyncSession = Depends(get_db), |
| 164 | + _auth=Depends(_get_session_auth), |
| 165 | +) -> SessionResponse: |
| 166 | + """Return a single session by ID. |
| 167 | +
|
| 168 | + Accepts either a runner token (any scope) or a standard user JWT. |
| 169 | + Returns 404 if the session does not exist. |
| 170 | + """ |
| 171 | + session = await get_session(db, session_id) |
| 172 | + if session is None: |
| 173 | + raise HTTPException( |
| 174 | + status_code=status.HTTP_404_NOT_FOUND, |
| 175 | + detail={"code": "session.not_found", "message": f"Session {session_id} does not exist.", "details": None}, |
| 176 | + ) |
| 177 | + |
| 178 | + return _session_to_response(session) |
0 commit comments