Project: pygitweb
"""
FastAPI dependencies for shared request validation (exported repositories, etc.).
"""
from __future__ import annotations
import ipaddress
from collections.abc import Callable
from typing import Annotated, Any
from fastapi import Depends, Form, HTTPException, Query, Request
from pygittools.validation import is_valid_project
from pygitweb.auth import (
access_token_from_request,
ensure_permission,
ensure_read_project,
ensure_write_project,
require_active_user_if_auth_enabled,
)
from pygitweb.config import settings
from pygitweb.permissions import Permission
from pygitweb.projects import git_get_projects_list, project_in_list
def _visible_projects_list() -> list[dict[str, Any]]:
return git_get_projects_list(
filter_path="",
paranoid=settings.STRICT_EXPORT,
export_ok=settings.EXPORT_OK,
)
def project_visible_in_list(project: str) -> bool:
"""True if ``project`` appears in the same listing as the project picker."""
return project_in_list(project, _visible_projects_list)
def require_valid_project(project: str) -> str:
"""Reject empty or unknown project paths (export_ok, strict list, etc.).
``project`` is taken from the path when the route has ``{project}``, otherwise
from the query string (FastAPI's usual inference).
"""
if not project or project == "":
raise HTTPException(status_code=400, detail="Project needed")
if not is_valid_project(
project,
settings.PROJECTROOT,
settings.EXPORT_OK,
settings.STRICT_EXPORT,
project_visible_in_list,
):
raise HTTPException(status_code=404, detail="No such project")
return project
def require_valid_project_name(name: str) -> str:
"""Same as ``require_valid_project`` for a path parameter named ``name``."""
return require_valid_project(name)
def require_valid_project_form(project: Annotated[str, Form()]) -> str:
return require_valid_project(project)
def require_readable_project(
project: str,
token: Annotated[str | None, Depends(access_token_from_request)],
) -> str:
"""Validate ``project`` (path or query) and require read access."""
validated = require_valid_project(project)
ensure_read_project(validated, token)
return validated
def require_readable_project_form(
project: Annotated[str, Form()],
token: Annotated[str | None, Depends(access_token_from_request)],
) -> str:
return require_readable_project(project, token)
def require_readable_project_name(
name: str,
token: Annotated[str | None, Depends(access_token_from_request)],
) -> str:
return require_readable_project(name, token)
def require_writable_project_name(
name: str,
token: Annotated[str | None, Depends(access_token_from_request)],
) -> str:
validated = require_valid_project(name)
ensure_write_project(validated, token)
return validated
def is_loopback_host(host: str | None) -> bool:
if not host:
return False
if host == "localhost":
return True
try:
return ipaddress.ip_address(host).is_loopback
except ValueError:
return False
def require_loopback_client(request: Request) -> None:
"""Reject non-local callers (hooks should POST from the same host)."""
client = request.client
if client is not None and is_loopback_host(client.host):
return
raise HTTPException(status_code=403, detail="Forbidden")
def require_notify_project(
project: Annotated[str | None, Query(alias="project", description="Repository path")] = None,
) -> str:
"""Internal notify: project must appear in the visible list (hook / long-poll contract)."""
if not project or not project.strip():
raise HTTPException(status_code=400, detail="project query parameter required")
p = project.strip()
if not project_visible_in_list(p):
raise HTTPException(status_code=404, detail="No such project")
return p
def board_create_resolved_project(
token: Annotated[str | None, Depends(access_token_from_request)],
p: Annotated[str | None, Query(alias="p")] = None,
project: Annotated[str | None, Query(alias="project")] = None,
) -> str:
"""Resolve ``?p=`` / ``?project=`` then validate as a normal project path."""
chosen = (project or p or "").strip()
if not chosen:
raise HTTPException(status_code=400, detail="Project needed (use ?project= or ?p=)")
return require_readable_project(chosen, token)
def filter_projects_by_read_access(
projects: list[dict[str, Any]],
token: str | None,
) -> list[dict[str, Any]]:
from pygitweb.auth import can_read_project
return [p for p in projects if can_read_project(p.get("path", ""), token)]
class RequirePermission:
"""Enforce ``permission`` on a path/query ``project`` (via ``require_readable_project``).
Auth runs before the readable-project check so unauthenticated callers get 401
rather than the 404 that ``ensure_read_project`` uses to hide existence.
"""
def __init__(self, permission: Permission) -> None:
self.permission = permission
def __call__(
self,
_auth: Annotated[None, Depends(require_active_user_if_auth_enabled)],
project: Annotated[str, Depends(require_readable_project)],
token: Annotated[str | None, Depends(access_token_from_request)],
) -> None:
ensure_permission(self.permission, project, token=token)
class RequireFormPermission:
"""Enforce ``permission`` on a form-field ``project``."""
def __init__(self, permission: Permission) -> None:
self.permission = permission
def __call__(
self,
_auth: Annotated[None, Depends(require_active_user_if_auth_enabled)],
project: Annotated[str, Depends(require_readable_project_form)],
token: Annotated[str | None, Depends(access_token_from_request)],
) -> None:
ensure_permission(self.permission, project, token=token)
def require_permission(permission: Permission) -> Callable[..., None]:
"""Enforce ``permission`` with no project context (global grants)."""
def _dep(
token: Annotated[str | None, Depends(access_token_from_request)],
) -> None:
ensure_permission(permission, None, token=token)
return _dep
ValidatedProject = Annotated[str, Depends(require_valid_project)]
ValidatedReadableProject = Annotated[str, Depends(require_readable_project)]
ValidatedReadableSettingsProject = Annotated[str, Depends(require_readable_project_name)]
ValidatedWritableSettingsProject = Annotated[str, Depends(require_writable_project_name)]
ValidatedBoardCreateProject = Annotated[str, Depends(board_create_resolved_project)]
ValidatedNotifyProject = Annotated[str, Depends(require_notify_project)]
ValidatedReadableFormProject = Annotated[str, Depends(require_readable_project_form)]