From c1f8975643eae14bd665b8280c3e4dce21e7e757 Mon Sep 17 00:00:00 2001 From: Sau1707 <83017316+Sau1707@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:51:15 +0100 Subject: [PATCH] refactor(api): centralize runtime ownership and shared policies --- api/main.py | 3 +- api/src/database/services/organizations.py | 31 ++----- api/src/database/services/registries.py | 46 ++-------- api/src/database/services/users.py | 19 ++-- api/src/models/companies.py | 7 -- api/src/operations/computes.py | 10 +-- api/src/operations/databases.py | 6 +- api/src/operations/registries.py | 36 ++++++++ api/src/operations/usage.py | 65 ++++++++++++++ api/src/routes/v1/auth.py | 7 +- api/src/routes/v1/organization/image.py | 2 +- .../routes/v1/organization/organizations.py | 37 ++------ api/src/routes/v1/organization/payments.py | 5 +- api/src/routes/v1/organization/solutions.py | 3 +- api/src/utils/cookies.py | 1 + api/src/utils/passwords.py | 16 ++++ api/tests/bootstrap.py | 2 + .../database/services/test_registries.py | 84 ------------------ api/tests/database/services/test_users.py | 68 +++++++++++++-- api/tests/operations/test_registries.py | 86 +++++++++++++++++++ api/tests/routes/test_mcp.py | 6 +- api/tests/routes/v1/test_payments.py | 64 +++++++++++++- api/tests/test_main.py | 15 ++-- api/tests/utils/test_cookies.py | 19 ++++ 24 files changed, 404 insertions(+), 234 deletions(-) create mode 100644 api/src/operations/usage.py create mode 100644 api/src/utils/passwords.py diff --git a/api/main.py b/api/main.py index 1227aa401..8ed97fb5e 100644 --- a/api/main.py +++ b/api/main.py @@ -16,7 +16,7 @@ from longlink.logger import ApiAccessFilter from src.environments import env from fastapi.responses import FileResponse, JSONResponse, RedirectResponse -from src.utils.cookies import AUTH_COOKIE, RESET_COOKIE, OAUTH_STATE_COOKIE, REGISTRATION_COOKIE +from src.utils.cookies import AUTHENTICATION_COOKIES from longlink.middleware import FrontendMiddleware from src.database.session import dispose_engine from src.database.services import public @@ -60,7 +60,6 @@ async def lifespan(_app: FastAPI) -> AsyncGenerator[None, None]: app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None, title="LongLink Platform API", version="1.0.0") -AUTHENTICATION_COOKIES = frozenset({AUTH_COOKIE, OAUTH_STATE_COOKIE, RESET_COOKIE, REGISTRATION_COOKIE}) UNSAFE_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"}) diff --git a/api/src/database/services/organizations.py b/api/src/database/services/organizations.py index 00e6afcb9..21a0751d6 100644 --- a/api/src/database/services/organizations.py +++ b/api/src/database/services/organizations.py @@ -1,29 +1,25 @@ -import httpx -import asyncio -from kr8s import ServerError, NotFoundError, APITimeoutError, ConnectionClosedError +import src.operations.usage +from kr8s import NotFoundError from uuid import UUID from typing import cast from fastapi import HTTPException from datetime import UTC, datetime from sqlmodel import col -from src.utils import s3, roles +from src.utils import roles from sqlalchemy import Select, func, delete, select from sqlalchemy import update as sql_update from sqlalchemy.orm import defer, load_only, joinedload, selectinload, contains_eager -from src.kubernetes import client, databases from collections.abc import Sequence from src.models.tags import TagIcon, TagKind from src.environments import env from src.models.roles import OrganizationRoles from sqlalchemy.engine import RowMapping, CursorResult from src.database.types import attr -from botocore.exceptions import ClientError, BotoCoreError from src.models.statuses import Status from src.database.services import operations from src.models.operations import OperationKind from src.models.pagination import Pagination from sqlalchemy.ext.asyncio import AsyncSession -from src.kubernetes.storage import Storage from src.database.models.tags import OrganizationTag from src.models.organizations import OrganizationUsageUpdate from src.database.models.users import User @@ -181,19 +177,6 @@ async def storage_infrastructure(session: AsyncSession, organization_id: UUID) - return compute -async def storage_usage(compute: ComputeRegistry, organization_id: UUID) -> int: - """Measure one Organization bucket with bounded I/O and stable availability errors.""" - - # Bound provider construction and the complete bucket scan. - try: - async with asyncio.timeout(15): - credentials = s3.Credentials(compute.storage_access_key, compute.storage_secret_key) - storage = s3.S3(compute.storage_endpoint, credentials, compute.storage_certificate) - return await storage.usage(Storage.bucket_name(organization_id)) - except (TimeoutError, BotoCoreError, ClientError) as exc: - raise HTTPException(status_code=503, detail="Storage resources unavailable") from exc - - async def database_infrastructure(session: AsyncSession, organization_id: UUID) -> tuple[Organization, ComputeRegistry]: """Return only the credentials and capacity needed to inspect one Organization database.""" @@ -468,22 +451,18 @@ async def update_usage(session: AsyncSession, organization_id: UUID, user_id: UU if compute is None: raise HTTPException(status_code=404, detail="Organization not found") try: - async with asyncio.timeout(15): - cluster = await client.api(compute.kubeconfig) - provisioned = await databases.provisioned_storage_bytes(cluster, organization_id) + provisioned = await src.operations.usage.provisioned_database_storage(compute, organization_id) except NotFoundError as exc: if organization.status != Status.failed or organization.provisioned_at is not None: raise HTTPException(status_code=503, detail="Database resources unavailable") from exc provisioned = 0 - except (TimeoutError, OSError, ServerError, APITimeoutError, ConnectionClosedError, httpx.HTTPError) as exc: - raise HTTPException(status_code=503, detail="Database resources unavailable") from exc if payload.database_storage_bytes < provisioned: raise HTTPException(status_code=409, detail="Database storage cannot be reduced below provisioned capacity") # File downsizing must retain every currently stored object. quota_bytes = payload.storage_bytes if quota_bytes < organization.storage_bytes: - used_bytes = await storage_usage(compute, organization_id) + used_bytes = await src.operations.usage.storage_usage(compute, organization_id) if quota_bytes < used_bytes: raise HTTPException(status_code=409, detail="Storage capacity cannot be reduced below current usage") diff --git a/api/src/database/services/registries.py b/api/src/database/services/registries.py index 431db61a7..c02a81b57 100644 --- a/api/src/database/services/registries.py +++ b/api/src/database/services/registries.py @@ -2,15 +2,12 @@ from fastapi import HTTPException from pydantic import SecretStr from sqlmodel import col -from src.utils import images from sqlalchemy import select from sqlalchemy.orm import defer, load_only from collections.abc import Sequence from src.models.roles import OrganizationRoles from src.models.types import Image from src.database.types import attr -from src.models.metadata import LongLinkMetadata -from src.database.session import session_scope from src.database.services import operations, organizations from src.models.operations import OperationKind from sqlalchemy.ext.asyncio import AsyncSession @@ -98,38 +95,11 @@ async def resolve(session: AsyncSession, organization_id: UUID, connection_id: U return connection -async def inspect(organization_id: UUID, image: Image) -> tuple[LongLinkMetadata, UUID | None]: - """Inspect anonymously first, then try tenant-owned credentials outside a database session.""" - - # Public images must not depend on saved credentials; retry only registry access denials. - try: - metadata = await images.required_metadata(image) - return metadata, None - - # Retry only GHCR authorization failures with tenant-owned credentials. - except HTTPException as exc: - if exc.status_code != 403 or image.registry != RegistryConnection.host: - raise - - # Only matching credentials in the caller-authorized organization may reach this registry. - async with session_scope() as session: - result = await session.scalars( - select(RegistryConnection) - .where(col(RegistryConnection.organization_id) == organization_id) - .order_by(col(RegistryConnection.id)) - ) - connections = result.all() - - # Stop on a successful lookup or a non-authentication error, never masking invalid metadata. - for connection in connections: - try: - metadata = await images.required_metadata(image, connection) - return metadata, connection.id - - # Do not mask registry or metadata failures with another credential attempt. - except HTTPException as exc: - if exc.status_code != 403: - raise - - # Report a stable access error after every eligible credential has been denied. - raise HTTPException(status_code=403, detail="Registry denied image access. Check package permissions and registry credentials.") +async def credentials(session: AsyncSession, organization_id: UUID) -> Sequence[RegistryConnection]: + """Load tenant-owned credentials in deterministic inspection order.""" + + # Only credentials in the caller-authorized organization may reach the registry. + result = await session.scalars( + select(RegistryConnection).where(col(RegistryConnection.organization_id) == organization_id).order_by(col(RegistryConnection.id)) + ) + return result.all() diff --git a/api/src/database/services/users.py b/api/src/database/services/users.py index 92157158f..da95b598f 100644 --- a/api/src/database/services/users.py +++ b/api/src/database/services/users.py @@ -1,10 +1,8 @@ -import asyncio import secrets -from pwdlib import PasswordHash from typing import cast from datetime import UTC, datetime from sqlmodel import col -from src.utils import oauth +from src.utils import oauth, passwords from sqlalchemy import or_, func, select, update from longlink.types import Email from sqlalchemy.exc import IntegrityError @@ -17,8 +15,6 @@ from sqlalchemy.ext.asyncio import AsyncSession from src.database.models.users import User -PASSWORD_HASH = PasswordHash.recommended() - async def fetch(session: AsyncSession, pagination: Pagination, search: str = "") -> tuple[Sequence[User], int]: """Return one newest-first page of Platform users for administrators.""" @@ -96,7 +92,7 @@ async def register(session: AsyncSession, name: str, email: str, password: str, """Add one user and assign its database-generated state without committing.""" # Keep expensive credential hashing outside the request event loop. - hashed_password = await asyncio.to_thread(PASSWORD_HASH.hash, password) + hashed_password = await passwords.hash_password(password) user = User(name=name, email=email, avatar=avatar, password=hashed_password) # Flush so callers can handle uniqueness errors within their existing transaction. @@ -109,7 +105,7 @@ async def replace_password(session: AsyncSession, user: User, password: str) -> """Replace an active user's password only while its validated credential snapshot remains current, without committing.""" # Keep expensive credential hashing outside the request event loop. - hashed_password = await asyncio.to_thread(PASSWORD_HASH.hash, password) + hashed_password = await passwords.hash_password(password) # Consume proof atomically and preserve audit fields that bulk updates do not populate. result = cast( @@ -131,12 +127,13 @@ async def ensure_administrator(session: AsyncSession) -> None: administrator = await session.scalar(select(User).where(col(User.administrator).is_(True)).with_for_update()) if administrator is not None and administrator.email != env.ADMIN_EMAIL: administrator.administrator = False - administrator.password = PASSWORD_HASH.hash(secrets.token_urlsafe(48)) + administrator.password = await passwords.hash_password(secrets.token_urlsafe(48)) statement = select(User).where(col(User.email) == env.ADMIN_EMAIL).with_for_update() user = await session.scalar(statement) if user is None: - user = User(name="Administrator", email=env.ADMIN_EMAIL, password=PASSWORD_HASH.hash(env.ADMIN_PASSWORD), administrator=True) + hashed_password = await passwords.hash_password(env.ADMIN_PASSWORD) + user = User(name="Administrator", email=env.ADMIN_EMAIL, password=hashed_password, administrator=True) # Concurrent Platform startup may create the configured administrator first. try: @@ -159,8 +156,8 @@ async def ensure_administrator(session: AsyncSession) -> None: return # Reconcile the configured account, including one created concurrently by another replica. - if not PASSWORD_HASH.verify(env.ADMIN_PASSWORD, user.password): - user.password = PASSWORD_HASH.hash(env.ADMIN_PASSWORD) + if not await passwords.verify_password(env.ADMIN_PASSWORD, user.password): + user.password = await passwords.hash_password(env.ADMIN_PASSWORD) user.name = "Administrator" user.email = env.ADMIN_EMAIL user.administrator = True diff --git a/api/src/models/companies.py b/api/src/models/companies.py index c541cecfe..c2f20b669 100644 --- a/api/src/models/companies.py +++ b/api/src/models/companies.py @@ -54,13 +54,6 @@ class CompanyProfile(CompanySummary): legal_form: str | None = Field(default=None, max_length=255, validation_alias="resolved_legal_form") registry_url: str | None = Field(default=None, max_length=255) - @field_validator("registry_url") - @classmethod - def validate_registry_url(cls, value: str | None) -> str | None: - """Allow only HTTP registry links.""" - - return str(HttpUrl(value)) if value else None - class CompanyPage(Page[CompanySummary]): """Company results with the effective pagination bounds.""" diff --git a/api/src/operations/computes.py b/api/src/operations/computes.py index 20d7a78a1..cf9995e26 100644 --- a/api/src/operations/computes.py +++ b/api/src/operations/computes.py @@ -6,6 +6,8 @@ from src.kubernetes.storage import Storage from src.database.models.computes import ComputeRegistry +COMPUTE_INFRASTRUCTURE_UNAVAILABLE = "Compute infrastructure is unavailable; verify endpoints, credentials, and certificates" + async def prepare(payload: ComputeRegistryCreate) -> ComputeRegistry: """Discover and verify an unpersisted Compute registration.""" @@ -42,13 +44,9 @@ async def prepare(payload: ComputeRegistryCreate) -> ComputeRegistry: storage = Storage(candidate, cluster) await storage.verify() except Exception as exc: - raise HTTPException( - status_code=503, detail="Compute infrastructure is unavailable; verify endpoints, credentials, and certificates" - ) from exc + raise HTTPException(status_code=503, detail=COMPUTE_INFRASTRUCTURE_UNAVAILABLE) from exc # Discovery failures and the overall deadline use the same unavailable response. except (NotFoundError, ServerError, TimeoutError, OSError) as exc: - raise HTTPException( - status_code=503, detail="Compute infrastructure is unavailable; verify endpoints, credentials, and certificates" - ) from exc + raise HTTPException(status_code=503, detail=COMPUTE_INFRASTRUCTURE_UNAVAILABLE) from exc return candidate diff --git a/api/src/operations/databases.py b/api/src/operations/databases.py index f65a7f50d..75f198ea2 100644 --- a/api/src/operations/databases.py +++ b/api/src/operations/databases.py @@ -16,6 +16,8 @@ from src.models.organizations import DatabaseState from src.database.models.organizations import Organization, OrganizationActivity +TRANSITION_LEASE_DURATION = timedelta(seconds=180) + @dataclass class Lease: @@ -66,7 +68,7 @@ async def renew() -> None: # Renewal must not extend a replacement owner's lease. if not await self.owned(session): raise RuntimeError("Organization activity lease was lost") - expires_at = datetime.now(UTC).replace(microsecond=0) + timedelta(seconds=180) + expires_at = datetime.now(UTC).replace(microsecond=0) + TRANSITION_LEASE_DURATION await session.execute( update(OrganizationActivity) .where(col(OrganizationActivity.organization_id) == self.organization_id) @@ -122,7 +124,7 @@ async def _claim(session: AsyncSession, organization_id: UUID) -> Lease | None: return None # Reserve the transition after removing expired activity. - row = OrganizationActivity(organization_id=organization_id, expires_at=now.replace(microsecond=0) + timedelta(seconds=180)) + row = OrganizationActivity(organization_id=organization_id, expires_at=now.replace(microsecond=0) + TRANSITION_LEASE_DURATION) session.add(row) await session.flush() return Lease(organization_id, row.expires_at) diff --git a/api/src/operations/registries.py b/api/src/operations/registries.py index d63df7253..699d0b123 100644 --- a/api/src/operations/registries.py +++ b/api/src/operations/registries.py @@ -2,10 +2,14 @@ import base64 from uuid import UUID from typing import cast +from fastapi import HTTPException from sqlmodel import col +from src.utils import images from sqlalchemy import select from kr8s.asyncio import Api from src.kubernetes import namespace +from src.models.types import Image +from src.models.metadata import LongLinkMetadata from kr8s.asyncio.objects import Secret from src.database.session import session_scope from src.kubernetes.utils import apply @@ -15,6 +19,38 @@ REGISTRY_LABEL = "longlink.io/registry-connection-id" +async def inspect(organization_id: UUID, image: Image) -> tuple[LongLinkMetadata, UUID | None]: + """Inspect anonymously first, then try tenant-owned credentials outside a database session.""" + + # Public images must not depend on saved credentials; retry only registry access denials. + try: + metadata = await images.required_metadata(image) + return metadata, None + + # Retry only GHCR authorization failures with tenant-owned credentials. + except HTTPException as exc: + if exc.status_code != 403 or image.registry != RegistryConnection.host: + raise + + # Release the credential-selection session before registry I/O. + async with session_scope() as session: + connections = await registries.credentials(session, organization_id) + + # Stop on a successful lookup or a non-authentication error, never masking invalid metadata. + for connection in connections: + try: + metadata = await images.required_metadata(image, connection) + return metadata, connection.id + + # Do not mask registry or metadata failures with another credential attempt. + except HTTPException as exc: + if exc.status_code != 403: + raise + + # Report a stable access error after every eligible credential has been denied. + raise HTTPException(status_code=403, detail="Registry denied image access. Check package permissions and registry credentials.") + + async def synchronize(api: Api, organization_id: UUID) -> None: """Own the transaction that serializes registry credentials and shared pull secrets.""" diff --git a/api/src/operations/usage.py b/api/src/operations/usage.py new file mode 100644 index 000000000..d791e2361 --- /dev/null +++ b/api/src/operations/usage.py @@ -0,0 +1,65 @@ +import httpx +import asyncio +from kr8s import ServerError, NotFoundError, APITimeoutError, ConnectionClosedError +from uuid import UUID +from fastapi import HTTPException +from src.utils import s3 +from sqlalchemy.exc import SQLAlchemyError +from src.kubernetes import client, databases +from botocore.exceptions import ClientError, BotoCoreError +from src.kubernetes.storage import Storage +from src.models.organizations import DatabaseState +from src.database.models.computes import ComputeRegistry +from src.database.models.organizations import Organization + + +async def storage_usage(compute: ComputeRegistry, organization_id: UUID) -> int: + """Measure one Organization bucket with bounded I/O and stable availability errors.""" + + # Bound provider construction and the complete bucket scan. + try: + async with asyncio.timeout(15): + credentials = s3.Credentials(compute.storage_access_key, compute.storage_secret_key) + storage = s3.S3(compute.storage_endpoint, credentials, compute.storage_certificate) + return await storage.usage(Storage.bucket_name(organization_id)) + except (TimeoutError, BotoCoreError, ClientError) as exc: + raise HTTPException(status_code=503, detail="Storage resources unavailable") from exc + + +async def database_usage(organization: Organization, compute: ComputeRegistry) -> int: + """Measure live PostgreSQL bytes without provisioning or repairing the database.""" + + # Usage reads never provision or repair an unavailable database. + if organization.database_state != DatabaseState.available: + raise HTTPException(status_code=503, detail="Database usage unavailable") + + # Bound tunnel establishment and measurement, releasing connections on every outcome. + try: + async with asyncio.timeout(15): + cluster = await client.api(compute.kubeconfig) + async with databases.connection(organization, cluster) as database: + return await database.usage(organization.id) + except ( + TimeoutError, + OSError, + RuntimeError, + SQLAlchemyError, + ServerError, + NotFoundError, + APITimeoutError, + ConnectionClosedError, + httpx.HTTPError, + ) as exc: + raise HTTPException(status_code=503, detail="Database usage unavailable") from exc + + +async def provisioned_database_storage(compute: ComputeRegistry, organization_id: UUID) -> int: + """Observe provisioned database capacity, leaving missing-cluster policy to admission.""" + + # Bound provider observation without changing infrastructure. + try: + async with asyncio.timeout(15): + cluster = await client.api(compute.kubeconfig) + return await databases.provisioned_storage_bytes(cluster, organization_id) + except (TimeoutError, OSError, ServerError, APITimeoutError, ConnectionClosedError, httpx.HTTPError) as exc: + raise HTTPException(status_code=503, detail="Database resources unavailable") from exc diff --git a/api/src/routes/v1/auth.py b/api/src/routes/v1/auth.py index a75deae3d..b5614b9b6 100644 --- a/api/src/routes/v1/auth.py +++ b/api/src/routes/v1/auth.py @@ -1,11 +1,10 @@ import jwt import hmac -import asyncio import secrets from src import auth from typing import Annotated from fastapi import Body, Query, Cookie, Header, Response, APIRouter, HTTPException, BackgroundTasks -from src.utils import mail, oauth, token, cookies +from src.utils import mail, oauth, token, cookies, passwords from longlink.types import Email from sqlalchemy.exc import IntegrityError from src.models.auth import EmailPayload, TokenPayload, PasswordLogin, OAuthAvailability, RegistrationComplete, PasswordResetComplete @@ -142,11 +141,11 @@ async def password_login(session: auth.Session, response: Response, payload: Pas # Load the canonical account identity before verifying its credential. user = await users.by_email(session, payload.email) if user is None: - await asyncio.to_thread(users.PASSWORD_HASH.hash, payload.password) + await passwords.hash_password(payload.password) raise HTTPException(status_code=400, detail="Invalid email or password.") # Verify the supplied password before issuing a session. - password_matches = await asyncio.to_thread(users.PASSWORD_HASH.verify, payload.password, user.password) + password_matches = await passwords.verify_password(payload.password, user.password) if not password_matches or user.deleted_at is not None: raise HTTPException(status_code=400, detail="Invalid email or password.") diff --git a/api/src/routes/v1/organization/image.py b/api/src/routes/v1/organization/image.py index 17ff281f4..206c20925 100644 --- a/api/src/routes/v1/organization/image.py +++ b/api/src/routes/v1/organization/image.py @@ -1,8 +1,8 @@ from src import auth from fastapi import APIRouter +from src.operations import registries from src.models.types import Image from src.models.metadata import LongLinkMetadata -from src.database.services import registries router = APIRouter() diff --git a/api/src/routes/v1/organization/organizations.py b/api/src/routes/v1/organization/organizations.py index d1826c4e1..0648070bd 100644 --- a/api/src/routes/v1/organization/organizations.py +++ b/api/src/routes/v1/organization/organizations.py @@ -1,20 +1,15 @@ -import httpx -import asyncio import aiosmtplib from src import auth -from kr8s import ServerError, NotFoundError, APITimeoutError, ConnectionClosedError from uuid import UUID from fastapi import APIRouter, HTTPException from src.utils import mail, roles -from sqlalchemy.exc import SQLAlchemyError -from src.kubernetes import client, databases +from src.operations import usage from collections.abc import Sequence from src.environments import env from src.models.roles import OrganizationRoles from src.models.resources import OrganizationSolutionSummary from src.database.services import invitations, organizations from src.models.organizations import ( - DatabaseState, OrganizationUsage, OrganizationByteUsage, OrganizationUsageUpdate, @@ -84,10 +79,10 @@ async def get_organization_storage_usage(session: auth.Session, membership: auth await session.commit() # Measure outside the read transaction. - usage = await organizations.storage_usage(compute, membership.organization_id) + used_bytes = await usage.storage_usage(compute, membership.organization_id) # Report the measured usage alongside the tenant's configured quota. - return {"space_used": usage, "quota_bytes": membership.organization.storage_bytes} + return {"space_used": used_bytes, "quota_bytes": membership.organization.storage_bytes} @router.get("/organizations/{organization_id}/database", response_model=OrganizationByteUsage) @@ -98,31 +93,11 @@ async def get_organization_database_usage(session: auth.Session, membership: aut organization, compute = await organizations.database_infrastructure(session, membership.organization_id) await session.commit() - # Usage reads never provision or repair an unavailable database. - if organization.database_state != DatabaseState.available: - raise HTTPException(status_code=503, detail="Database usage unavailable") - - # Bound tunnel establishment and measurement, releasing connections on every outcome. - try: - async with asyncio.timeout(15): - cluster = await client.api(compute.kubeconfig) - async with databases.connection(organization, cluster) as database: - usage = await database.usage(organization.id) - except ( - TimeoutError, - OSError, - RuntimeError, - SQLAlchemyError, - ServerError, - NotFoundError, - APITimeoutError, - ConnectionClosedError, - httpx.HTTPError, - ) as exc: - raise HTTPException(status_code=503, detail="Database usage unavailable") from exc + # Measure outside the read transaction without provisioning. + used_bytes = await usage.database_usage(organization, compute) # Report the configured byte capacity without legacy MiB rounding. - return {"space_used": usage, "quota_bytes": organization.database_storage_bytes} + return {"space_used": used_bytes, "quota_bytes": organization.database_storage_bytes} @router.post("/organizations/{organization_id}/invitations", status_code=204) diff --git a/api/src/routes/v1/organization/payments.py b/api/src/routes/v1/organization/payments.py index 7b18b2983..acde2093b 100644 --- a/api/src/routes/v1/organization/payments.py +++ b/api/src/routes/v1/organization/payments.py @@ -13,6 +13,7 @@ from src.database.models.organizations import Organization router = APIRouter() +ISSUED_INVOICE_STATUSES = frozenset({"open", "paid", "void", "uncollectible"}) @router.get("/organizations/{organization_id}/cards", response_model=list[PaymentCard]) @@ -83,7 +84,7 @@ async def get_invoices(session: auth.Session, membership: auth.OrganizationOwner "hosted_invoice_url": invoice.hosted_invoice_url, } async for invoice in invoices.auto_paging_iter() - if invoice.status in {"open", "paid", "void", "uncollectible"} + if invoice.status in ISSUED_INVOICE_STATUSES ] @@ -110,7 +111,7 @@ async def get_invoice_pdf(invoice_id: str, session: auth.Session, membership: au invoice = await connection.v1.invoices.retrieve_async(invoice_id) # Only finalized invoices belonging to this customer may be downloaded. - if invoice.customer != customer_id or invoice.status not in {"open", "paid", "void", "uncollectible"} or not invoice.invoice_pdf: + if invoice.customer != customer_id or invoice.status not in ISSUED_INVOICE_STATUSES or not invoice.invoice_pdf: raise HTTPException(status_code=404, detail="Invoice PDF unavailable") # Fetch only Stripe-provided invoice documents with bounded time and memory. diff --git a/api/src/routes/v1/organization/solutions.py b/api/src/routes/v1/organization/solutions.py index b3a1c6e93..77df9a766 100644 --- a/api/src/routes/v1/organization/solutions.py +++ b/api/src/routes/v1/organization/solutions.py @@ -1,7 +1,8 @@ from src import auth from fastapi import APIRouter +from src.operations import registries from src.models.solutions import SolutionCreate -from src.database.services import solutions, registries +from src.database.services import solutions router = APIRouter() diff --git a/api/src/utils/cookies.py b/api/src/utils/cookies.py index dff70a498..b6d142c08 100644 --- a/api/src/utils/cookies.py +++ b/api/src/utils/cookies.py @@ -13,6 +13,7 @@ RESET_COOKIE: "/api/v1/auth/reset-password", REGISTRATION_COOKIE: "/api/v1/auth/register", } +AUTHENTICATION_COOKIES = frozenset(_COOKIE_PATHS) # Share the same policy between cookie creation and deletion. diff --git a/api/src/utils/passwords.py b/api/src/utils/passwords.py new file mode 100644 index 000000000..927cab87f --- /dev/null +++ b/api/src/utils/passwords.py @@ -0,0 +1,16 @@ +import asyncio +from pwdlib import PasswordHash + +_password_hash = PasswordHash.recommended() + + +async def hash_password(password: str) -> str: + """Hash a password without blocking the event loop.""" + + return await asyncio.to_thread(_password_hash.hash, password) + + +async def verify_password(password: str, hashed_password: str) -> bool: + """Verify a password without blocking the event loop.""" + + return await asyncio.to_thread(_password_hash.verify, password, hashed_password) diff --git a/api/tests/bootstrap.py b/api/tests/bootstrap.py index 22055858b..3712971a9 100644 --- a/api/tests/bootstrap.py +++ b/api/tests/bootstrap.py @@ -23,6 +23,8 @@ def pytest_load_initial_conftests() -> None: "SMTP_TRANSPORT": "starttls", "SMTP_PASSWORD": "null", "SMTP_USERNAME": "null", + "STRIPE_SECRET_KEY": "null", + "STRIPE_WEBHOOK_SECRET": "null", "GITHUB_OAUTH_CLIENT_ID": "null", "GOOGLE_OAUTH_CLIENT_ID": "null", "GITHUB_OAUTH_CLIENT_SECRET": "null", diff --git a/api/tests/database/services/test_registries.py b/api/tests/database/services/test_registries.py index 2e81077aa..8188f9322 100644 --- a/api/tests/database/services/test_registries.py +++ b/api/tests/database/services/test_registries.py @@ -1,12 +1,7 @@ import pytest -from uuid import UUID from fastapi import HTTPException from factories import create_organization -from src.utils import images -from sqlalchemy.orm import object_session from src.models.types import Image -from src.models.metadata import LongLinkMetadata -from longlink.permissions import Catalog from src.database.session import session_scope from src.database.services import registries from src.database.models.users import User @@ -38,82 +33,3 @@ async def test_resolve_rejects_existing_connection_from_another_organization(use # Assert assert error.value.status_code == 404 assert error.value.detail == "Registry connection not found" - - -async def test_private_image_fallback_never_uses_foreign_credentials( - users: tuple[User, User, User], monkeypatch: pytest.MonkeyPatch -) -> None: - """Retry denied local credentials without disclosing another Organization's token.""" - - # Arrange - organization = await create_organization(users[0]) - foreign_organization = await create_organization(users[2], name="foreign") - - # Put foreign credentials first so removing tenant scoping cannot hide behind local success. - foreign = RegistryConnection(id=UUID(int=1), organization_id=foreign_organization.id, username="foreign", credential="foreign-token") - denied = RegistryConnection(id=UUID(int=2), organization_id=organization.id, username="denied", credential="denied-token") - accepted = RegistryConnection(id=UUID(int=3), organization_id=organization.id, username="accepted", credential="accepted-token") - async with session_scope() as session: - session.add_all([foreign, denied, accepted]) - await session.commit() - image = Image("ghcr.io/acme/private:latest") - metadata = LongLinkMetadata(image=Image("ghcr.io/acme/private@sha256:resolved"), permissions=Catalog(endpoints=[])) - attempts: list[str | None] = [] - - async def required_metadata(requested: Image, connection: RegistryConnection | None = None) -> LongLinkMetadata: - """Model anonymous denial, a rejected local token, and an accepted local token.""" - - assert requested == image - if connection is not None: - assert object_session(connection) is None - attempts.append(connection.credential if connection is not None else None) - if connection is None or connection.id == denied.id: - raise HTTPException(status_code=403, detail="Registry denied access") - assert connection.organization_id == organization.id - assert connection.id == accepted.id - return metadata - - # Replace only external registry inspection, leaving credential selection real. - monkeypatch.setattr(images, "required_metadata", required_metadata) - - # Act - result = await registries.inspect(organization.id, image) - - # Assert - assert result == (metadata, accepted.id) - assert attempts == [None, "denied-token", "accepted-token"] - - -@pytest.mark.parametrize("failure_after_authentication", [False, True]) -async def test_private_image_fallback_stops_on_invalid_metadata( - users: tuple[User, User, User], monkeypatch: pytest.MonkeyPatch, failure_after_authentication: bool -) -> None: - """Propagate invalid metadata without sending any further saved credentials.""" - - # Arrange - organization = await create_organization(users[0]) - first = RegistryConnection(id=UUID(int=1), organization_id=organization.id, username="first", credential="first-token") - later = RegistryConnection(id=UUID(int=2), organization_id=organization.id, username="later", credential="later-token") - async with session_scope() as session: - session.add_all([first, later]) - await session.commit() - failure = HTTPException(status_code=422, detail="Image is missing required LongLink metadata") - attempts: list[str | None] = [] - - async def required_metadata(_image: Image, connection: RegistryConnection | None = None) -> LongLinkMetadata: - """Deny anonymous access only for the credentialed failure scenario.""" - - attempts.append(connection.credential if connection is not None else None) - if connection is None and failure_after_authentication: - raise HTTPException(status_code=403, detail="Registry denied access") - raise failure - - monkeypatch.setattr(images, "required_metadata", required_metadata) - - # Act - with pytest.raises(HTTPException, match="422: Image is missing required LongLink metadata") as raised: - await registries.inspect(organization.id, Image("ghcr.io/acme/private:latest")) - - # Assert - assert raised.value is failure - assert attempts == ([None, "first-token"] if failure_after_authentication else [None]) diff --git a/api/tests/database/services/test_users.py b/api/tests/database/services/test_users.py index ff9a69569..104cc607b 100644 --- a/api/tests/database/services/test_users.py +++ b/api/tests/database/services/test_users.py @@ -1,6 +1,9 @@ +import pytest +import threading from pwdlib import PasswordHash from datetime import UTC, datetime from sqlmodel import col +from src.utils import passwords from sqlalchemy import select from src.environments import env from src.database.session import session_scope @@ -14,7 +17,6 @@ async def test_replace_password_preserves_snapshot_and_caller_transaction(users: # Arrange original = users[1] - password_hash = PasswordHash.recommended() async with session_scope() as session: user = await session.get(User, original.id) assert user is not None @@ -30,7 +32,7 @@ async def test_replace_password_preserves_snapshot_and_caller_transaction(users: assert replaced assert not repeated assert user.password == original.password - assert password_hash.verify("replacement-password", persisted.password) + assert await passwords.verify_password("replacement-password", persisted.password) assert persisted.name == "Pending rename" assert persisted.updated_id == original.id assert persisted.updated_at.replace(tzinfo=UTC) > original.updated_at.replace(tzinfo=UTC) @@ -70,9 +72,6 @@ async def test_replace_password_rejects_pending_account_deletion(users: tuple[Us async def test_ensure_administrator_creates_absent_configured_user() -> None: """Create the configured administrator and preserve its ID and credential hash on repeated reconciliation.""" - # Arrange - password_hash = PasswordHash.recommended() - # Act async with session_scope() as session: await user_service.ensure_administrator(session) @@ -84,7 +83,7 @@ async def test_ensure_administrator_creates_absent_configured_user() -> None: administrator = result.one() assert administrator.name == "Administrator" assert administrator.email == env.ADMIN_EMAIL - assert password_hash.verify(env.ADMIN_PASSWORD, administrator.password) + assert await passwords.verify_password(env.ADMIN_PASSWORD, administrator.password) assert administrator.deleted_at is None # Arrange @@ -133,8 +132,7 @@ async def test_ensure_administrator_replaces_stale_configured_password() -> None """Replace a configured administrator password that no longer matches settings.""" # Arrange - password_hash = PasswordHash.recommended() - stale_password = password_hash.hash("stale-password") + stale_password = await passwords.hash_password("stale-password") async with session_scope() as session: administrator = User(name="Administrator", email=env.ADMIN_EMAIL, password=stale_password, administrator=True) session.add(administrator) @@ -151,7 +149,7 @@ async def test_ensure_administrator_replaces_stale_configured_password() -> None persisted_administrator = await session.get(User, administrator_id) assert persisted_administrator is not None assert persisted_administrator.password != stale_password - assert password_hash.verify(env.ADMIN_PASSWORD, persisted_administrator.password) + assert await passwords.verify_password(env.ADMIN_PASSWORD, persisted_administrator.password) async def test_user_service_retains_deleted_accounts_in_email_lookups_and_administrator_lists(users: tuple[User, User, User]) -> None: @@ -209,3 +207,55 @@ async def test_administrator_handover_keeps_provider_links_on_demoted_account(pa assert replacement.administrator assert replacement.google_id is None assert replacement.github_id is None + + +@pytest.mark.parametrize("handover", [False, True], ids=["create", "handover"]) +async def test_administrator_password_work_runs_outside_event_loop(monkeypatch: pytest.MonkeyPatch, handover: bool) -> None: + """Keep administrator creation, password rotation, and verification off the event-loop thread.""" + + # Arrange + event_loop_thread = threading.get_ident() + operations: list[tuple[str, int]] = [] + stale_hash = "stale-credential" + retired_hash = "retired-credential" + configured_hash = "configured-credential" + + def hash_password(_self: PasswordHash, password: str) -> str: + """Record the hashing thread at the credential-library boundary.""" + + operations.append(("hash", threading.get_ident())) + return configured_hash if password == env.ADMIN_PASSWORD else retired_hash + + def verify_password(_self: PasswordHash, _password: str | bytes, _hashed_password: str | bytes) -> bool: + """Record the verification thread and reject the stale credential.""" + + operations.append(("verify", threading.get_ident())) + return False + + monkeypatch.setattr(PasswordHash, "hash", hash_password) + monkeypatch.setattr(PasswordHash, "verify", verify_password) + if handover: + async with session_scope() as session: + former = User(email="former@example.com", password=stale_hash, administrator=True) + incoming = User(email=env.ADMIN_EMAIL, password=stale_hash) + session.add_all([former, incoming]) + await session.commit() + + # Act + async with session_scope() as session: + await user_service.ensure_administrator(session) + await session.commit() + + # Assert + assert {operation for operation, _thread in operations} == ({"hash", "verify"} if handover else {"hash"}) + assert all(thread != event_loop_thread for _operation, thread in operations) + async with session_scope() as session: + administrator = await user_service.by_email(session, env.ADMIN_EMAIL) + assert administrator is not None + assert administrator.administrator + assert administrator.password == configured_hash + if handover: + retired = await user_service.by_email(session, "former@example.com") + assert retired is not None + assert not retired.administrator + assert retired.password == retired_hash diff --git a/api/tests/operations/test_registries.py b/api/tests/operations/test_registries.py index e1a7748cf..ea06002c4 100644 --- a/api/tests/operations/test_registries.py +++ b/api/tests/operations/test_registries.py @@ -1,15 +1,101 @@ import json import base64 import pytest +from uuid import UUID +from fastapi import HTTPException from conftest import kubernetes_client from factories import create_organization +from src.utils import images +from sqlalchemy.orm import object_session from src.operations import registries from collections.abc import AsyncIterator +from src.models.types import Image +from src.models.metadata import LongLinkMetadata +from longlink.permissions import Catalog from src.database.session import session_scope from src.database.models.users import User from src.database.models.registries import RegistryConnection +async def test_private_image_fallback_never_uses_foreign_credentials( + users: tuple[User, User, User], monkeypatch: pytest.MonkeyPatch +) -> None: + """Retry denied local credentials without disclosing another Organization's token.""" + + # Arrange + organization = await create_organization(users[0]) + foreign_organization = await create_organization(users[2], name="foreign") + + # Put foreign credentials first so removing tenant scoping cannot hide behind local success. + foreign = RegistryConnection(id=UUID(int=1), organization_id=foreign_organization.id, username="foreign", credential="foreign-token") + denied = RegistryConnection(id=UUID(int=2), organization_id=organization.id, username="denied", credential="denied-token") + accepted = RegistryConnection(id=UUID(int=3), organization_id=organization.id, username="accepted", credential="accepted-token") + async with session_scope() as session: + session.add_all([foreign, denied, accepted]) + await session.commit() + image = Image("ghcr.io/acme/private:latest") + metadata = LongLinkMetadata(image=Image("ghcr.io/acme/private@sha256:resolved"), permissions=Catalog(endpoints=[])) + attempts: list[str | None] = [] + + async def required_metadata(requested: Image, connection: RegistryConnection | None = None) -> LongLinkMetadata: + """Model anonymous denial, a rejected local token, and an accepted local token.""" + + assert requested == image + if connection is not None: + assert object_session(connection) is None + attempts.append(connection.credential if connection is not None else None) + if connection is None or connection.id == denied.id: + raise HTTPException(status_code=403, detail="Registry denied access") + assert connection.organization_id == organization.id + assert connection.id == accepted.id + return metadata + + # Replace only external registry inspection, leaving credential selection real. + monkeypatch.setattr(images, "required_metadata", required_metadata) + + # Act + result = await registries.inspect(organization.id, image) + + # Assert + assert result == (metadata, accepted.id) + assert attempts == [None, "denied-token", "accepted-token"] + + +@pytest.mark.parametrize("failure_after_authentication", [False, True]) +async def test_private_image_fallback_stops_on_invalid_metadata( + users: tuple[User, User, User], monkeypatch: pytest.MonkeyPatch, failure_after_authentication: bool +) -> None: + """Propagate invalid metadata without sending any further saved credentials.""" + + # Arrange + organization = await create_organization(users[0]) + first = RegistryConnection(id=UUID(int=1), organization_id=organization.id, username="first", credential="first-token") + later = RegistryConnection(id=UUID(int=2), organization_id=organization.id, username="later", credential="later-token") + async with session_scope() as session: + session.add_all([first, later]) + await session.commit() + failure = HTTPException(status_code=422, detail="Image is missing required LongLink metadata") + attempts: list[str | None] = [] + + async def required_metadata(_image: Image, connection: RegistryConnection | None = None) -> LongLinkMetadata: + """Deny anonymous access only for the credentialed failure scenario.""" + + attempts.append(connection.credential if connection is not None else None) + if connection is None and failure_after_authentication: + raise HTTPException(status_code=403, detail="Registry denied access") + raise failure + + monkeypatch.setattr(images, "required_metadata", required_metadata) + + # Act + with pytest.raises(HTTPException, match="422: Image is missing required LongLink metadata") as raised: + await registries.inspect(organization.id, Image("ghcr.io/acme/private:latest")) + + # Assert + assert raised.value is failure + assert attempts == ([None, "first-token"] if failure_after_authentication else [None]) + + async def test_registry_synchronization_updates_active_secret_and_removes_stale_credentials( monkeypatch: pytest.MonkeyPatch, users: tuple[User, User, User] ) -> None: diff --git a/api/tests/routes/test_mcp.py b/api/tests/routes/test_mcp.py index 15f9becc2..6702b63b7 100644 --- a/api/tests/routes/test_mcp.py +++ b/api/tests/routes/test_mcp.py @@ -9,6 +9,7 @@ from pathlib import Path from datetime import UTC, datetime, timedelta from factories import create_solution, create_organization +from src.utils import passwords from sqlalchemy import delete, select from longlink.app import LongLink from urllib.parse import parse_qs, urlsplit @@ -19,7 +20,6 @@ from src.database.services import mcp from src.database.models.mcp import MCPCode, MCPToken from src.database.models.users import User -from src.database.services.users import PASSWORD_HASH from src.database.models.solutions import Solution from src.database.models.association import UserOrganization from src.database.models.organizations import Organization @@ -219,7 +219,7 @@ async def test_mcp_code_exchange_rechecks_identity_and_membership( # Change account state after authorization proof has already been issued. if invalidation == "password": - user.password = PASSWORD_HASH.hash(secrets.token_urlsafe(32)) + user.password = await passwords.hash_password(secrets.token_urlsafe(32)) else: user.deleted_at = datetime.now(UTC) await session.commit() @@ -459,7 +459,7 @@ async def test_mcp_grants_recheck_expiry_revocation_identity_and_permissions( # Password replacement invalidates the grant's captured fingerprint. if invalidation == "password": - user.password = PASSWORD_HASH.hash(secrets.token_urlsafe(32)) + user.password = await passwords.hash_password(secrets.token_urlsafe(32)) else: user.deleted_at = datetime.now(UTC) await session.commit() diff --git a/api/tests/routes/v1/test_payments.py b/api/tests/routes/v1/test_payments.py index 78f06629e..c6a828068 100644 --- a/api/tests/routes/v1/test_payments.py +++ b/api/tests/routes/v1/test_payments.py @@ -1,6 +1,7 @@ import hmac import json import time +import httpx2 import pytest import stripe import hashlib @@ -135,7 +136,8 @@ async def test_payment_endpoints_require_the_organizations_owner_before_stripe( # Provider invoices expose their display and download links. "invoice_pdf": "https://stripe.example/invoice.pdf", "hosted_invoice_url": "https://stripe.example/invoice", - } + }, + {"id": "in_draft", "object": "invoice", "status": "draft"}, ], }, None, @@ -191,6 +193,66 @@ async def test_payment_endpoints_require_the_organizations_owner_before_stripe( await assert_no_new_operations(previous_operations) +@pytest.mark.usefixtures("configured_stripe") +@pytest.mark.parametrize( + ("status", "customer", "pdf_url", "expected_status"), + [ + pytest.param("paid", "cus_acme", "https://invoice.stripe.com/acme.pdf", 200, id="issued-customer-invoice"), + pytest.param("draft", "cus_acme", "https://invoice.stripe.com/acme.pdf", 404, id="draft"), + pytest.param("paid", "cus_other", "https://invoice.stripe.com/acme.pdf", 404, id="other-customer"), + pytest.param("paid", "cus_acme", "https://example.com/acme.pdf", 502, id="untrusted-pdf-host"), + ], +) +async def test_invoice_pdf_only_downloads_issued_customer_documents( + status: str, + customer: str, + pdf_url: str, + expected_status: int, + clients: tuple[AsyncClient, AsyncClient, AsyncClient], + card_organization: Organization, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Serve issued customer PDFs and reject unsafe downloads before HTTP access.""" + + # Arrange + connection = MagicMock() + connection.v1.invoices.retrieve_async = AsyncMock( + return_value=stripe.Invoice.construct_from( + {"id": "in_acme", "object": "invoice", "status": status, "customer": customer, "invoice_pdf": pdf_url}, None + ) + ) + provider = MagicMock() + provider.return_value.__aenter__.return_value = connection + monkeypatch.setattr(stripe_provider, "client", provider) + document = b"%PDF-1.7\ninvoice document" + requests: list[httpx2.Request] = [] + + def fetch_pdf(request: httpx2.Request) -> httpx2.Response: + """Record external access and return a provider PDF.""" + + requests.append(request) + return httpx2.Response(200, content=document) + + transport = httpx2.MockTransport(fetch_pdf) + http_client = AsyncClient(transport=transport) + monkeypatch.setattr(httpx2, "AsyncClient", MagicMock(return_value=http_client)) + + # Act + response = await clients[1].get(f"/api/v1/organizations/{card_organization.id}/invoices/in_acme/pdf") + + # Assert + assert response.status_code == expected_status + if expected_status == 200: + assert response.content == document + assert response.headers["content-type"] == "application/pdf" + assert response.headers["content-disposition"] == 'inline; filename="invoice.pdf"' + assert response.headers["cache-control"] == "private, no-store" + assert [str(request.url) for request in requests] == [pdf_url] + else: + assert response.json() == {"detail": "Invoice PDF unavailable"} + assert requests == [] + + def signed_webhook(secret: str, *, livemode: bool = False) -> tuple[bytes, str]: """Sign an otherwise actionable checkout event with a current Stripe timestamp.""" diff --git a/api/tests/test_main.py b/api/tests/test_main.py index b3faad244..e9d2c2b49 100644 --- a/api/tests/test_main.py +++ b/api/tests/test_main.py @@ -372,7 +372,7 @@ def test_main_skips_static_routes_when_web_bundle_is_absent(monkeypatch: pytest. @pytest.mark.no_db async def test_lifespan_starts_and_stops_background_jobs(monkeypatch: pytest.MonkeyPatch) -> None: - """Start administrator reconciliation and scheduler work without delaying serving.""" + """Start background jobs without delaying serving and stop them before shared cleanup.""" # Arrange events: list[str] = [] @@ -403,8 +403,11 @@ async def background_task() -> None: return background_task + monkeypatch.setattr(main.env, "STRIPE_SECRET_KEY", "sk_test_lifespan") + monkeypatch.setattr(main.env, "STRIPE_WEBHOOK_SECRET", "whsec_test_lifespan") monkeypatch.setattr(main.jobs, "run_administrator_reconciler", run_background_task("administrator")) monkeypatch.setattr(main.jobs, "run_operation_scheduler", run_background_task("scheduler")) + monkeypatch.setattr(main.invoices, "run", run_background_task("invoices")) monkeypatch.setattr(main.client, "dispose_clients", dispose_clients) monkeypatch.setattr(main, "dispose_engine", dispose_engine) @@ -413,8 +416,8 @@ async def background_task() -> None: await main.asyncio.sleep(0) events.append("serving") - # Assert both jobs stop before the shared Kubernetes transport and database pool are disposed. - assert set(events[:2]) == {"administrator start", "scheduler start"} - assert events[2] == "serving" - assert set(events[3:5]) == {"administrator cancel", "scheduler cancel"} - assert events[5:] == ["kubernetes dispose", "dispose"] + # Assert all jobs stop before the shared Kubernetes transport and database pool are disposed. + assert set(events[:3]) == {"administrator start", "scheduler start", "invoices start"} + assert events[3] == "serving" + assert set(events[4:7]) == {"administrator cancel", "scheduler cancel", "invoices cancel"} + assert events[7:] == ["kubernetes dispose", "dispose"] diff --git a/api/tests/utils/test_cookies.py b/api/tests/utils/test_cookies.py index 334f41c06..bb1c57ee7 100644 --- a/api/tests/utils/test_cookies.py +++ b/api/tests/utils/test_cookies.py @@ -1,4 +1,6 @@ import pytest +from main import app +from httpx2 import AsyncClient, ASGITransport from fastapi import Response from src.utils import cookies from http.cookies import SimpleCookie @@ -7,6 +9,23 @@ pytestmark = pytest.mark.no_db +@pytest.mark.parametrize("credential", [cookies.AUTH_COOKIE, cookies.OAUTH_STATE_COOKIE, cookies.RESET_COOKIE, cookies.REGISTRATION_COOKIE]) +async def test_browser_credential_rejects_untrusted_origin_write(credential: str) -> None: + """Reject writes carrying any browser credential before authentication or route handling.""" + + # Arrange + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as client: + # Act + response = await client.post( + "/api/v1/organizations", headers={"cookie": f"{credential}=credential", "origin": "https://attacker.example"}, json={} + ) + + # Assert + assert response.status_code == 403 + assert response.json() == {"detail": "Origin required"} + + @pytest.mark.parametrize(("public_url", "expected_secure"), [("https://app.example.com", True), ("http://localhost:5173", False)]) def test_set_browser_cookie_marks_secure_only_on_https(monkeypatch: pytest.MonkeyPatch, public_url: str, expected_secure: bool) -> None: """Protect browser credentials and set Secure only for HTTPS origins."""