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: 1 addition & 2 deletions api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"})


Expand Down
31 changes: 5 additions & 26 deletions api/src/database/services/organizations.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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."""

Expand Down Expand Up @@ -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")

Expand Down
46 changes: 8 additions & 38 deletions api/src/database/services/registries.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
19 changes: 8 additions & 11 deletions api/src/database/services/users.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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."""
Expand Down Expand Up @@ -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.
Expand All @@ -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(
Expand All @@ -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:
Expand All @@ -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
Expand Down
7 changes: 0 additions & 7 deletions api/src/models/companies.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
10 changes: 4 additions & 6 deletions api/src/operations/computes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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
6 changes: 4 additions & 2 deletions api/src/operations/databases.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
36 changes: 36 additions & 0 deletions api/src/operations/registries.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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."""

Expand Down
Loading