Skip to content
Merged
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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,19 +134,22 @@ 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)
- [Security model](docs/security.md)
- [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)
- [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)
Expand Down
8 changes: 8 additions & 0 deletions app/api/error_catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
RATE_LIMITED = "rate_limited"
GONE = "gone"
INTERNAL_ERROR = "internal_error"
BAD_GATEWAY = "bad_gateway"


@dataclass(frozen=True)
Expand Down Expand Up @@ -74,6 +75,13 @@
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()}
Expand All @@ -99,7 +107,7 @@
}
if details is not None:
payload["details"] = details
response = jsonify(payload)

Check warning

Code scanning / CodeQL

Information exposure through an exception Medium

Stack trace information
flows to this location and may be exposed to an external user.
Stack trace information
flows to this location and may be exposed to an external user.
Stack trace information
flows to this location and may be exposed to an external user.
Stack trace information
flows to this location and may be exposed to an external user.
Stack trace information
flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
[Stack trace
response.status_code = entry.status
return response

Expand Down
133 changes: 133 additions & 0 deletions app/api/filtering.py
Original file line number Diff line number Diff line change
@@ -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",
]
123 changes: 96 additions & 27 deletions app/api/v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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:
Expand All @@ -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
Expand All @@ -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,
}

Expand All @@ -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/<int:project_id>", methods=["GET"])
Expand All @@ -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/<int:review_id>", methods=["GET"])
Expand All @@ -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:
Expand Down
Loading
Loading