From cf4553fe2d08eaf2596a60a8d21963c26b109f29 Mon Sep 17 00:00:00 2001 From: johnvin489-cloud Date: Sun, 22 Nov 2026 20:59:10 +0100 Subject: [PATCH 1/4] test(sdk): cover Python SDK packaging and repository gates (#656) --- sdk/python/README.md | 17 +++++++++++ tests/test_sdk_packaging.py | 58 +++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 tests/test_sdk_packaging.py diff --git a/sdk/python/README.md b/sdk/python/README.md index 689080ef..f4ff95ae 100644 --- a/sdk/python/README.md +++ b/sdk/python/README.md @@ -67,3 +67,20 @@ runs against a local mock HTTP server and requires no network access: ```bash pytest tests/test_sdk_python.py ``` + +## Repository gates + +The SDK lives under the root `pyproject.toml` scope, so the normal contributor +gate covers it without a separate configuration: + +```bash +python -m ruff check . +python -m black --check . +python -m pytest tests/test_sdk_python.py tests/test_sdk_packaging.py +``` + +`tests/test_sdk_packaging.py` asserts that the `pyproject.toml` version matches +`ai_code_assistant.__version__`, that the package has no third-party runtime +dependencies, and that this editable-install path stays documented. The version +is changed in both places together when the package is released (see +[`docs/sdk-release.md`](../../docs/sdk-release.md)). diff --git a/tests/test_sdk_packaging.py b/tests/test_sdk_packaging.py new file mode 100644 index 00000000..320de0da --- /dev/null +++ b/tests/test_sdk_packaging.py @@ -0,0 +1,58 @@ +"""Packaging checks for the Phase 12 Python SDK (#656). + +The SDK is intended to be installed with ``pip install -e sdk/python`` and must +be covered by the repository gates. These tests assert the metadata is real +(no placeholder version), stays in sync with the package, and that the +contributor install path is documented. +""" + +from __future__ import annotations + +import sys +import tomllib +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +SDK = ROOT / "sdk" / "python" + +sys.path.insert(0, str(SDK)) + +from ai_code_assistant import Client, __version__ # noqa: E402 + + +def _metadata() -> dict: + return tomllib.loads((SDK / "pyproject.toml").read_text(encoding="utf-8")) + + +def test_pyproject_declares_installable_metadata(): + project = _metadata()["project"] + + assert project["name"] == "ai-code-assistant-sdk" + assert project["version"] == __version__ + assert project["requires-python"] == ">=3.12" + assert project["description"].strip() + assert project["license"]["text"] == "MIT" + + +def test_sdk_has_no_third_party_runtime_dependencies(): + project = _metadata()["project"] + + # A standard-library-only client keeps the test suite offline and avoids a + # dependency surface an SDK consumer did not ask for. + assert project.get("dependencies", []) == [] + + +def test_editable_install_is_documented_for_contributors(): + readme = (SDK / "README.md").read_text(encoding="utf-8") + sdk_readme = (ROOT / "sdk" / "README.md").read_text(encoding="utf-8") + + assert "pip install -e sdk/python" in readme + assert "pip install -e sdk/python" in sdk_readme + assert "pytest tests/test_sdk_python.py" in readme + + +def test_client_requires_a_base_url_and_accepts_an_api_key(): + client = Client("https://api.example.com/", api_token="secret") + + assert client.base_url == "https://api.example.com" + assert client.api_token == "secret" From c0af0471c36b26bf8bb33e86e7ee4a8e53c68dc0 Mon Sep 17 00:00:00 2001 From: johnvin489-cloud Date: Sun, 22 Nov 2026 21:06:45 +0100 Subject: [PATCH 2/4] feat(api): add a filtering and sorting standard for v1 lists (#648) --- README.md | 1 + app/api/filtering.py | 133 ++++++++++++++++++++++++++++++++++++++++++ app/api/v1.py | 123 +++++++++++++++++++++++++++++--------- docs/api-docs.md | 2 +- docs/api-filtering.md | 89 ++++++++++++++++++++++++++++ docs/api-v1.md | 24 +++++--- tests/test_api_v1.py | 97 ++++++++++++++++++++++++++++++ 7 files changed, 433 insertions(+), 36 deletions(-) create mode 100644 app/api/filtering.py create mode 100644 docs/api-filtering.md diff --git a/README.md b/README.md index 71f223dc..9314a1cc 100644 --- a/README.md +++ b/README.md @@ -141,6 +141,7 @@ table, quotas, budgets, alerts, invoices, and reconciliation. - [Security headers and CSP](docs/security-headers.md) - [Dependency policy and SBOM](docs/dependency-policy.md) - [API error catalog](docs/api-errors.md) +- [API filtering and sorting](docs/api-filtering.md) - [API rate limits and quotas](docs/api-rate-limits.md) - [OpenAPI document](docs/api-openapi.md) - [Upgrade guide](docs/upgrade-guide.md) diff --git a/app/api/filtering.py b/app/api/filtering.py new file mode 100644 index 00000000..44218d18 --- /dev/null +++ b/app/api/filtering.py @@ -0,0 +1,133 @@ +"""Filtering, sorting, and unknown-parameter rejection for public lists (#648). + +Public list resources accept a small, explicit query grammar: + +* filters are plain query parameters (``?status=ready``) and must be on the + resource's whitelist; +* ``sort`` names one whitelisted field, and ``order`` is ``asc`` or ``desc``; +* pagination parameters ``page``, ``limit`` and ``cursor`` are handled by + :mod:`app.services.pagination`; +* anything else is rejected instead of silently ignored, so a typo cannot + produce a misleadingly "unfiltered" result. + +Every resource documents its whitelist and default ordering next to the route. +Callers translate :class:`FilterError` into the shared ``invalid_input`` error +shape via :func:`app.api.error_catalog.error_response`. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass, field +from typing import Any + +PAGINATION_PARAMS = frozenset({"page", "limit", "cursor"}) +SORT_PARAMS = frozenset({"sort", "order"}) +ORDERS = ("asc", "desc") + + +class FilterError(ValueError): + """Raised for an unknown parameter, unknown field, or malformed value.""" + + def __init__(self, message: str, *, details: Mapping[str, Any] | None = None) -> None: + super().__init__(message) + self.details = dict(details or {}) + + +@dataclass(frozen=True) +class FilterField: + """One whitelisted filter: its public name, model column, and value kind.""" + + column: str + kind: str = "string" + + +@dataclass(frozen=True) +class ListQuery: + """A validated filter/sort request.""" + + filters: dict[str, Any] = field(default_factory=dict) + sort: str = "id" + column: str = "id" + descending: bool = True + + +def _coerce(name: str, raw: str, kind: str) -> Any: + if kind == "int": + try: + return int(raw) + except (TypeError, ValueError): + raise FilterError(f"{name} must be an integer.") from None + if kind == "bool": + lowered = str(raw).strip().lower() + if lowered in ("1", "true", "yes"): + return True + if lowered in ("0", "false", "no"): + return False + raise FilterError(f"{name} must be true or false.") + return raw + + +def reject_unknown_parameters(args: Mapping[str, Any], allowed: set[str] | frozenset[str]) -> None: + """Raise :class:`FilterError` when ``args`` contains an unexpected name.""" + unknown = sorted(set(args) - set(allowed)) + if unknown: + raise FilterError( + "Unknown query parameter(s): " + + ", ".join(unknown) + + ". Allowed: " + + ", ".join(sorted(allowed)), + details={"unknown": unknown, "allowed": sorted(allowed)}, + ) + + +def parse_list_query( + args: Mapping[str, Any], + *, + filters: Mapping[str, FilterField], + sorts: Mapping[str, str], + default_sort: str = "id", +) -> ListQuery: + """Validate ``args`` against the resource whitelist. + + ``sorts`` maps a public sort name to the model column name. The default + ordering is the default sort field in descending order. + """ + if default_sort not in sorts: + raise ValueError(f"default_sort {default_sort!r} is not a whitelisted sort") + + allowed = set(filters) | set(sorts) | PAGINATION_PARAMS | SORT_PARAMS + reject_unknown_parameters(args, allowed) + + sort = (args.get("sort") or default_sort).strip() + if sort not in sorts: + raise FilterError( + f"Unknown sort field: {sort}. Allowed: " + ", ".join(sorted(sorts)), + details={"field": sort, "allowed": sorted(sorts)}, + ) + + order = (args.get("order") or "desc").strip().lower() + if order not in ORDERS: + raise FilterError( + "order must be 'asc' or 'desc'.", + details={"field": "order", "allowed": list(ORDERS)}, + ) + + parsed: dict[str, Any] = {} + for name, spec in filters.items(): + raw = args.get(name) + if raw is None or raw == "": + continue + parsed[spec.column] = _coerce(name, raw, spec.kind) + + return ListQuery(filters=parsed, sort=sort, column=sorts[sort], descending=order == "desc") + + +__all__ = [ + "PAGINATION_PARAMS", + "FilterError", + "FilterField", + "ListQuery", + "parse_list_query", + "reject_unknown_parameters", +] diff --git a/app/api/v1.py b/app/api/v1.py index 8f6859fe..8ece219c 100644 --- a/app/api/v1.py +++ b/app/api/v1.py @@ -10,6 +10,10 @@ ``current_user.id`` and another user's row is reported as ``404`` (never as a 403 existence oracle). Usage is always scoped to the authenticated user. Errors use the shared code catalog via :func:`error_response`. + +Filtering and sorting follow :mod:`app.api.filtering`: only the whitelisted +fields below are accepted, ``sort``/``order`` are validated, and unknown query +parameters are rejected with a structured ``400``. """ from __future__ import annotations @@ -20,11 +24,43 @@ from flask_login import current_user from app.api.error_catalog import INVALID_INPUT, NOT_FOUND, UNAUTHORIZED, error_response +from app.api.filtering import ( + FilterError, + FilterField, + parse_list_query, + reject_unknown_parameters, +) from app.models import Project, Review from app.services import pagination, usage_ledger bp = Blueprint("api_v1", __name__, url_prefix="/api/v1") +PROJECT_FILTERS = { + "workspace_id": FilterField("workspace_id", "int"), + "source": FilterField("source"), + "status": FilterField("status"), +} +PROJECT_SORTS = { + "id": "id", + "name": "name", + "created_at": "created_at", + "updated_at": "updated_at", +} + +REVIEW_FILTERS = { + "project_id": FilterField("project_id", "int"), + "source": FilterField("source"), + "kind": FilterField("kind"), + "status": FilterField("status"), +} +REVIEW_SORTS = { + "id": "id", + "created_at": "created_at", + "updated_at": "updated_at", + "kind": "kind", + "status": "status", +} + def _login_required(view): @functools.wraps(view) @@ -44,6 +80,14 @@ def _page_request(): return None, error_response(INVALID_INPUT, str(exc)) +def _list_query(filters, sorts): + """Validate filters/sort/order, returning ``(query, error_response)``.""" + try: + return parse_list_query(request.args, filters=filters, sorts=sorts), None + except FilterError as exc: + return None, error_response(INVALID_INPUT, str(exc), details=exc.details) + + def _cursor_id(page) -> int | None: """Return the opaque cursor's ``id``, or ``None`` when absent.""" if page.cursor is None: @@ -56,14 +100,22 @@ def _cursor_id(page) -> int | None: return value -def _paginate(query, model, page): - """Return ``(rows, total, next_cursor)`` for a stable id-ordered list.""" +def _paginate(query, model, page, options): + """Return ``(rows, total, next_cursor)`` for a deterministic sorted list.""" total = query.count() cursor_id = _cursor_id(page) - query = query.order_by(model.id.desc()) + column = getattr(model, options.column) + direction = column.desc if options.descending else column.asc + id_direction = model.id.desc if options.descending else model.id.asc if cursor_id is not None: - query = query.filter(model.id < cursor_id) - else: + # A cursor continues from the id of the last row, so it is only + # meaningful for the default id ordering. + if options.sort != "id": + raise FilterError("Cursor pagination requires sort=id.") + query = query.filter(model.id < cursor_id if options.descending else model.id > cursor_id) + ordering = [id_direction()] if options.sort == "id" else [direction(), id_direction()] + query = query.order_by(*ordering) + if cursor_id is None: query = query.offset((page.page - 1) * page.limit) rows = query.limit(page.limit + 1).all() has_more = len(rows) > page.limit @@ -72,12 +124,14 @@ def _paginate(query, model, page): return rows, total, next_cursor -def _list_payload(items, total, page, next_cursor): +def _list_payload(items, total, page, options, next_cursor): return { "items": items, "total": total, "page": page.page, "limit": page.limit, + "sort": options.sort, + "order": "desc" if options.descending else "asc", "next_cursor": next_cursor, } @@ -96,22 +150,28 @@ def _optional_int(name: str): @bp.route("/projects", methods=["GET"]) @_login_required def list_projects(): - """List the caller's projects, newest id first.""" + """List the caller's projects, newest id first by default. + + Filters: ``workspace_id``, ``source``, ``status``. Sorts: ``id``, ``name``, + ``created_at``, ``updated_at``. + """ page, error = _page_request() if error is not None: return error - - workspace_id, error = _optional_int("workspace_id") + options, error = _list_query(PROJECT_FILTERS, PROJECT_SORTS) if error is not None: return error + query = Project.query.filter_by(user_id=current_user.id) - if workspace_id is not None: - query = query.filter_by(workspace_id=workspace_id) + for column, value in options.filters.items(): + query = query.filter_by(**{column: value}) try: - rows, total, next_cursor = _paginate(query, Project, page) - except pagination.PaginationError as exc: + rows, total, next_cursor = _paginate(query, Project, page, options) + except (pagination.PaginationError, FilterError) as exc: return error_response(INVALID_INPUT, str(exc)) - return jsonify(_list_payload([row.to_dict() for row in rows], total, page, next_cursor)) + return jsonify( + _list_payload([row.to_dict() for row in rows], total, page, options, next_cursor) + ) @bp.route("/projects/", methods=["GET"]) @@ -127,27 +187,29 @@ def get_project(project_id: int): @bp.route("/reviews", methods=["GET"]) @_login_required def list_reviews(): - """List the caller's reviews, newest id first.""" + """List the caller's reviews, newest id first by default. + + Filters: ``project_id``, ``source``, ``kind``, ``status``. Sorts: ``id``, + ``created_at``, ``updated_at``, ``kind``, ``status``. + """ page, error = _page_request() if error is not None: return error - - query = Review.query.filter_by(user_id=current_user.id) - for name in ("source", "kind", "status"): - value = request.args.get(name) - if value: - query = query.filter_by(**{name: value}) - project_id, error = _optional_int("project_id") + options, error = _list_query(REVIEW_FILTERS, REVIEW_SORTS) if error is not None: return error - if project_id is not None: - query = query.filter_by(project_id=project_id) + + query = Review.query.filter_by(user_id=current_user.id) + for column, value in options.filters.items(): + query = query.filter_by(**{column: value}) try: - rows, total, next_cursor = _paginate(query, Review, page) - except pagination.PaginationError as exc: + rows, total, next_cursor = _paginate(query, Review, page, options) + except (pagination.PaginationError, FilterError) as exc: return error_response(INVALID_INPUT, str(exc)) - return jsonify(_list_payload([row.to_dict() for row in rows], total, page, next_cursor)) + return jsonify( + _list_payload([row.to_dict() for row in rows], total, page, options, next_cursor) + ) @bp.route("/reviews/", methods=["GET"]) @@ -171,6 +233,13 @@ def list_usage(): return error_response( INVALID_INPUT, "Cursor pagination is not supported here; use page and limit." ) + try: + reject_unknown_parameters( + request.args, + {"page", "limit", "cursor", "workspace_id", "project_id", "source"}, + ) + except FilterError as exc: + return error_response(INVALID_INPUT, str(exc), details=exc.details) workspace_id, error = _optional_int("workspace_id") if error is not None: diff --git a/docs/api-docs.md b/docs/api-docs.md index cceaf1be..554bb156 100644 --- a/docs/api-docs.md +++ b/docs/api-docs.md @@ -28,4 +28,4 @@ with inline CSS. Re-run it whenever a public route changes. - Authentication, pagination, errors, and webhook verification are documented on the generated page and link to their full guides: [API errors](api-errors.md), [pagination](pagination.md), - [webhooks](webhooks.md). + [filtering and sorting](api-filtering.md), [webhooks](webhooks.md). diff --git a/docs/api-filtering.md b/docs/api-filtering.md new file mode 100644 index 00000000..7b142590 --- /dev/null +++ b/docs/api-filtering.md @@ -0,0 +1,89 @@ +# Filtering and sorting standard + +Public list resources accept one query grammar, implemented in +[`app/api/filtering.py`](../app/api/filtering.py). The same rules apply to every +resource: only whitelisted fields are accepted, the default ordering is +documented, and an unknown parameter is an error rather than a silently ignored +typo. + +## Query parameters + +| Parameter | Meaning | +| --- | --- | +| `=` | Exact-match filter. The field must be on the resource whitelist. | +| `sort=` | One whitelisted sort field. Defaults to the resource's default ordering (always `id`). | +| `order=asc\|desc` | Sort direction. Defaults to `desc`. | +| `page`, `limit`, `cursor` | The [pagination contract](pagination.md). | + +Whitelisted fields are listed per endpoint below. A repeated parameter keeps +the last value, matching normal query-string handling. + +## Ordering + +The default ordering is newest id first: `sort=id&order=desc`. It is stable +because `id` is unique. A named sort always adds `id` as a tie-breaker in the +same direction, so equal values still have a deterministic order. + +`cursor` continues from the id of the last row of the previous page. It is only +valid with the default ordering; combining a cursor with another sort returns +`400 invalid_input` (`Cursor pagination requires sort=id.`) instead of silently +producing gaps or duplicates. Use `page`/`limit` for custom sorts. + +## Resources + +### `GET /api/v1/projects` + +| Filters | Sort fields | +| --- | --- | +| `workspace_id` (integer), `source`, `status` | `id`, `name`, `created_at`, `updated_at` | + +Default: `sort=id&order=desc`. See the [v1 reference](api-v1.md). + +### `GET /api/v1/reviews` + +| Filters | Sort fields | +| --- | --- | +| `project_id` (integer), `source`, `kind`, `status` | `id`, `created_at`, `updated_at`, `kind`, `status` | + +Default: `sort=id&order=desc`. + +### `GET /api/v1/usage` + +Usage keeps its dedicated `workspace_id`, `project_id`, and `source` filters +and its fixed ledger ordering. It does not accept `sort` or `order`; sending +either is rejected as an unknown parameter. Use the usage export filters +documented in [usage privacy](usage-privacy.md). + +## Errors + +An unknown parameter, an unknown sort field, a malformed value, or an invalid +order returns `400` with the shared [error catalog](api-errors.md) shape. The +`details` object names the offending field and, where useful, the accepted +values: + +```json +{ + "error": "Unknown query parameter(s): stauts. Allowed: created_at, cursor, id, limit, name, order, page, sort, source, status, updated_at, workspace_id", + "kind": "invalid", + "code": "invalid_input", + "details": { + "unknown": ["stauts"], + "allowed": ["created_at", "cursor", "id", "limit", "name", "order", "page", "sort", "source", "status", "updated_at", "workspace_id"] + } +} +``` + +```json +{ + "error": "Unknown sort field: summary. Allowed: created_at, id, kind, status, updated_at", + "kind": "invalid", + "code": "invalid_input", + "details": {"field": "summary", "allowed": ["created_at", "id", "kind", "status", "updated_at"]} +} +``` + +## Tests + +[`tests/test_api_v1.py`](../tests/test_api_v1.py) covers default ordering, +whitelisted filters and sorts, unknown-parameter rejection with `details`, an +invalid `order`, the cursor/sort rule, and the unsupported usage parameters. diff --git a/docs/api-v1.md b/docs/api-v1.md index 78d4c94f..ead0f037 100644 --- a/docs/api-v1.md +++ b/docs/api-v1.md @@ -2,8 +2,9 @@ Stable, versioned JSON resources for projects, reviews, and usage. The implementation is `app/api/v1.py`; errors use the -[API error catalog](api-errors.md) and lists use the -[pagination contract](pagination.md). +[API error catalog](api-errors.md), lists use the +[pagination contract](pagination.md), and filters/sort use the +[filtering and sorting standard](api-filtering.md). All endpoints require an authenticated session or API key. Unauthenticated calls return `401 {"code": "unauthorized"}`. @@ -15,9 +16,11 @@ calls return `401 {"code": "unauthorized"}`. | `GET` | `/api/v1/projects` | List the caller's projects (newest id first). | | `GET` | `/api/v1/projects/` | Return one project owned by the caller. | -Query parameters: `workspace_id` (optional filter), plus `page`, `limit`, and -`cursor`. A project owned by another user is `404 not_found`, matching the web -UI's owner-scoped project lookup. +Query parameters: `workspace_id` (optional filter), `source`, `status`, plus +`sort`/`order` (`id` default, then `name`, `created_at`, `updated_at`) and +`page`, `limit`, and `cursor`. A project owned by another user is +`404 not_found`, matching the web UI's owner-scoped project lookup. See the +[filtering standard](api-filtering.md) for validation and error shapes. Response item schema: @@ -46,8 +49,10 @@ Response item schema: | `GET` | `/api/v1/reviews` | List the caller's reviews (newest id first). | | `GET` | `/api/v1/reviews/` | Return one review owned by the caller. | -Query parameters: `source`, `kind`, `status`, `project_id`, plus pagination. -Only the caller's reviews are visible; another user's review is `404`. +Query parameters: `source`, `kind`, `status`, `project_id`, plus +`sort`/`order` (`id` default, then `created_at`, `updated_at`, `kind`, +`status`) and pagination. Only the caller's reviews are visible; another +user's review is `404`. Response item schema: @@ -82,7 +87,8 @@ It reuses the existing usage export service, so the schema is the same `page_totals`, and `records`. Optional filters are `workspace_id`, `project_id`, and `source`. Cursor pagination is not supported here; use `page` and `limit` (a cursor returns `400 invalid_input` rather than being -silently ignored). +silently ignored). It does not accept `sort`/`order`; those are rejected as +unknown parameters (see the [filtering standard](api-filtering.md)). ## List envelope @@ -92,6 +98,8 @@ silently ignored). "total": 42, "page": 1, "limit": 50, + "sort": "id", + "order": "desc", "next_cursor": null } ``` diff --git a/tests/test_api_v1.py b/tests/test_api_v1.py index 63080a23..1de12cba 100644 --- a/tests/test_api_v1.py +++ b/tests/test_api_v1.py @@ -200,6 +200,103 @@ def test_invalid_project_filter_is_structured(self, client, make_user, login): assert response.get_json()["code"] == "invalid_input" +class TestFilteringAndSorting: + def test_projects_sort_and_filter_by_whitelisted_fields(self, client, make_user, login): + user = make_user() + login() + workspace = _workspace(user) + zulu = _project(user, workspace, "Zulu") + _project(user, workspace, "Alpha") + failed = Project( + workspace_id=workspace.id, + user_id=user.id, + name="Alpha", + source=SOURCE_ARCHIVE, + status="failed", + ) + db.session.add(failed) + db.session.commit() + + response = client.get("/api/v1/projects?sort=name&order=asc") + payload = response.get_json() + + assert response.status_code == 200 + assert payload["sort"] == "name" + assert payload["order"] == "asc" + assert [item["name"] for item in payload["items"]] == ["Alpha", "Alpha", "Zulu"] + + filtered = client.get("/api/v1/projects?status=failed").get_json() + assert [item["id"] for item in filtered["items"]] == [failed.id] + assert zulu.id not in [item["id"] for item in filtered["items"]] + + def test_reviews_sort_by_whitelisted_field(self, client, make_user, login): + user = make_user() + login() + project = _project(user, _workspace(user)) + running = _review(user, project, kind="security") + running.status = "running" + completed = _review(user, project, kind="quality") + db.session.commit() + + payload = client.get("/api/v1/reviews?sort=status&order=asc").get_json() + + assert [item["id"] for item in payload["items"]] == [completed.id, running.id] + + def test_unknown_filter_parameter_is_rejected_with_details(self, client, make_user, login): + make_user() + login() + + response = client.get("/api/v1/projects?stauts=ready") + + assert response.status_code == 400 + payload = response.get_json() + assert payload["code"] == "invalid_input" + assert payload["details"]["unknown"] == ["stauts"] + assert "status" in payload["details"]["allowed"] + + def test_unknown_sort_field_is_rejected_with_details(self, client, make_user, login): + make_user() + login() + + response = client.get("/api/v1/reviews?sort=summary") + + assert response.status_code == 400 + payload = response.get_json() + assert payload["code"] == "invalid_input" + assert payload["details"]["field"] == "summary" + + def test_invalid_order_is_rejected(self, client, make_user, login): + make_user() + login() + + response = client.get("/api/v1/projects?sort=name&order=sideways") + + assert response.status_code == 400 + assert response.get_json()["code"] == "invalid_input" + + def test_cursor_requires_the_id_ordering(self, client, make_user, login): + user = make_user() + login() + workspace = _workspace(user) + _project(user, workspace, "First") + _project(user, workspace, "Second") + + page = client.get("/api/v1/projects?limit=1").get_json() + response = client.get(f"/api/v1/projects?sort=name&limit=1&cursor={page['next_cursor']}") + + assert response.status_code == 400 + assert "sort=id" in response.get_json()["error"] + + def test_usage_rejects_unsupported_query_parameters(self, client, make_user, login): + make_user() + login() + + response = client.get("/api/v1/usage?sort=id") + + assert response.status_code == 400 + assert response.get_json()["code"] == "invalid_input" + + class TestUsage: def test_usage_is_scoped_to_the_caller(self, client, make_user, login): user = make_user() From 0e1aa388b39c0236a49df349dfb963bd83816632 Mon Sep 17 00:00:00 2001 From: johnvin489-cloud Date: Sun, 22 Nov 2026 21:08:44 +0100 Subject: [PATCH 3/4] docs(audit): add the audit and compliance guide (#642) --- README.md | 1 + docs/audit-compliance-guide.md | 179 +++++++++++++++++++++++++++ tests/test_audit_compliance_guide.py | 79 ++++++++++++ 3 files changed, 259 insertions(+) create mode 100644 docs/audit-compliance-guide.md create mode 100644 tests/test_audit_compliance_guide.py diff --git a/README.md b/README.md index 9314a1cc..57eae944 100644 --- a/README.md +++ b/README.md @@ -148,6 +148,7 @@ table, quotas, budgets, alerts, invoices, and reconciliation. - [Changelog](CHANGELOG.md) - [Admin action audit view](docs/admin-actions.md) - [Audit log integrity](docs/audit-integrity.md) +- [Audit and compliance guide](docs/audit-compliance-guide.md) - [Audit retention and legal hold](docs/audit-retention.md) - [Data classification](docs/data-classification.md) - [Compliance evidence pack](docs/compliance-evidence.md) diff --git a/docs/audit-compliance-guide.md b/docs/audit-compliance-guide.md new file mode 100644 index 00000000..49e251a3 --- /dev/null +++ b/docs/audit-compliance-guide.md @@ -0,0 +1,179 @@ +# Audit and compliance guide + +This guide is the entry point for auditors, customer security reviewers, and +operators. It explains what the product records, how long it is kept, how to +export it, and what the evidence pack does **not** certify. It links to the +detailed guides instead of restating them, so there is one source of truth per +topic. + +| Topic | Detailed guide | +| --- | --- | +| Append-only log and hash chain | [Audit log integrity](audit-integrity.md) | +| Retention window, purge, legal hold | [Audit retention and legal hold](audit-retention.md) | +| Evidence pack contents and limits | [Compliance evidence pack](compliance-evidence.md) | +| Field-level export controls | [Data classification](data-classification.md) | +| Admin investigation view and export | [Admin action audit view](admin-actions.md) | + +## What is audited + +Sensitive and security-relevant actions append a row to `audit_logs`. Rows are +written through `app.services.audit.record` and are never updated or deleted by +the application. Examples include authentication success/failure, account +creation, conversation and prompt deletion, budget and pricing changes, audit +exports, user data-export lifecycle events, SIEM endpoint changes, and domain +verification/SSO enforcement changes. + +Each row records: + +| Field | Meaning | +| --- | --- | +| `workspace_id` | Workspace whose hash chain the row belongs to; `NULL` is the global chain. | +| `user_id` | Acting account, or `NULL` for an unauthenticated event such as a failed login. | +| `action` | Stable action name, for example `login_success`. | +| `target_type`, `target_id` | The affected object, when there is one. | +| `metadata` | Small contextual JSON blob. It is hashed but is not part of public exports. | +| `prev_hash`, `record_hash` | SHA-256 chain link used by `flask audit verify`. | +| `created_at` | UTC timestamp. | + +The action list is not a complete list of every database write. It covers +security-relevant and administrative operations, not routine content reads. +Request bodies, prompts, message content, and secrets are not written to the +audit log. + +### Integrity check + +```bash +flask audit verify +flask audit verify --workspace-id 7 --json +``` + +Exit status is `0` for intact chains, `1` when a modified or missing row is +found, and `2` for invalid input. The chain detects edits and deletions of +middle rows. It cannot prove that the newest rows were not truncated; keep +database backups or publish the latest `record_hash` externally if that matters +for your threat model. Legacy rows with `NULL` hashes are reported as +`unhashed`, never as tampered. Full semantics are in +[audit log integrity](audit-integrity.md). + +## Retention + +Retention is per workspace and lives in `audit_retention_policies`. A workspace +with no policy uses **365 days** and no legal hold. The accepted window is +**1 to 3650 days**. + +```bash +flask audit retention show --workspace-id 7 +flask audit retention set --workspace-id 7 --days 90 +flask audit retention set --workspace-id 7 --legal-hold +flask audit retention set --workspace-id 7 --no-legal-hold +flask audit purge --workspace-id 7 --dry-run +flask audit purge --workspace-id 7 +``` + +`flask audit purge` deletes audit rows **strictly older** than +`now - retention_days`; a row exactly at the cutoff is retained. The purge only +touches that workspace's audit rows. Global rows (`workspace_id IS NULL`) are +not removed by a workspace policy. Run the purge from a scheduler (cron, a +Kubernetes CronJob, or your platform scheduler) and use `--dry-run` after +changing a window. Details: [audit retention and legal hold](audit-retention.md). + +### Legal hold and deletion + +A legal hold always wins over age: while it is active, `flask audit purge` +deletes nothing and reports `skipped_reason: "legal_hold"`. Releasing it with +`--no-legal-hold` lets the next scheduled run proceed. Holds are per workspace +and do not expire automatically. + +Deletion behaviour follows the same boundaries as the rest of the data model: + +- Deleting a **workspace** cascades to its audit rows and retention policy. +- Deleting a **user account** sets `user_id` to `NULL` on retained audit rows, + preserving the historical action without the identity link. `user_id` is + deliberately excluded from the hash, so this does not make the chain look + tampered. +- A legal hold blocks **audit retention purge only**. It is not a general + account-deletion or data-export control; use the user data export workflow + ([user data export](user-data-export.md)) for a copy of account data. + +## Exporting evidence + +### Audit export endpoint + +`GET /admin/audit/export` streams the audit rows an administrator is allowed to +see. It requires an authenticated admin; non-admins receive +`403 forbidden` in the shared [error catalog](api-errors.md) shape. + +| Query parameter | Meaning | +| --- | --- | +| `format` | `json` (default) or `csv`. | +| `actor` | Exact username. Unknown names return no rows. | +| `action` | Exact action name. | +| `resource_type`, `resource_id` | Exact target type and id. | +| `start`, `end` | Inclusive `YYYY-MM-DD` dates. | +| `limit` | Maximum rows, 1-50000 (default 10000). | + +The projection is fixed at the `internal` classification level: actor +usernames, the metadata blob, secrets, and prompt content are never exported. +Every export appends an `audit_exported` entry for the admin who ran it. Use +the investigation view at `/admin/actions` when you need to browse rather than +download; `/admin/actions?format=json` returns the same whitelisted rows. + +### Workspace audit API + +Owners can read the defined workspace audit event subset at +`GET /workspaces/api/workspaces//audit`. It supports `event_type` and +`actor` filters and page/per-page pagination, and requires the owner-level +`view_audit` capability. Non-members receive a uniform `404`; members without +the capability receive `403`. + +### Evidence pack + +```python +from app.services.evidence_pack import build_evidence_pack + +pack = build_evidence_pack(workspace_id, actor=current_user) +``` + +The pack is a bounded JSON document containing the audit export and chain +verification result, an access review, the effective retention/legal-hold +policy, and non-secret security switches. Collections are capped and carry a +`truncated` flag. Fields are projected through the +[data classification](data-classification.md) helper at `internal` level, so +usernames, emails, metadata blobs, and secrets are excluded. + +An actor without the owner-level `view_audit` capability gets +`PermissionError`; an unknown workspace gets `LookupError`. The operator path +(`actor=None`, for example a CLI maintenance job) relies on deployment +credentials instead, the same trust model as the other `flask audit` commands. + +## What the evidence pack does and does not certify + +The pack is **evidence, not a certification**. The payload states this +explicitly with `"certification": false` and the disclaimer: + +> This pack is evidence of current configuration and recent activity. It is +> not a certification, attestation, or audit opinion. + +It **does** show the current configuration and recent activity at the time it +was generated, and it records whether the audit chains verified at that moment. + +It **does not** certify that any framework (SOC 2, ISO 27001, GDPR, and so on) +is met, and it is not an audit opinion or an attestation. It does not +reconstruct historical state, prove that logs were never deleted outside the +application, or replace evidence from the hosting platform, identity provider, +or database backups. See [compliance evidence pack](compliance-evidence.md) for +the control-by-control contents and limits. + +## Reproduction checklist + +A reviewer who wants to reproduce the evidence can: + +1. Run `flask audit verify --json` and keep the output. +2. Run `flask audit retention show --workspace-id --json`. +3. Download `GET /admin/audit/export?format=json&start=...&end=...` with an + admin session and keep the file plus the `X-Export-Limit` header. +4. Call `build_evidence_pack()` in a maintenance shell (or as the workspace + owner) and keep the JSON output. +5. Record the date, deployment revision, and who ran each command. The pack + describes current state; a review that needs history must retain these + exports over time. diff --git a/tests/test_audit_compliance_guide.py b/tests/test_audit_compliance_guide.py new file mode 100644 index 00000000..a65f306b --- /dev/null +++ b/tests/test_audit_compliance_guide.py @@ -0,0 +1,79 @@ +"""The audit and compliance guide documents real commands/endpoints (#642).""" + +from __future__ import annotations + +import re +from pathlib import Path + +from click.testing import CliRunner + +from app.services.evidence_pack import DISCLAIMER + +ROOT = Path(__file__).resolve().parents[1] +GUIDE = ROOT / "docs" / "audit-compliance-guide.md" + + +def _guide() -> str: + return GUIDE.read_text(encoding="utf-8") + + +def _cli(app, *args: str): + return CliRunner().invoke(app.cli, list(args)) + + +def test_documented_audit_commands_and_options_exist(app): + audit = app.cli.commands["audit"] + assert {"verify", "purge", "retention"} <= set(audit.commands) + retention = audit.commands["retention"] + assert {"show", "set"} <= set(retention.commands) + + documented = [ + (("audit", "verify"), ("--workspace-id", "--json")), + (("audit", "retention", "show"), ("--workspace-id", "--json")), + ( + ("audit", "retention", "set"), + ("--workspace-id", "--days", "--legal-hold", "--no-legal-hold"), + ), + (("audit", "purge"), ("--workspace-id", "--dry-run")), + ] + for command, options in documented: + result = _cli(app, *command, "--help") + assert result.exit_code == 0, result.output + for option in options: + assert option in result.output, f"{' '.join(command)} lacks {option}" + + +def test_documented_endpoints_are_registered(app): + rules = {rule.rule for rule in app.url_map.iter_rules()} + + assert "/admin/audit/export" in rules + assert "/admin/actions" in rules + assert any( + rule.startswith("/workspaces/api/workspaces/") and rule.endswith("/audit") for rule in rules + ), "workspace audit API is not registered" + + +def test_guide_links_the_existing_audit_docs_and_keeps_the_disclaimer(): + text = _guide() + + for target in ( + "audit-integrity.md", + "audit-retention.md", + "compliance-evidence.md", + "data-classification.md", + "admin-actions.md", + ): + assert target in text, f"guide does not link {target}" + + assert "not a certification, attestation, or audit opinion" in DISCLAIMER + assert "not a certification, attestation, or audit opinion" in text + assert "3650" in text + assert "legal_hold" in text + + +def test_every_documented_flask_audit_command_is_documented_in_the_cli_help(app): + """Every `flask audit ...` command in the guide resolves to a real command.""" + commands = set(re.findall(r"flask audit ([a-z-]+)", _guide())) + assert commands, "the guide no longer documents any audit commands" + audit = app.cli.commands["audit"] + assert commands <= set(audit.commands), commands - set(audit.commands) From 4942a1d70a6cf352c254405ce17e5efc9ec6d67a Mon Sep 17 00:00:00 2001 From: johnvin489-cloud Date: Sun, 22 Nov 2026 21:22:36 +0100 Subject: [PATCH 4/4] feat(integrations): create Jira or Linear tickets for acknowledged high-risk findings (#630) --- README.md | 1 + app/api/error_catalog.py | 8 + app/models/__init__.py | 2 + app/models/security_ticket.py | 69 +++ app/reviews/routes.py | 20 +- app/services/security_tickets.py | 450 ++++++++++++++++++ docs/api-errors.md | 1 + docs/security-ticketing.md | 118 +++++ .../a3b4c5d6e7f8_add_security_ticket_links.py | 85 ++++ tests/test_security_tickets.py | 357 ++++++++++++++ 10 files changed, 1109 insertions(+), 2 deletions(-) create mode 100644 app/models/security_ticket.py create mode 100644 app/services/security_tickets.py create mode 100644 docs/security-ticketing.md create mode 100644 migrations/versions/a3b4c5d6e7f8_add_security_ticket_links.py create mode 100644 tests/test_security_tickets.py diff --git a/README.md b/README.md index 57eae944..d2ba294c 100644 --- a/README.md +++ b/README.md @@ -134,6 +134,7 @@ table, quotas, budgets, alerts, invoices, and reconciliation. - [Plugin artifact cache](docs/plugin-artifact-cache.md) - [Encrypted integration credentials](docs/integration-credentials.md) - [Integration setup and local mocks](docs/integrations.md) +- [Security ticketing (Jira and Linear)](docs/security-ticketing.md) - [GitLab integration](docs/gitlab.md) - [Webhooks, delivery logs, and dead-letter replay](docs/webhooks.md) - [Architecture](docs/architecture.md) diff --git a/app/api/error_catalog.py b/app/api/error_catalog.py index 62991fb9..afc1ca66 100644 --- a/app/api/error_catalog.py +++ b/app/api/error_catalog.py @@ -25,6 +25,7 @@ RATE_LIMITED = "rate_limited" GONE = "gone" INTERNAL_ERROR = "internal_error" +BAD_GATEWAY = "bad_gateway" @dataclass(frozen=True) @@ -74,6 +75,13 @@ class ApiError: INTERNAL_ERROR: ApiError( INTERNAL_ERROR, 500, "internal_error", "Something went wrong.", "Unexpected server error." ), + BAD_GATEWAY: ApiError( + BAD_GATEWAY, + 502, + "upstream_error", + "An upstream service failed to complete the request.", + "A third-party delivery failed.", + ), } STATUS_TO_CODE = {entry.status: entry.code for entry in CATALOG.values()} diff --git a/app/models/__init__.py b/app/models/__init__.py index 0d400944..ffe4c352 100644 --- a/app/models/__init__.py +++ b/app/models/__init__.py @@ -44,6 +44,7 @@ from app.models.review_comment import ReviewComment from app.models.review_config import ReviewConfig from app.models.review_finding import ReviewFinding +from app.models.security_ticket import SecurityTicketLink from app.models.siem_endpoint import SiemEndpoint from app.models.stellar_security_finding import StellarSecurityFinding from app.models.usage_record import UsageRecord @@ -106,6 +107,7 @@ "ReviewComment", "ReviewConfig", "ReviewFinding", + "SecurityTicketLink", "SiemEndpoint", "StellarSecurityFinding", "UsageRecord", diff --git a/app/models/security_ticket.py b/app/models/security_ticket.py new file mode 100644 index 00000000..3e7255f5 --- /dev/null +++ b/app/models/security_ticket.py @@ -0,0 +1,69 @@ +"""Durable links from security findings to external tickets (#630). + +One row per ``(workspace_id, finding_id)`` is the duplicate guard: retrying an +acknowledgement returns the stored ticket instead of creating another issue. +``(provider, external_key)`` is also unique so the same external issue cannot +be recorded twice. +""" + +from datetime import UTC, datetime + +from app.extensions import db + + +class SecurityTicketLink(db.Model): + """A high-risk finding exported to Jira or Linear when acknowledged.""" + + __tablename__ = "security_ticket_links" + __table_args__ = ( + db.UniqueConstraint( + "workspace_id", + "finding_id", + name="uq_security_ticket_links_workspace_finding", + ), + db.UniqueConstraint( + "provider", + "external_key", + name="uq_security_ticket_links_provider_external", + ), + db.Index("ix_security_ticket_links_workspace_created", "workspace_id", "created_at"), + ) + + id = db.Column(db.Integer, primary_key=True) + workspace_id = db.Column( + db.Integer, + db.ForeignKey("workspaces.id", ondelete="CASCADE"), + nullable=False, + index=True, + ) + finding_id = db.Column( + db.Integer, + db.ForeignKey("review_findings.id", ondelete="CASCADE"), + nullable=False, + index=True, + ) + provider = db.Column(db.String(20), nullable=False) + external_key = db.Column(db.String(100), nullable=False, index=True) + external_url = db.Column(db.String(500), nullable=True) + severity = db.Column(db.String(20), nullable=False) + created_at = db.Column( + db.DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC) + ) + + def to_dict(self) -> dict: + return { + "id": self.id, + "workspace_id": self.workspace_id, + "finding_id": self.finding_id, + "provider": self.provider, + "external_key": self.external_key, + "external_url": self.external_url, + "severity": self.severity, + "created_at": self.created_at.isoformat() if self.created_at else None, + } + + def __repr__(self) -> str: # pragma: no cover - debugging aid + return ( + f"" + ) diff --git a/app/reviews/routes.py b/app/reviews/routes.py index e7d4d785..42eabfc7 100644 --- a/app/reviews/routes.py +++ b/app/reviews/routes.py @@ -25,6 +25,7 @@ from flask import Response, jsonify, render_template, request from flask_login import current_user, login_required +from app.api.error_catalog import error_code_for_status, error_response from app.extensions import db from app.models import Project, Review, ReviewConfig, ReviewFinding, Workspace from app.models.project import STATUS_READY @@ -38,7 +39,7 @@ ) from app.models.review_finding import CATEGORIES_BY_KIND, SEVERITIES from app.reviews import bp -from app.services import budgets, chat_audit, usage_ledger +from app.services import budgets, chat_audit, security_tickets, usage_ledger from app.services import metrics as metrics_service from app.services import reviews as reviews_service from app.services.events import emit_event @@ -639,8 +640,23 @@ def api_update_finding(finding_id: int): data = request.get_json(silent=True) or {} if "addressed" in data: finding.addressed = bool(data["addressed"]) + ticket = None + if finding.addressed and bool(data.get("addressed")): + # Acknowledging a high-risk finding is the trigger for the optional + # ticketing integration. A retried request reaches the service again + # and returns the stored link instead of creating a duplicate. A + # delivery failure rolls the acknowledgement back and returns a + # structured error. + try: + ticket = security_tickets.create_for_acknowledged_finding(finding) + except security_tickets.TicketingError as exc: + db.session.rollback() + return error_response(error_code_for_status(exc.http_status), str(exc)) db.session.commit() - return jsonify(finding.to_dict()) + payload = finding.to_dict() + if ticket is not None: + payload["ticket"] = ticket.to_dict() + return jsonify(payload) # -------------------------------------------------------------------------- diff --git a/app/services/security_tickets.py b/app/services/security_tickets.py new file mode 100644 index 00000000..e08afe8e --- /dev/null +++ b/app/services/security_tickets.py @@ -0,0 +1,450 @@ +"""Create Jira or Linear tickets when a high-risk finding is acknowledged (#630). + +The workspace opts in by storing encrypted credentials through +:mod:`app.services.integration_credentials` (``integration="ticketing"``). When +a finding with severity ``critical`` or ``high`` transitions to +``addressed=True``, :func:`create_for_acknowledged_finding` creates a ticket in +the configured provider. + +Safety properties: + +* The request payload is built from known finding fields, every string is + length-bounded, and the encoded JSON is capped at :data:`MAX_REQUEST_BYTES`. +* A durable :class:`~app.models.security_ticket.SecurityTicketLink` row keyed by + ``(workspace_id, finding_id)`` makes retries idempotent: the second call + returns the stored link without contacting the provider. +* Misses (not acknowledged, not high risk, no workspace, not configured) are + no-ops; real failures raise a typed :class:`TicketingError` with a stable + code and HTTP status. +* Callers can inject ``post`` so tests use a mocked provider, never the network. +""" + +from __future__ import annotations + +import hashlib +import json +import re +from urllib.parse import urlparse + +import requests +from flask import current_app + +from app.extensions import db +from app.models import Review, ReviewFinding, SecurityTicketLink +from app.services.integration_credentials import ( + IntegrationCredentialError, + set_credential, +) +from app.services.integrations.common import ( + IntegrationNotConfigured, + credential_names, + load_credential_value, + sanitize_error, +) + +INTEGRATION = "ticketing" +PROVIDERS = ("jira", "linear") +HIGH_RISK_SEVERITIES = frozenset({"critical", "high"}) + +REQUIRED_CREDENTIALS = { + "jira": ("base_url", "email", "api_token", "project_key"), + "linear": ("api_token", "team_id"), +} + +MAX_TITLE = 200 +MAX_DESCRIPTION = 4000 +MAX_REQUEST_BYTES = 16_384 + +LINEAR_ENDPOINT = "https://api.linear.app/graphql" +LINEAR_MUTATION = ( + "mutation IssueCreate($input: IssueCreateInput!) {" + " issueCreate(input: $input) { success issue { identifier url } } }" +) + +_PROJECT_KEY_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]{0,49}$") + +JIRA_PRIORITY = {"critical": "Highest", "high": "High"} +LINEAR_PRIORITY = {"critical": 1, "high": 2} + + +class TicketingError(ValueError): + """Base class for structured ticketing errors.""" + + code = "ticketing_error" + http_status = 400 + + +class TicketingValidationError(TicketingError): + code = "invalid_input" + + +class TicketingPermissionError(TicketingError, PermissionError): + code = "permission_denied" + http_status = 403 + + +class TicketingNotConfigured(TicketingError): + code = "not_configured" + http_status = 409 + + +class TicketingNotFound(TicketingError): + code = "not_found" + http_status = 404 + + +class TicketingDeliveryError(TicketingError): + code = "delivery_failed" + http_status = 502 + + +def _config(name: str, default): + try: + return current_app.config.get(name, default) + except RuntimeError: # no application context + return default + + +def _normalize_provider(provider) -> str: + value = str(provider or "").strip().lower() + if value not in PROVIDERS: + raise TicketingValidationError( + "provider must be 'jira' or 'linear'.", + ) + return value + + +def _nonempty(value, label: str, limit: int) -> str: + text = str(value or "").strip() + if not text: + raise TicketingValidationError(f"{label} is required.") + if len(text) > limit: + raise TicketingValidationError(f"{label} must be {limit} characters or fewer.") + return text + + +def _jira_base_url(value) -> str: + text = _nonempty(value, "base_url", 500) + parsed = urlparse(text) + if parsed.scheme not in ("http", "https") or not parsed.hostname: + raise TicketingValidationError("base_url must be an http(s) URL.") + if parsed.username or parsed.password: + raise TicketingValidationError("base_url must not contain credentials.") + return parsed.geturl() + + +def configure_ticketing( + workspace_id: int, + user, + *, + provider, + base_url=None, + email=None, + api_token=None, + project_key=None, + team_id=None, +) -> dict: + """Validate and store encrypted ticketing credentials (owner only). + + Raises :class:`TicketingPermissionError` for a non-owner and + :class:`TicketingValidationError` for malformed settings. Secrets are + written through ``integration_credentials`` and never returned. + """ + provider = _normalize_provider(provider) + + if provider == "jira": + base_url = _jira_base_url(base_url) + email = _nonempty(email, "email", 255) + if "@" not in email: + raise TicketingValidationError("email must be a valid address.") + api_token = _nonempty(api_token, "api_token", 500) + project_key = _nonempty(project_key, "project_key", 50) + if not _PROJECT_KEY_RE.match(project_key): + raise TicketingValidationError( + "project_key must be 1-50 letters, digits, or underscores." + ) + settings = { + "base_url": base_url, + "email": email, + "api_token": api_token, + "project_key": project_key, + } + else: + api_token = _nonempty(api_token, "api_token", 500) + team_id = _nonempty(team_id, "team_id", 100) + settings = {"api_token": api_token, "team_id": team_id} + + try: + set_credential(workspace_id, INTEGRATION, "provider", provider, user=user) + for name, value in settings.items(): + set_credential(workspace_id, INTEGRATION, name, value, user=user) + except PermissionError as exc: + raise TicketingPermissionError(str(exc)) from exc + except IntegrationCredentialError as exc: + raise TicketingValidationError(str(exc)) from exc + + return { + "integration": INTEGRATION, + "provider": provider, + "configured": True, + "credential_names": list(REQUIRED_CREDENTIALS[provider]), + } + + +def configured_provider(workspace_id: int) -> str | None: + """Return the configured provider, or ``None`` when the workspace opted out.""" + try: + provider = load_credential_value(workspace_id, INTEGRATION, "provider") + except IntegrationNotConfigured: + return None + provider = str(provider or "").strip().lower() + if provider not in PROVIDERS: + return None + if not set(REQUIRED_CREDENTIALS[provider]).issubset( + credential_names(workspace_id, INTEGRATION) + ): + return None + return provider + + +def is_configured(workspace_id: int) -> bool: + """Return ``True`` when this workspace has a complete ticketing setup.""" + return configured_provider(workspace_id) is not None + + +def _bounded(value, limit: int, *, single_line: bool = False) -> str: + text = str(value or "") + if single_line: + text = " ".join(text.split()) + return text[:limit] + + +def _idempotency_key(workspace_id: int, finding_id: int) -> str: + raw = f"ticketing:{workspace_id}:{finding_id}".encode() + return hashlib.sha256(raw).hexdigest()[:32] + + +def _workspace_for_finding(finding: ReviewFinding) -> tuple[int | None, Review | None]: + if not isinstance(finding, ReviewFinding) or finding.id is None: + raise TicketingValidationError("a persisted review finding is required.") + review = finding.review + if review is None and finding.review_id: + review = db.session.get(Review, finding.review_id) + if review is None: + raise TicketingValidationError("finding does not belong to a review.") + project = review.project + if project is None or project.workspace_id is None: + return None, review + return project.workspace_id, review + + +def _description(finding: ReviewFinding, workspace_id: int) -> str: + location = finding.file or "review" + if finding.line: + location = f"{location}:{finding.line}" + parts = [ + f"High-risk {finding.severity} finding in {location}.", + "", + _bounded(finding.explanation, MAX_DESCRIPTION), + ] + if finding.recommendation: + parts += ["", "Recommendation:", _bounded(finding.recommendation, 1000)] + parts += [ + "", + f"Category: {finding.category}", + f"Confidence: {finding.confidence}", + f"Finding: {finding.id}", + f"Review: {finding.review_id}", + f"Idempotency key: {_idempotency_key(workspace_id, finding.id)}", + ] + return _bounded("\n".join(parts), MAX_DESCRIPTION) + + +def _build_payload(provider: str, workspace_id: int, finding: ReviewFinding) -> dict: + location = finding.file or "review" + if finding.line: + location = f"{location}:{finding.line}" + title = _bounded( + f"[{finding.severity.upper()}] {finding.category}: {location}", + MAX_TITLE, + single_line=True, + ) + description = _description(finding, workspace_id) + severity = str(finding.severity).lower() + + if provider == "jira": + project_key = load_credential_value(workspace_id, INTEGRATION, "project_key") + return { + "fields": { + "project": {"key": project_key}, + "summary": title, + "description": description, + "issuetype": {"name": "Bug"}, + "priority": {"name": JIRA_PRIORITY[severity]}, + "labels": ["security", "ai-review", severity], + } + } + return { + "query": LINEAR_MUTATION, + "variables": { + "input": { + "teamId": load_credential_value(workspace_id, INTEGRATION, "team_id"), + "title": title, + "description": description, + "priority": LINEAR_PRIORITY[severity], + } + }, + } + + +def _response_json(response, provider: str) -> dict: + try: + data = response.json() + except (TypeError, ValueError) as exc: + raise TicketingDeliveryError(f"{provider} returned a non-JSON response.") from exc + if not isinstance(data, dict): + raise TicketingDeliveryError(f"{provider} returned an unexpected response.") + return data + + +def _deliver( + provider: str, + workspace_id: int, + payload: dict, + post, +) -> tuple[str, str | None]: + """Send one bounded request and return ``(external_key, external_url)``.""" + timeout = float(_config("INTEGRATION_REQUEST_TIMEOUT", 10)) + try: + if provider == "jira": + base_url = load_credential_value(workspace_id, INTEGRATION, "base_url").rstrip("/") + email = load_credential_value(workspace_id, INTEGRATION, "email") + token = load_credential_value(workspace_id, INTEGRATION, "api_token") + response = post( + f"{base_url}/rest/api/3/issue", + json=payload, + auth=(email, token), + headers={"Accept": "application/json"}, + timeout=timeout, + allow_redirects=False, + ) + status = int(getattr(response, "status_code", 0) or 0) + if not 200 <= status < 300: + raise TicketingDeliveryError(f"Jira returned HTTP {status}.") + data = _response_json(response, "Jira") + key = str(data.get("key") or "").strip() + if not key: + raise TicketingDeliveryError("Jira response did not include an issue key.") + return key[:100], f"{base_url}/browse/{key}" + + token = load_credential_value(workspace_id, INTEGRATION, "api_token") + response = post( + LINEAR_ENDPOINT, + json=payload, + headers={"Accept": "application/json", "Authorization": token}, + timeout=timeout, + allow_redirects=False, + ) + status = int(getattr(response, "status_code", 0) or 0) + if not 200 <= status < 300: + raise TicketingDeliveryError(f"Linear returned HTTP {status}.") + data = _response_json(response, "Linear") + result = (data.get("data") or {}).get("issueCreate") or {} + issue = result.get("issue") or {} + key = str(issue.get("identifier") or "").strip() + if not key: + raise TicketingDeliveryError("Linear response did not include an issue identifier.") + url = str(issue.get("url") or "").strip() or None + return key[:100], (url[:500] if url else None) + except TicketingError: + raise + except Exception as exc: + raise TicketingDeliveryError(sanitize_error(exc)) from exc + + +def create_for_acknowledged_finding( + finding: ReviewFinding, + *, + post=None, + now=None, +) -> SecurityTicketLink | None: + """Create (or return) the ticket for an acknowledged high-risk finding. + + Returns ``None`` when the finding is not acknowledged, is not high risk, + has no workspace, or the workspace has no ticketing configuration. A real + provider/configuration failure raises :class:`TicketingError`. + """ + if not bool(getattr(finding, "addressed", False)): + return None + severity = str(getattr(finding, "severity", "")).lower() + if severity not in HIGH_RISK_SEVERITIES: + return None + + workspace_id, _review = _workspace_for_finding(finding) + if workspace_id is None: + return None + provider = configured_provider(workspace_id) + if provider is None: + return None + + existing = SecurityTicketLink.query.filter_by( + workspace_id=workspace_id, + finding_id=finding.id, + ).first() + if existing is not None: + return existing + + payload = _build_payload(provider, workspace_id, finding) + try: + encoded = json.dumps(payload, separators=(",", ":")).encode("utf-8") + except (TypeError, ValueError) as exc: + raise TicketingValidationError("ticket payload is not serializable.") from exc + if len(encoded) > MAX_REQUEST_BYTES: + raise TicketingValidationError(f"ticket payload exceeds {MAX_REQUEST_BYTES} bytes.") + + external_key, external_url = _deliver(provider, workspace_id, payload, post or requests.post) + link = SecurityTicketLink( + workspace_id=workspace_id, + finding_id=finding.id, + provider=provider, + external_key=external_key, + external_url=external_url, + severity=severity, + ) + if now is not None: + link.created_at = now + db.session.add(link) + try: + db.session.commit() + except Exception: + db.session.rollback() + existing = SecurityTicketLink.query.filter_by( + workspace_id=workspace_id, + finding_id=finding.id, + ).first() + if existing is not None: + return existing + raise TicketingDeliveryError("Could not record the external ticket link.") from None + return link + + +__all__ = [ + "HIGH_RISK_SEVERITIES", + "INTEGRATION", + "LINEAR_ENDPOINT", + "MAX_DESCRIPTION", + "MAX_REQUEST_BYTES", + "MAX_TITLE", + "PROVIDERS", + "REQUIRED_CREDENTIALS", + "TicketingDeliveryError", + "TicketingError", + "TicketingNotConfigured", + "TicketingNotFound", + "TicketingPermissionError", + "TicketingValidationError", + "configure_ticketing", + "configured_provider", + "create_for_acknowledged_finding", + "is_configured", +] diff --git a/docs/api-errors.md b/docs/api-errors.md index 5d609d10..9a0983fe 100644 --- a/docs/api-errors.md +++ b/docs/api-errors.md @@ -26,6 +26,7 @@ fails when a code is missing. | `rate_limited` | 429 | `rate_limited` | Too many requests. Please try again later. | | `gone` | 410 | `gone` | This resource is no longer available. | | `internal_error` | 500 | `internal_error` | Something went wrong. | +| `bad_gateway` | 502 | `upstream_error` | An upstream service failed to complete the request. | ## Where catalog errors are produced diff --git a/docs/security-ticketing.md b/docs/security-ticketing.md new file mode 100644 index 00000000..5db2c2de --- /dev/null +++ b/docs/security-ticketing.md @@ -0,0 +1,118 @@ +# Security ticketing integration (Jira and Linear) + +When a high-risk review finding is acknowledged (`addressed=true`), the app can +create one Jira or Linear issue for it. The integration is opt-in per workspace +and is implemented in +[`app/services/security_tickets.py`](../app/services/security_tickets.py), wired +to `PATCH /reviews/api/reviews/findings/`. + +"High risk" means severity `critical` or `high` — the same set used by the +quality dashboard (`app/services/metrics.py`). + +## Configuration + +Only a workspace owner (`manage_integrations`) may configure it. Credentials are +validated, encrypted with AES-256-GCM, and stored by +[`integration_credentials`](integration-credentials.md) under +`integration="ticketing"`. The plaintext is never returned or logged. + +```python +from app.services.security_tickets import configure_ticketing + +configure_ticketing( + workspace_id, + owner, + provider="jira", + base_url="https://acme.atlassian.net", + email="security@acme.test", + api_token="...", + project_key="SEC", +) + +# Or Linear: +configure_ticketing( + workspace_id, + owner, + provider="linear", + api_token="...", + team_id="", +) +``` + +| Provider | Required credentials | +| --- | --- | +| `jira` | `base_url` (http/https, no embedded credentials), `email`, `api_token`, `project_key` | +| `linear` | `api_token`, `team_id` | + +`api_token`, `email`, and provider settings are stored encrypted; `provider` is +stored as a credential too so the workspace can switch providers without a +schema change. `is_configured(workspace_id)` returns `True` only when the full +credential set for the stored provider exists. + +The outbound request timeout uses the existing +`INTEGRATION_REQUEST_TIMEOUT` setting (default 10 seconds). No new environment +variables are required. + +## What happens on acknowledgement + +1. The existing finding update route validates ownership and applies + `addressed`. +2. If the new state is `true` and the severity is high risk, the service checks + the workspace configuration. Not configured, no workspace (for example a PR + review), not high risk, or not acknowledged are **no-ops**. +3. The service builds a bounded payload and posts it to Jira + (`POST /rest/api/3/issue`) or Linear (`https://api.linear.app/graphql`). +4. On success it stores a `security_ticket_links` row and returns it in the + response as `"ticket": {...}`. + +### Idempotency + +`security_ticket_links` has a unique `(workspace_id, finding_id)` constraint. +The service looks the row up before calling the provider, so a retried request — +including a client retry after a successful response was lost — returns the +stored link without a second issue. `(provider, external_key)` is also unique. +The description includes a deterministic idempotency key derived from +`sha256("ticketing::")` to help a human find the +intended duplicate. If two workers race, the loser reads the stored row after a +commit failure instead of creating a second link. + +### Bounded payload + +Only known finding fields are copied: severity, category, file path and line, +explanation, recommendation, confidence, finding id, and review id. Titles are +capped at 200 characters and descriptions at 4,000; the encoded JSON request is +capped at 16 KiB. The integration does not read repository files, metadata +blobs, credentials, or raw request bodies. + +## Errors + +Service errors carry a stable `code` and HTTP status: + +| Exception | `code` | HTTP | +| --- | --- | --- | +| `TicketingValidationError` | `invalid_input` | 400 | +| `TicketingPermissionError` | `permission_denied` | 403 | +| `TicketingNotConfigured` | `not_configured` | 409 | +| `TicketingNotFound` | `not_found` | 404 | +| `TicketingDeliveryError` | `delivery_failed` | 502 | + +The acknowledgement route maps them to the shared +[error catalog](api-errors.md), for example `502 bad_gateway` for a provider +failure. A delivery failure also rolls back the acknowledgement, so the finding +is not left marked addressed without its ticket; the client can retry, and the +retry is idempotent once a link exists. Provider error text is sanitized and +truncated (URLs redacted) before it reaches the response. + +## Migration + +`migrations/versions/a3b4c5d6e7f8_add_security_ticket_links.py` creates +`security_ticket_links`. Apply it with `flask --app wsgi db upgrade`. Deleting a +workspace or a finding cascades to its ticket links. + +## Tests + +[`tests/test_security_tickets.py`](../tests/test_security_tickets.py) uses a +mocked `post` callable, so no network access or real provider is needed. It +covers encrypted credential storage, owner-only configuration, invalid settings, +Jira and Linear payloads, bounded descriptions, idempotent retries, missed +triggers, delivery failures, and the acknowledgement route (including rollback). diff --git a/migrations/versions/a3b4c5d6e7f8_add_security_ticket_links.py b/migrations/versions/a3b4c5d6e7f8_add_security_ticket_links.py new file mode 100644 index 00000000..9f31f9c2 --- /dev/null +++ b/migrations/versions/a3b4c5d6e7f8_add_security_ticket_links.py @@ -0,0 +1,85 @@ +"""add security ticket links + +Revision ID: a3b4c5d6e7f8 +Revises: 590a1b2c3d4e +Create Date: 2026-11-22 00:00:00.000000 + +Phase 11 (#630): durable Jira/Linear ticket links for high-risk findings. The +unique ``(workspace_id, finding_id)`` row is the idempotency guard; credentials +remain encrypted in ``integration_credentials``. +""" + +import sqlalchemy as sa +from alembic import op + +revision = "a3b4c5d6e7f8" +down_revision = "590a1b2c3d4e" +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table( + "security_ticket_links", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("workspace_id", sa.Integer(), nullable=False), + sa.Column("finding_id", sa.Integer(), nullable=False), + sa.Column("provider", sa.String(length=20), nullable=False), + sa.Column("external_key", sa.String(length=100), nullable=False), + sa.Column("external_url", sa.String(length=500), nullable=True), + sa.Column("severity", sa.String(length=20), nullable=False), + sa.Column("created_at", sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint(["workspace_id"], ["workspaces.id"], ondelete="CASCADE"), + sa.ForeignKeyConstraint(["finding_id"], ["review_findings.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint( + "workspace_id", + "finding_id", + name="uq_security_ticket_links_workspace_finding", + ), + sa.UniqueConstraint( + "provider", + "external_key", + name="uq_security_ticket_links_provider_external", + ), + ) + op.create_index( + "ix_security_ticket_links_workspace_id", + "security_ticket_links", + ["workspace_id"], + ) + op.create_index( + "ix_security_ticket_links_finding_id", + "security_ticket_links", + ["finding_id"], + ) + op.create_index( + "ix_security_ticket_links_external_key", + "security_ticket_links", + ["external_key"], + ) + op.create_index( + "ix_security_ticket_links_workspace_created", + "security_ticket_links", + ["workspace_id", "created_at"], + ) + + +def downgrade(): + op.drop_index( + "ix_security_ticket_links_workspace_created", + table_name="security_ticket_links", + ) + op.drop_index( + "ix_security_ticket_links_external_key", + table_name="security_ticket_links", + ) + op.drop_index( + "ix_security_ticket_links_finding_id", + table_name="security_ticket_links", + ) + op.drop_index( + "ix_security_ticket_links_workspace_id", + table_name="security_ticket_links", + ) + op.drop_table("security_ticket_links") diff --git a/tests/test_security_tickets.py b/tests/test_security_tickets.py new file mode 100644 index 00000000..226f89a3 --- /dev/null +++ b/tests/test_security_tickets.py @@ -0,0 +1,357 @@ +"""Tests for the acknowledgement ticketing integration (#630).""" + +from __future__ import annotations + +import json + +import pytest + +from app.extensions import db +from app.models import ( + IntegrationCredential, + Project, + Review, + ReviewFinding, + SecurityTicketLink, + Workspace, +) +from app.models.project import SOURCE_ARCHIVE, STATUS_READY +from app.models.review import SOURCE_PROJECT, STATUS_COMPLETED +from app.services import security_tickets +from app.services.crypto import decrypt_api_key + + +class FakeResponse: + def __init__(self, status_code=200, payload=None): + self.status_code = status_code + self._payload = payload + + def json(self): + if self._payload is None: + raise ValueError("not json") + return self._payload + + +class FakePost: + def __init__(self, *responses): + self.responses = list(responses) + self.calls = [] + + def __call__(self, url, **kwargs): + self.calls.append({"url": url, **kwargs}) + if not self.responses: + raise AssertionError("unexpected provider call") + response = self.responses.pop(0) + if isinstance(response, Exception): + raise response + return response + + +def _setup(make_user, *, severity="high", addressed=False): + user = make_user() + workspace = Workspace(user_id=user.id, name="Org") + db.session.add(workspace) + db.session.commit() + project = Project( + workspace_id=workspace.id, + user_id=user.id, + name="Project", + source=SOURCE_ARCHIVE, + status=STATUS_READY, + ) + db.session.add(project) + db.session.commit() + review = Review( + user_id=user.id, + project_id=project.id, + source=SOURCE_PROJECT, + kind="security", + status=STATUS_COMPLETED, + ) + db.session.add(review) + db.session.commit() + finding = ReviewFinding( + review_id=review.id, + file="app/db.py", + line=12, + severity=severity, + category="injection", + explanation="Unparameterized query.", + recommendation="Use bound parameters.", + confidence="confirmed", + addressed=addressed, + ) + db.session.add(finding) + db.session.commit() + return user, workspace, finding + + +def _configure_jira(workspace, owner): + return security_tickets.configure_ticketing( + workspace.id, + owner, + provider="jira", + base_url="https://acme.atlassian.net", + email="security@acme.test", + api_token="jira-secret-token", + project_key="SEC", + ) + + +def _configure_linear(workspace, owner): + return security_tickets.configure_ticketing( + workspace.id, + owner, + provider="linear", + api_token="lin-secret-token", + team_id="team-123", + ) + + +class TestConfiguration: + def test_owner_stores_encrypted_credentials(self, db, make_user): + owner, workspace, _ = _setup(make_user) + + result = _configure_jira(workspace, owner) + + assert result["provider"] == "jira" + assert result["configured"] is True + assert set(result["credential_names"]) == { + "base_url", + "email", + "api_token", + "project_key", + } + stored = IntegrationCredential.query.filter_by( + workspace_id=workspace.id, + integration="ticketing", + name="api_token", + ).one() + assert stored.encrypted_value != "jira-secret-token" + assert decrypt_api_key(stored.encrypted_value) == "jira-secret-token" + assert security_tickets.is_configured(workspace.id) is True + + def test_non_owner_cannot_configure(self, db, make_user): + _owner, workspace, _ = _setup(make_user) + outsider = make_user(username="outsider", email="outsider@example.com") + + with pytest.raises(security_tickets.TicketingPermissionError) as info: + _configure_jira(workspace, outsider) + + assert info.value.code == "permission_denied" + assert info.value.http_status == 403 + assert security_tickets.is_configured(workspace.id) is False + + @pytest.mark.parametrize( + "kwargs", + [ + {"provider": "service-desk", "api_token": "x", "team_id": "t"}, + {"provider": "jira", "base_url": "ftp://x", "email": "a@b.c"}, + { + "provider": "jira", + "base_url": "https://user:pass@x.test", + "email": "a@b.c", + "api_token": "t", + "project_key": "SEC", + }, + { + "provider": "jira", + "base_url": "https://x.test", + "email": "not-an-email", + "api_token": "t", + "project_key": "SEC", + }, + { + "provider": "linear", + "api_token": "", + "team_id": "team-1", + }, + ], + ) + def test_invalid_configuration_is_structured(self, db, make_user, kwargs): + owner, workspace, _ = _setup(make_user) + + with pytest.raises(security_tickets.TicketingValidationError) as info: + security_tickets.configure_ticketing(workspace.id, owner, **kwargs) + + assert info.value.code == "invalid_input" + + +class TestTicketCreation: + def test_jira_ticket_is_created_once_and_retries_are_idempotent(self, db, make_user): + owner, workspace, finding = _setup(make_user, addressed=True) + _configure_jira(workspace, owner) + post = FakePost(FakeResponse(201, {"key": "SEC-42", "id": "10042"})) + + first = security_tickets.create_for_acknowledged_finding(finding, post=post) + second = security_tickets.create_for_acknowledged_finding(finding, post=post) + + assert first.id == second.id + assert first.external_key == "SEC-42" + assert first.external_url == "https://acme.atlassian.net/browse/SEC-42" + assert SecurityTicketLink.query.count() == 1 + assert len(post.calls) == 1 + + call = post.calls[0] + assert call["url"] == "https://acme.atlassian.net/rest/api/3/issue" + assert call["auth"] == ("security@acme.test", "jira-secret-token") + fields = call["json"]["fields"] + assert fields["project"] == {"key": "SEC"} + assert fields["priority"] == {"name": "High"} + assert "Unparameterized query." in fields["description"] + assert "jira-secret-token" not in json.dumps(call["json"]) + + def test_linear_ticket_payload(self, db, make_user): + owner, workspace, finding = _setup(make_user, addressed=True) + _configure_linear(workspace, owner) + post = FakePost( + FakeResponse( + 200, + { + "data": { + "issueCreate": { + "success": True, + "issue": { + "identifier": "ENG-7", + "url": "https://linear.app/acme/issue/ENG-7", + }, + } + } + }, + ) + ) + + link = security_tickets.create_for_acknowledged_finding(finding, post=post) + + assert link.provider == "linear" + assert link.external_key == "ENG-7" + assert post.calls[0]["url"] == security_tickets.LINEAR_ENDPOINT + assert post.calls[0]["headers"]["Authorization"] == "lin-secret-token" + issue_input = post.calls[0]["json"]["variables"]["input"] + assert issue_input["teamId"] == "team-123" + assert issue_input["priority"] == 2 + + def test_misses_are_noops(self, db, make_user): + owner, workspace, finding = _setup(make_user, addressed=False) + _configure_jira(workspace, owner) + post = FakePost() + + assert security_tickets.create_for_acknowledged_finding(finding, post=post) is None + + finding.addressed = True + finding.severity = "low" + db.session.commit() + assert security_tickets.create_for_acknowledged_finding(finding, post=post) is None + assert post.calls == [] + + def test_unconfigured_workspace_is_a_noop(self, db, make_user): + _owner, _workspace, finding = _setup(make_user, addressed=True) + post = FakePost() + + assert security_tickets.create_for_acknowledged_finding(finding, post=post) is None + assert post.calls == [] + assert SecurityTicketLink.query.count() == 0 + + def test_payload_is_bounded(self, db, make_user): + owner, workspace, finding = _setup(make_user, addressed=True) + finding.explanation = "x" * 20_000 + db.session.commit() + _configure_jira(workspace, owner) + post = FakePost(FakeResponse(201, {"key": "SEC-1"})) + + security_tickets.create_for_acknowledged_finding(finding, post=post) + + fields = post.calls[0]["json"]["fields"] + assert len(fields["summary"]) <= security_tickets.MAX_TITLE + assert len(fields["description"]) <= security_tickets.MAX_DESCRIPTION + encoded = json.dumps(post.calls[0]["json"]).encode("utf-8") + assert len(encoded) <= security_tickets.MAX_REQUEST_BYTES + + def test_delivery_failure_is_structured_and_records_nothing(self, db, make_user): + owner, workspace, finding = _setup(make_user, addressed=True) + _configure_jira(workspace, owner) + post = FakePost(FakeResponse(500, {"error": "boom"})) + + with pytest.raises(security_tickets.TicketingDeliveryError) as info: + security_tickets.create_for_acknowledged_finding(finding, post=post) + + assert info.value.code == "delivery_failed" + assert info.value.http_status == 502 + assert SecurityTicketLink.query.count() == 0 + + +class TestAcknowledgementRoute: + def _finding(self, make_user): + user, workspace, finding = _setup(make_user) + return user, workspace, finding + + def test_acknowledging_a_high_risk_finding_creates_a_ticket( + self, db, client, make_user, login, monkeypatch + ): + owner, workspace, finding = self._finding(make_user) + _configure_jira(workspace, owner) + post = FakePost(FakeResponse(201, {"key": "SEC-9"})) + monkeypatch.setattr(security_tickets.requests, "post", post) + login(email=owner.email) + + response = client.patch( + f"/reviews/api/reviews/findings/{finding.id}", + json={"addressed": True}, + ) + + assert response.status_code == 200 + payload = response.get_json() + assert payload["addressed"] is True + assert payload["ticket"]["external_key"] == "SEC-9" + assert len(post.calls) == 1 + + # Re-acknowledging (or a retried request) reuses the stored link. + again = client.patch( + f"/reviews/api/reviews/findings/{finding.id}", + json={"addressed": True}, + ) + assert again.get_json()["ticket"]["external_key"] == "SEC-9" + assert len(post.calls) == 1 + + def test_low_risk_or_plain_updates_do_not_create_tickets( + self, db, client, make_user, login, monkeypatch + ): + owner, workspace, finding = self._finding(make_user) + finding.severity = "low" + db.session.commit() + _configure_jira(workspace, owner) + post = FakePost() + monkeypatch.setattr(security_tickets.requests, "post", post) + login(email=owner.email) + + response = client.patch( + f"/reviews/api/reviews/findings/{finding.id}", + json={"addressed": True}, + ) + + assert response.status_code == 200 + assert "ticket" not in response.get_json() + assert post.calls == [] + + def test_delivery_failure_rolls_back_the_acknowledgement( + self, db, client, make_user, login, monkeypatch + ): + owner, workspace, finding = self._finding(make_user) + _configure_jira(workspace, owner) + monkeypatch.setattr( + security_tickets.requests, + "post", + FakePost(FakeResponse(503, {"error": "unavailable"})), + ) + login(email=owner.email) + + response = client.patch( + f"/reviews/api/reviews/findings/{finding.id}", + json={"addressed": True}, + ) + + assert response.status_code == 502 + assert response.get_json()["code"] == "bad_gateway" + db.session.expire_all() + assert db.session.get(ReviewFinding, finding.id).addressed is False + assert SecurityTicketLink.query.count() == 0