Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
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
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ dependencies = [
"pypinyin>=0.55.0",
"python-docx>=1.1.0",
"python-dotenv>=1.2.2",
"python-multipart>=0.0.22",
"reportlab>=4.4.4",
"regex>=2024.11.6",
"segno>=1.6.6",
Expand Down
286 changes: 286 additions & 0 deletions pyrit/backend/README.md

Large diffs are not rendered by default.

23 changes: 23 additions & 0 deletions pyrit/backend/middleware/error_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,36 @@
from pyrit.backend.middleware.request_size import RequestTooLargeError, request_too_large_response
from pyrit.backend.models import FieldError, ProblemDetail
from pyrit.exceptions.analytics_exception import AnalyticsException
from pyrit.exceptions.dataset_exception import DatasetAPIException

logger = logging.getLogger(__name__)


def register_error_handlers(app: FastAPI) -> None:
"""Register all error handlers with the FastAPI app."""

@app.exception_handler(DatasetAPIException)
async def dataset_exception_handler_async(request: Request, exc: DatasetAPIException) -> JSONResponse:
"""
Return sanitized dataset errors with durable cleanup guidance.

Returns:
JSONResponse: An RFC 7807 problem, with Location when cleanup remains pending.
"""
problem = ProblemDetail(
type="/errors/dataset",
title="Dataset request failed",
status=exc.status_code,
detail=exc.message,
instance=request.url.path,
)
return JSONResponse(
status_code=exc.status_code,
media_type="application/problem+json",
content=problem.model_dump(exclude_none=True),
headers={"Location": f"/api/datasets/deletions/{exc.cleanup_id}"} if exc.cleanup_id else None,
)

@app.exception_handler(AnalyticsException)
async def analytics_exception_handler_async(request: Request, exc: AnalyticsException) -> JSONResponse:
"""
Expand Down
14 changes: 10 additions & 4 deletions pyrit/backend/middleware/request_size.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@

"""Reject requests whose URL or body is larger than the backend accepts."""

from starlette._utils import get_route_path
from starlette.datastructures import Headers
from starlette.exceptions import HTTPException
from starlette.responses import JSONResponse
from starlette.types import ASGIApp, Message, Receive, Scope, Send

from pyrit.backend.models.datasets import DatasetUploadLimits


class RequestTooLargeError(HTTPException):
"""Raised when a request body grows past the size limit while it is read."""
Expand Down Expand Up @@ -56,13 +59,16 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if len(path) + len(scope.get("query_string", b"")) > self.MAX_URL_LENGTH:
await self._reject_async(scope=scope, receive=receive, send=send, status=414, title="URI Too Long")
return
maximum = self.MAX_BODY_BYTES
if scope["method"] == "POST" and get_route_path(scope).rstrip("/") == "/api/datasets":
maximum = DatasetUploadLimits.from_environment().request_bytes
content_length = Headers(scope=scope).get("content-length", "")
if content_length.isdigit() and int(content_length) > self.MAX_BODY_BYTES:
if content_length.isdigit() and int(content_length) > maximum:
await self._reject_async(scope=scope, receive=receive, send=send, status=413, title="Content Too Large")
return
await self.app(scope, self._limit_body(receive), send)
await self.app(scope, self._limit_body(receive, maximum=maximum), send)

def _limit_body(self, receive: Receive) -> Receive:
def _limit_body(self, receive: Receive, *, maximum: int | None = None) -> Receive:
"""
Wrap ``receive`` so bodies sent without a reliable ``Content-Length`` are also capped.

Expand All @@ -76,7 +82,7 @@ async def limited_receive_async() -> Message:
message = await receive()
if message["type"] == "http.request":
received += len(message.get("body", b""))
if received > self.MAX_BODY_BYTES:
if received > (self.MAX_BODY_BYTES if maximum is None else maximum):
raise RequestTooLargeError
return message

Expand Down
116 changes: 115 additions & 1 deletion pyrit/backend/models/datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@
listing available datasets and browsing their stored seed examples.
"""

import os
from dataclasses import dataclass
from typing import Any, Literal
from uuid import UUID

from pydantic import BaseModel, Field
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator

from pyrit.backend.models.common import PaginationInfo
from pyrit.models import PromptDataType, ScenarioDatasetSettings, SeedRecord, SeedType
Expand Down Expand Up @@ -49,6 +52,114 @@ class DatasetListResponse(BaseModel):
items: list[DatasetInfo] = Field(..., description="List of available datasets")


@dataclass(frozen=True)
class DatasetUploadLimits:
"""Positive environment-configured limits, in bytes except for prompt count."""

request_bytes: int = 100 * 1024 * 1024
manifest_bytes: int = 10 * 1024 * 1024
prompts: int = 10_000

@classmethod
def from_environment(cls) -> "DatasetUploadLimits":
"""
Read explicit limits without silently accepting invalid configuration.

Returns:
DatasetUploadLimits: The positive configured limits.
"""
values = {
field: int(os.environ.get(variable, default))
for field, variable, default in (
("request_bytes", "PYRIT_DATASET_MAX_REQUEST_BYTES", cls.request_bytes),
("manifest_bytes", "PYRIT_DATASET_MAX_MANIFEST_BYTES", cls.manifest_bytes),
("prompts", "PYRIT_DATASET_MAX_PROMPTS", cls.prompts),
)
}
if any(value <= 0 for value in values.values()):
raise ValueError("Dataset upload limits must be positive integers.")
return cls(**values)


class DatasetUploadManifest(BaseModel):
"""Untrusted JSON; canonical seed construction follows trust and reference checks."""

model_config = ConfigDict(extra="forbid", strict=True)
name: str = Field(min_length=1, max_length=256)
mode: Literal["create", "update"] = "create"
expected_version: str | None = Field(None, min_length=64, max_length=64)
seeds: list[dict[str, Any]]
delete_seed_ids: list[str] = Field(default_factory=list)

@model_validator(mode="after")
def _validate_operations(self) -> "DatasetUploadManifest":
if self.mode == "create":
if not self.seeds or self.delete_seed_ids or self.expected_version is not None:
raise ValueError("Create requires seeds and forbids deletions and expected_version.")
elif not self.expected_version or not (self.seeds or self.delete_seed_ids):
raise ValueError("Update requires expected_version and at least one operation.")
ids = [str(UUID(value)) for value in self.delete_seed_ids]
if len(set(ids)) != len(ids):
raise ValueError("Duplicate delete record IDs.")
self.delete_seed_ids = ids
return self

@field_validator("name")
@classmethod
def _validate_name(cls, value: str) -> str:
if value != value.strip() or any(ord(char) < 32 for char in value) or len(value.encode("utf-16-le")) > 512:
raise ValueError("Use a nonempty dataset name of at most 256 UTF-16 code units without outer whitespace.")
return value


class DatasetDeletionResponse(BaseModel):
"""Durable status of exact dataset removal and its owned-media cleanup."""

deletion_id: UUID
status: Literal["pending", "completed"]
deleted_seeds: int
pending_media: int | None = Field(..., description="Unknown only if committed cleanup status could not be read")
error: str | None = None


class _DatasetPopulationResponse(BaseModel):
"""Counts and selection identity shared by committed create and update results."""

name: str
selection_key: str
seed_pieces: int
logical_examples: int


class DatasetUploadResponse(_DatasetPopulationResponse):
"""The actual committed population, immediately available through existing browsing."""

cleanup: DatasetDeletionResponse | None = Field(default=None, exclude_if=lambda value: value is None)
cleanup_location: str | None = Field(default=None, exclude_if=lambda value: value is None)


class DatasetSeedResult(BaseModel):
"""Exact persisted record identity correlated to the manifest's seed index."""

index: int
id: UUID
operation: Literal["added", "updated"]


class DatasetMutationResponse(_DatasetPopulationResponse):
"""A committed batch, even when physical cleanup still needs retrying."""

dataset_exists: bool
version: str | None
added: int
updated: int
deleted: int
seeds: list[DatasetSeedResult]
delete_seed_ids: list[UUID]
cleanup: DatasetDeletionResponse
cleanup_location: str


class ScenarioDatasetLoadResponse(BaseModel):
"""Selected dataset settings and metadata after an explicit load."""

Expand All @@ -69,6 +180,7 @@ class SeedExampleSummary(BaseModel):
objective_count: int
harm_categories: list[str]
has_unlabeled_harm: bool = Field(..., description="Whether any member has no harm category")
editable_seeds: list[dict[str, Any]] | None = Field(None, description="Opt-in submit-ready seed replacements")


class SeedExampleListResponse(BaseModel):
Expand All @@ -77,6 +189,7 @@ class SeedExampleListResponse(BaseModel):
items: list[SeedExampleSummary]
pagination: PaginationInfo
total: int = Field(..., description="Number of logical examples that match the filters")
version: str | None = Field(None, description="Opt-in token from the same snapshot as editable_seeds")


class SeedMemberView(SeedRecord):
Expand All @@ -101,3 +214,4 @@ class SeedExampleDetailResponse(SeedExampleSummary):
"Media members include value_url for display; value is the stored reference."
),
)
version: str | None = Field(None, description="Opt-in token from the same snapshot as editable_seeds")
Loading
Loading