diff --git a/api/src/database/services/organizations.py b/api/src/database/services/organizations.py index 10302e958..00e6afcb9 100644 --- a/api/src/database/services/organizations.py +++ b/api/src/database/services/organizations.py @@ -10,7 +10,7 @@ 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 databases +from src.kubernetes import client, databases from collections.abc import Sequence from src.models.tags import TagIcon, TagKind from src.environments import env @@ -20,7 +20,6 @@ from botocore.exceptions import ClientError, BotoCoreError from src.models.statuses import Status from src.database.services import operations -from src.kubernetes.client import Kubernetes from src.models.operations import OperationKind from src.models.pagination import Pagination from sqlalchemy.ext.asyncio import AsyncSession @@ -468,9 +467,9 @@ 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") - cluster = Kubernetes(compute.kubeconfig) try: async with asyncio.timeout(15): + cluster = await client.api(compute.kubeconfig) provisioned = await databases.provisioned_storage_bytes(cluster, organization_id) except NotFoundError as exc: if organization.status != Status.failed or organization.provisioned_at is not None: diff --git a/api/src/database/services/permissions.py b/api/src/database/services/permissions.py index a09dee1b3..eb2fb91a4 100644 --- a/api/src/database/services/permissions.py +++ b/api/src/database/services/permissions.py @@ -92,7 +92,16 @@ async def member(session: AsyncSession, solution: Solution, user_id: UUID) -> di async def update_member(session: AsyncSession, solution: Solution, member_id: UUID, payload: models.AccessUpdate) -> None: """Save a reviewed assignment atomically under the Solution management lock.""" - await organizations.require_membership(session, member_id, solution.organization_id) + # The caller holds the active Organization lock; only target membership remains to check. + membership = await session.scalar( + select(col(UserOrganization.user_id)).where( + col(UserOrganization.user_id) == member_id, col(UserOrganization.organization_id) == solution.organization_id + ) + ) + if membership is None: + raise HTTPException(status_code=403, detail="Access required") + + # Reject stale catalog reviews before changing assignments. definition = await catalog(session, solution) if definition is None or payload.revision_id != solution.deployed_revision_id: raise HTTPException(status_code=409, detail="Permission catalog changed; reload before saving") diff --git a/api/src/database/services/registries.py b/api/src/database/services/registries.py index 35ecf3aa4..431db61a7 100644 --- a/api/src/database/services/registries.py +++ b/api/src/database/services/registries.py @@ -4,7 +4,7 @@ from sqlmodel import col from src.utils import images from sqlalchemy import select -from sqlalchemy.orm import defer +from sqlalchemy.orm import defer, load_only from collections.abc import Sequence from src.models.roles import OrganizationRoles from src.models.types import Image @@ -63,9 +63,13 @@ async def delete(session: AsyncSession, organization_id: UUID, connection_id: UU await lock(session, organization_id) await organizations.locked_membership(session, user_id, organization_id, OrganizationRoles.maintain) - # Resolve only registry credentials belonging to the authorized Organization. - connection = await session.get(RegistryConnection, connection_id) - if connection is None or connection.organization_id != organization_id: + # Resolve the tenant-owned identity without decrypting credentials. + connection = await session.scalar( + select(RegistryConnection) + .options(load_only(attr(RegistryConnection.id), raiseload=True)) + .where(col(RegistryConnection.id) == connection_id, col(RegistryConnection.organization_id) == organization_id) + ) + if connection is None: raise HTTPException(status_code=404, detail="Registry connection not found") # Retained deployment revisions must keep their registry credentials available. diff --git a/api/src/kubernetes/client.py b/api/src/kubernetes/client.py index ddf567d97..daa11b5c3 100644 --- a/api/src/kubernetes/client.py +++ b/api/src/kubernetes/client.py @@ -22,38 +22,23 @@ async def dispose_clients() -> None: connections.push_async_callback(api._session.aclose) -# Keep shared API connections separate from operation-owned tunnels. -class Kubernetes: - """Borrow one Compute API connection for resource workflows. - - Database resources have dedicated Organization namespaces; Solutions run in - the Organization compute namespace. Resource operations borrow this client's - lazy kr8s connection. Database and storage workflows own their tunnel scopes. - """ - - def __init__(self, kubeconfig: dict[str, object]) -> None: - """Initialize one lazy cluster connection.""" - - self._kubeconfig = kubeconfig - - async def api(self) -> Api: - """Return the cached kr8s client for the configured cluster.""" - - # Lazily borrow the loop-local connection from kr8s rather than caching it in this wrapper. - api = await kr8s.asyncio.api(kubeconfig=cast(str, self._kubeconfig), serviceaccount="") - - # Only the Platform lifespan owns the borrowed transport. - _api_clients.setdefault(asyncio.get_running_loop(), set()).add(api) - return api - - async def cluster_uid(self) -> str: - """Return the stable UID of the configured Kubernetes cluster.""" - - # The system Namespace is created with the cluster and provides an identity independent of kubeconfig aliases. - system = Namespace("kube-system", api=await self.api()) - await system.refresh() - metadata = system.raw.get("metadata") - uid = metadata.get("uid") if isinstance(metadata, dict) else None - if not isinstance(uid, str) or not uid: - raise RuntimeError("Kubernetes cluster identity is unavailable") - return uid +async def api(kubeconfig: dict[str, object]) -> Api: + """Borrow the loop-local kr8s client owned by the Platform lifespan.""" + + # kr8s caches clients by configuration and event loop. + connection = await kr8s.asyncio.api(kubeconfig=cast(str, kubeconfig), serviceaccount="") + _api_clients.setdefault(asyncio.get_running_loop(), set()).add(connection) + return connection + + +async def cluster_uid(api: Api) -> str: + """Return the stable UID of the configured Kubernetes cluster.""" + + # The system Namespace provides an identity independent of kubeconfig aliases. + system = Namespace("kube-system", api=api) + await system.refresh() + metadata = system.raw.get("metadata") + uid = metadata.get("uid") if isinstance(metadata, dict) else None + if not isinstance(uid, str) or not uid: + raise RuntimeError("Kubernetes cluster identity is unavailable") + return uid diff --git a/api/src/kubernetes/databases.py b/api/src/kubernetes/databases.py index f9d1a790b..bc556992e 100644 --- a/api/src/kubernetes/databases.py +++ b/api/src/kubernetes/databases.py @@ -12,7 +12,7 @@ from src.database.models.organizations import Organization if TYPE_CHECKING: - from src.kubernetes.client import Kubernetes + from kr8s.asyncio import Api ClusterResource = new_class("Cluster", "postgresql.cnpg.io/v1", asyncio=True, plural="clusters") @@ -36,14 +36,7 @@ def _allocation(storage_bytes: int, cpu_millicores: int, ram_bytes: int) -> tupl async def apply( - client: "Kubernetes", - organization_id: UUID, - password: str, - storage_class: str, - *, - storage_bytes: int, - cpu_millicores: int, - ram_bytes: int, + api: "Api", organization_id: UUID, password: str, storage_class: str, *, storage_bytes: int, cpu_millicores: int, ram_bytes: int ) -> None: """Create the database boundary and submit the PostgreSQL cluster.""" @@ -51,7 +44,7 @@ async def apply( if min(storage_bytes, cpu_millicores, ram_bytes) <= 0: raise ValueError("Database storage, CPU and RAM capacity must be positive") database_namespace = namespace.database(organization_id) - existing = ClusterResource("database", namespace=database_namespace, api=await client.api()) + existing = ClusterResource("database", namespace=database_namespace, api=api) try: await existing.refresh() except NotFoundError: @@ -74,7 +67,6 @@ async def apply( quota=json.dumps({"pods": "3", "persistentvolumeclaims": "2", **quota}), resources=json.dumps(resources), ) - api = await client.api() # Establish independent database quota and ingress before CNPG creates any Pods. cluster_document = next(document for document in documents if document.get("kind") == "Cluster") @@ -99,13 +91,12 @@ async def apply( await utils.apply(cluster) -async def resize(client: "Kubernetes", organization_id: UUID, *, storage_bytes: int, cpu_millicores: int, ram_bytes: int) -> None: +async def resize(api: "Api", organization_id: UUID, *, storage_bytes: int, cpu_millicores: int, ram_bytes: int) -> None: """Reconcile running database resources without shrinking persistent storage.""" # Reject unsafe PVC shrink before mutating any quota or database configuration. if min(storage_bytes, cpu_millicores, ram_bytes) <= 0: raise ValueError("Database storage, CPU and RAM capacity must be positive") - api = await client.api() database_namespace = namespace.database(organization_id) cluster = ClusterResource("database", namespace=database_namespace, api=api) await cluster.refresh() @@ -119,21 +110,19 @@ async def resize(client: "Kubernetes", organization_id: UUID, *, storage_bytes: await cluster.patch({"spec": {"storage": {"size": str(storage_bytes)}, "resources": resources}}) -async def provisioned_storage_bytes(client: "Kubernetes", organization_id: UUID) -> int: +async def provisioned_storage_bytes(api: "Api", organization_id: UUID) -> int: """Read the current persistent allocation before accepting a capacity update.""" # Preserve historic binary allocations exactly when validating decimal-byte requests. - api = await client.api() cluster = ClusterResource("database", namespace=namespace.database(organization_id), api=api) await cluster.refresh() return int(utils.quantity(cluster.spec["storage"]["size"])) -async def wait_ready(client: "Kubernetes", organization_id: UUID) -> None: +async def wait_ready(api: "Api", organization_id: UUID) -> None: """Wait for cluster readiness and the expected ready, nonterminating database Pods.""" # Observe readiness without changing externally managed hibernation. - api = await client.api() database_namespace = namespace.database(organization_id) cluster = ClusterResource("database", namespace=database_namespace, api=api) async with asyncio.timeout(2 * 60): @@ -194,18 +183,16 @@ async def wait_ready(client: "Kubernetes", organization_id: UUID) -> None: @asynccontextmanager -async def connection( - organization: Organization, cluster: "Kubernetes", *, certificate: str | None = None -) -> AsyncGenerator[postgres.Postgres]: +async def connection(organization: Organization, api: "Api", *, certificate: str | None = None) -> AsyncGenerator[postgres.Postgres]: """Own a private PostgreSQL tunnel using the caller's CA snapshot or a fresh cluster lookup.""" # Refresh the selector before kr8s resolves a ready Pod for the private database tunnel. - service = Service("database-rw", namespace=namespace.database(organization.id), api=await cluster.api()) + service = Service("database-rw", namespace=namespace.database(organization.id), api=api) await service.refresh() async with service.portforward(5432, local_port="auto") as port: # Preserve the cluster DNS hostname for certificate verification even through a local tunnel. if certificate is None: - certificate = await databases.certificate(cluster, organization.id) + certificate = await databases.certificate(api, organization.id) database = postgres.Postgres( host=namespace.database_hostname(organization.id), port=port, @@ -218,8 +205,8 @@ async def connection( yield database -async def certificate(client: "Kubernetes", organization_id: UUID) -> str: +async def certificate(api: "Api", organization_id: UUID) -> str: """Read the CNPG-generated server CA as PEM text, not a filesystem path.""" # CNPG's default server CA Secret is named after its Cluster. - return await tls.certificate(client, namespace.database(organization_id), "database-ca", entry="ca.crt") + return await tls.certificate(api, namespace.database(organization_id), "database-ca", entry="ca.crt") diff --git a/api/src/kubernetes/gateway.py b/api/src/kubernetes/gateway.py index 7090ed042..98b692734 100644 --- a/api/src/kubernetes/gateway.py +++ b/api/src/kubernetes/gateway.py @@ -5,7 +5,7 @@ from kr8s.asyncio.objects import ConfigMap, Deployment if TYPE_CHECKING: - from src.kubernetes.client import Kubernetes + from kr8s.asyncio import Api def _deployment_is_ready(deployment: Deployment) -> bool: @@ -28,12 +28,11 @@ def _deployment_is_ready(deployment: Deployment) -> bool: ) -async def verify(client: "Kubernetes", gateway_url: str, gateway_certificate: str | None = None) -> None: +async def verify(api: "Api", gateway_url: str, gateway_certificate: str | None = None) -> None: """Inspect package compatibility and readiness without changing infrastructure.""" # Configure trust before opening the operator-configured endpoint. context = ssl.create_default_context(cadata=gateway_certificate) - api = await client.api() # The deployment owner applies the release contract only after shared infrastructure. release = ConfigMap("compute-release", namespace="longlink-system", api=api) @@ -63,7 +62,6 @@ async def verify(client: "Kubernetes", gateway_url: str, gateway_certificate: st http_client = httpx2.AsyncClient(verify=context, trust_env=False, timeout=10, follow_redirects=False) async with http_client: while True: - # Probe routing only after the deployment checks succeed. try: response = await http_client.get(f"{gateway_url.rstrip('/')}/ready", headers={"Host": "internalkourier"}) diff --git a/api/src/kubernetes/organizations.py b/api/src/kubernetes/organizations.py index e6cf7bd0f..b3dfb487c 100644 --- a/api/src/kubernetes/organizations.py +++ b/api/src/kubernetes/organizations.py @@ -8,10 +8,10 @@ from src.models.organizations import MAX_SOLUTIONS, MAX_SOLUTION_CPU_MILLICORES if TYPE_CHECKING: - from src.kubernetes.client import Kubernetes + from kr8s.asyncio import Api -async def apply(client: "Kubernetes", organization_id: UUID, *, cpu_millicores: int, ram_bytes: int) -> None: +async def apply(api: "Api", organization_id: UUID, *, cpu_millicores: int, ram_bytes: int) -> None: """Create one Organization Namespace boundary for its explicit lifecycle.""" # Render and apply only the requested Organization boundary. @@ -33,7 +33,6 @@ async def apply(client: "Kubernetes", organization_id: UUID, *, cpu_millicores: ) # Apply the Namespace before its policy through the lifecycle owner's connection. - api = await client.api() compute_boundary = Namespace(namespace_manifest, api=api) await utils.apply(compute_boundary) diff --git a/api/src/kubernetes/solutions.py b/api/src/kubernetes/solutions.py index bcd6fc110..0e6ee0249 100644 --- a/api/src/kubernetes/solutions.py +++ b/api/src/kubernetes/solutions.py @@ -3,7 +3,7 @@ import asyncio from kr8s import ServerError, NotFoundError, APITimeoutError, ConnectionClosedError from uuid import UUID -from typing import TYPE_CHECKING, cast +from typing import cast from src.utils import templates from kr8s.asyncio import Api from src.kubernetes import utils, namespace @@ -11,9 +11,6 @@ from importlib.resources import files from kr8s.asyncio.objects import Job, Pod, Secret, APIObject, Namespace, new_class -if TYPE_CHECKING: - from src.kubernetes.client import Kubernetes - SOLUTION_ID_LABEL = "longlink.io/solution-id" KnativeServiceResource = new_class("Service", "serving.knative.dev/v1", asyncio=True, plural="services") @@ -152,7 +149,7 @@ async def _wait_for_rollout(deployed: APIObject) -> None: async def apply( - client: "Kubernetes", + api: "Api", organization_id: UUID, solution_id: UUID, image: str, @@ -184,8 +181,6 @@ async def apply( pull_secrets=json.dumps([{"name": f"registry-{registry_connection_id}"}] if registry_connection_id is not None else []), ) - api = await client.api() - # Stop interrupted migrations before another release or fallback can use the schema. await _stop_migrations(api, compute_namespace, solution_id, resume_job=migration_id if migrate else None) @@ -215,12 +210,11 @@ async def apply( await _wait_for_rollout(deployed) -async def delete(client: "Kubernetes", organization_id: UUID, solution_id: UUID) -> None: +async def delete(api: "Api", organization_id: UUID, solution_id: UUID) -> None: """Delete one Solution and wait until its Pods have terminated.""" # Recheck only Kubernetes state while resources and Pods terminate. compute_namespace = namespace.compute(organization_id) - api = await client.api() namespace_resource = Namespace(compute_namespace, api=api) while await namespace_resource.exists(): remaining = False @@ -241,13 +235,12 @@ async def delete(client: "Kubernetes", organization_id: UUID, solution_id: UUID) await asyncio.sleep(5) -async def logs(client: "Kubernetes", organization_id: UUID, solution_id: UUID) -> list[str]: +async def logs(api: "Api", organization_id: UUID, solution_id: UUID) -> list[str]: """Return recent logs for one managed Solution Pod.""" # Scope the Solution Pod lookup to its Organization Namespace. try: compute_namespace = namespace.compute(organization_id) - api = await client.api() migration_pod: Pod | None = None async for candidate in Pod.list(api=api, namespace=compute_namespace, label_selector={SOLUTION_ID_LABEL: str(solution_id)}): pod = cast(Pod, candidate) diff --git a/api/src/kubernetes/storage.py b/api/src/kubernetes/storage.py index 5a8150275..7e72cb790 100644 --- a/api/src/kubernetes/storage.py +++ b/api/src/kubernetes/storage.py @@ -8,14 +8,14 @@ from kr8s.asyncio.objects import Secret, Service if TYPE_CHECKING: - from src.kubernetes.client import Kubernetes + from kr8s.asyncio import Api from src.database.models.computes import ComputeRegistry class Storage: """Verify RustFS and reconcile Organization buckets with Solution service accounts.""" - def __init__(self, compute: "ComputeRegistry", cluster: "Kubernetes") -> None: + def __init__(self, compute: "ComputeRegistry", cluster: "Api") -> None: """Bind controller connections without opening a transport.""" # The controller identity owns bucket lifecycle and service-account administration. @@ -29,7 +29,7 @@ async def _tunnel(self) -> AsyncGenerator[int, None]: """Own the private RustFS administration tunnel for one storage workflow.""" # Forward the cluster service directly so administrator requests never traverse the public storage proxy. - service = Service("rustfs-svc", namespace="rustfs", api=await self._cluster.api()) + service = Service("rustfs-svc", namespace="rustfs", api=self._cluster) await service.refresh() async with service.portforward(9000, local_port="auto") as port: yield port @@ -46,11 +46,11 @@ async def _admin(self) -> AsyncGenerator[rustfs.RustFS, None]: yield admin @staticmethod - async def controller_credentials(cluster: "Kubernetes") -> s3.Credentials: + async def controller_credentials(cluster: "Api") -> s3.Credentials: """Read the chart-managed RustFS administrator credentials without operator input.""" # The chart creates and owns this Secret; the administrator only supplies cluster access. - secret = Secret("longlink-rustfs", namespace="rustfs", api=await cluster.api()) + secret = Secret("longlink-rustfs", namespace="rustfs", api=cluster) await secret.refresh() data = secret.raw.get("data", {}) if not isinstance(data, dict): diff --git a/api/src/kubernetes/storageclasses.py b/api/src/kubernetes/storageclasses.py index 01c9d663e..d7ba9250d 100644 --- a/api/src/kubernetes/storageclasses.py +++ b/api/src/kubernetes/storageclasses.py @@ -2,19 +2,19 @@ from kr8s.asyncio.objects import APIObject, new_class if TYPE_CHECKING: - from src.kubernetes.client import Kubernetes + from kr8s.asyncio import Api DEFAULT_CLASS_ANNOTATION = "storageclass.kubernetes.io/is-default-class" StorageClassResource = new_class("StorageClass", "storage.k8s.io/v1", asyncio=True, namespaced=False, plural="storageclasses") -async def resolve(cluster: "Kubernetes") -> str: +async def resolve(cluster: "Api") -> str: """Return the sole or default StorageClass configured in a Compute cluster.""" # A single class needs no administrator choice; multiple classes require the Kubernetes default marker. classes: list[tuple[str, bool]] = [] - async for candidate in StorageClassResource.list(api=await cluster.api()): + async for candidate in StorageClassResource.list(api=cluster): storage_class = cast(APIObject, candidate) name = storage_class.metadata.get("name") annotations = storage_class.metadata.get("annotations", {}) diff --git a/api/src/kubernetes/tls.py b/api/src/kubernetes/tls.py index ad9efdaac..c9443843f 100644 --- a/api/src/kubernetes/tls.py +++ b/api/src/kubernetes/tls.py @@ -4,14 +4,14 @@ from kr8s.asyncio.objects import Secret if TYPE_CHECKING: - from src.kubernetes.client import Kubernetes + from kr8s.asyncio import Api -async def certificate(client: "Kubernetes", namespace: str, name: str, *, entry: str = "tls.crt") -> str: +async def certificate(api: "Api", namespace: str, name: str, *, entry: str = "tls.crt") -> str: """Read one valid TLS certificate from a Kubernetes Secret.""" # Decode the Kubernetes TLS Secret into the PEM trust data used by Platform clients. - secret = Secret(name, namespace=namespace, api=await client.api()) + secret = Secret(name, namespace=namespace, api=api) await secret.refresh() data = secret.raw.get("data", {}) encoded_certificate = data.get(entry) if isinstance(data, dict) else None diff --git a/api/src/operations/computes.py b/api/src/operations/computes.py index 999dc5f42..20d7a78a1 100644 --- a/api/src/operations/computes.py +++ b/api/src/operations/computes.py @@ -1,9 +1,8 @@ import asyncio from kr8s import ServerError, NotFoundError from fastapi import HTTPException -from src.kubernetes import tls, gateway, storageclasses +from src.kubernetes import tls, client, gateway, storageclasses from src.models.computes import ComputeRegistryCreate -from src.kubernetes.client import Kubernetes from src.kubernetes.storage import Storage from src.database.models.computes import ComputeRegistry @@ -12,11 +11,11 @@ async def prepare(payload: ComputeRegistryCreate) -> ComputeRegistry: """Discover and verify an unpersisted Compute registration.""" # Include cluster discovery and verification in the same deadline. - cluster = Kubernetes(payload.kubeconfig) try: async with asyncio.timeout(7): # Verify cluster identity before accepting its service endpoints. - cluster_uid = await cluster.cluster_uid() + cluster = await client.api(payload.kubeconfig) + cluster_uid = await client.cluster_uid(cluster) try: # Reject invalid storage and trust configuration before endpoint verification. database_storage_class = await storageclasses.resolve(cluster) diff --git a/api/src/operations/databases.py b/api/src/operations/databases.py index 1ed289f68..f65a7f50d 100644 --- a/api/src/operations/databases.py +++ b/api/src/operations/databases.py @@ -6,12 +6,12 @@ from sqlmodel import col from sqlalchemy import text, delete, update from dataclasses import dataclass +from kr8s.asyncio import Api from src.kubernetes import databases as database_resources from collections.abc import AsyncGenerator from src.models.statuses import Status from src.database.session import session_scope from src.database.services import organizations -from src.kubernetes.client import Kubernetes from sqlalchemy.ext.asyncio import AsyncSession from src.models.organizations import DatabaseState from src.database.models.organizations import Organization, OrganizationActivity @@ -180,7 +180,7 @@ async def reconciling(organization_id: UUID) -> AsyncGenerator[Lease | None]: await asyncio.sleep(0.5) -async def prepare(lease: Lease, organization: Organization, cluster: Kubernetes, database_storage_class: str) -> None: +async def prepare(lease: Lease, organization: Organization, cluster: Api, database_storage_class: str) -> None: """Prepare the captured database assignment under the caller's admitted lease.""" # Verify available infrastructure without repeating initialization or changing its published state. diff --git a/api/src/operations/organizations.py b/api/src/operations/organizations.py index ff756fbcc..d6f6f29e1 100644 --- a/api/src/operations/organizations.py +++ b/api/src/operations/organizations.py @@ -5,12 +5,11 @@ from src.utils import stripe from sqlalchemy import or_, select, update from sqlalchemy import delete as sql_delete -from src.kubernetes import utils, namespace, organizations +from src.kubernetes import utils, client, namespace, organizations from src.kubernetes import databases as database_resources from src.operations import invoices, databases, registries from src.models.statuses import Status from src.database.session import session_scope -from src.kubernetes.client import Kubernetes from src.models.operations import OperationKind from src.kubernetes.storage import Storage from src.models.organizations import OrganizationUsageUpdate @@ -53,7 +52,8 @@ async def reconcile(operation: Operation) -> None: desired = allocation or OrganizationUsageUpdate.model_validate(organization, from_attributes=True) # Prepare confirmed database defaults before applying purchased capacity. - cluster = Kubernetes(compute.kubeconfig) + await lease.check() + cluster = await client.api(compute.kubeconfig) await databases.prepare(lease, organization, cluster, compute.database_storage_class) # Reconcile independent pools using only the frozen desired snapshot. @@ -152,13 +152,13 @@ async def delete(organization_id: UUID) -> None: await connection.v1.checkout.sessions.expire_async(hosted.id) # Release the read session before acquiring external cleanup resources. - cluster = Kubernetes(compute.kubeconfig) + cluster = await client.api(compute.kubeconfig) # Namespace deletion cascades every Solution Kubernetes resource and waits for all Pods to terminate. - await utils.delete_namespace(await cluster.api(), namespace.compute(organization.id)) + await utils.delete_namespace(cluster, namespace.compute(organization.id)) # Delete the dedicated CNPG boundary only after compute Pods have terminated. - await utils.delete_namespace(await cluster.api(), namespace.database(organization.id)) + await utils.delete_namespace(cluster, namespace.database(organization.id)) storage = Storage(compute, cluster) await storage.delete(organization.id, solution_ids) diff --git a/api/src/operations/registries.py b/api/src/operations/registries.py index ec2e12900..d63df7253 100644 --- a/api/src/operations/registries.py +++ b/api/src/operations/registries.py @@ -4,18 +4,18 @@ from typing import cast from sqlmodel import col from sqlalchemy import select +from kr8s.asyncio import Api from src.kubernetes import namespace from kr8s.asyncio.objects import Secret from src.database.session import session_scope from src.kubernetes.utils import apply from src.database.services import registries -from src.kubernetes.client import Kubernetes from src.database.models.registries import RegistryConnection REGISTRY_LABEL = "longlink.io/registry-connection-id" -async def synchronize(cluster: Kubernetes, organization_id: UUID) -> None: +async def synchronize(api: Api, organization_id: UUID) -> None: """Own the transaction that serializes registry credentials and shared pull secrets.""" # Never let an older deployment overwrite a newly rotated registry credential. @@ -23,7 +23,6 @@ async def synchronize(cluster: Kubernetes, organization_id: UUID) -> None: await registries.lock(session, organization_id) result = await session.scalars(select(RegistryConnection).where(col(RegistryConnection.organization_id) == organization_id)) connections = result.all() - api = await cluster.api() compute_namespace = namespace.compute(organization_id) # Shared connection names let retained Knative revisions use rotated credentials. diff --git a/api/src/operations/solutions.py b/api/src/operations/solutions.py index a1c648703..d7739e141 100644 --- a/api/src/operations/solutions.py +++ b/api/src/operations/solutions.py @@ -6,15 +6,14 @@ from src.utils import s3 from sqlalchemy import delete as sql_delete from sqlalchemy import update +from src.kubernetes import client, namespace from src.kubernetes import databases as database_resources -from src.kubernetes import namespace from src.kubernetes import solutions as solution_resources from src.operations import registries from sqlalchemy.engine import CursorResult from src.models.statuses import Status from src.database.session import session_scope from src.database.services import organizations -from src.kubernetes.client import Kubernetes from src.kubernetes.storage import Storage from src.models.organizations import MAX_SOLUTION_CPU_MILLICORES from src.database.models.solutions import Revision, Solution @@ -46,7 +45,7 @@ async def deploy(revision_id: UUID) -> None: runtime_secrets = dict(solution.secrets) # Organization reconciliation owns bucket provisioning and quota admission. - cluster = Kubernetes(compute.kubeconfig) + cluster = await client.api(compute.kubeconfig) # Use one current CA snapshot for SQL provisioning and workload rendering in this attempt. database_certificate = await database_resources.certificate(cluster, organization.id) @@ -165,7 +164,7 @@ async def delete(solution_id: UUID) -> None: return # Remove Solution Kubernetes resources before revoking provider credentials. - cluster = Kubernetes(compute.kubeconfig) + cluster = await client.api(compute.kubeconfig) await solution_resources.delete(cluster, organization.id, solution_id) async with database_resources.connection(organization, cluster) as database: await database.delete_solution_schema(organization.id, solution_id) diff --git a/api/src/routes/v1/organization/organizations.py b/api/src/routes/v1/organization/organizations.py index 1e83955b6..d1826c4e1 100644 --- a/api/src/routes/v1/organization/organizations.py +++ b/api/src/routes/v1/organization/organizations.py @@ -7,13 +7,12 @@ from fastapi import APIRouter, HTTPException from src.utils import mail, roles from sqlalchemy.exc import SQLAlchemyError -from src.kubernetes import databases +from src.kubernetes import client, databases 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.kubernetes.client import Kubernetes from src.models.organizations import ( DatabaseState, OrganizationUsage, @@ -106,7 +105,7 @@ async def get_organization_database_usage(session: auth.Session, membership: aut # Bound tunnel establishment and measurement, releasing connections on every outcome. try: async with asyncio.timeout(15): - cluster = Kubernetes(compute.kubeconfig) + cluster = await client.api(compute.kubeconfig) async with databases.connection(organization, cluster) as database: usage = await database.usage(organization.id) except ( diff --git a/api/src/routes/v1/solutions.py b/api/src/routes/v1/solutions.py index 7a2f00286..a135b00fe 100644 --- a/api/src/routes/v1/solutions.py +++ b/api/src/routes/v1/solutions.py @@ -5,12 +5,12 @@ from uuid import UUID from fastapi import Response, APIRouter, HTTPException from src.utils import images +from src.kubernetes import client from src.kubernetes import solutions as solution_resources from src.models.types import Image from src.models.metadata import LongLinkMetadata from src.models.solutions import SolutionPatch, SolutionVisibility, SolutionUpdateCheck from src.database.services import mcp, solutions, registries -from src.kubernetes.client import Kubernetes from sqlalchemy.ext.asyncio import AsyncSession from src.database.models.solutions import Revision, Solution @@ -18,12 +18,11 @@ async def _inspect_update( - session: AsyncSession, solution: Solution, user_id: UUID, expected_revision_id: UUID | None = None -) -> tuple[Solution, Revision, LongLinkMetadata]: - """Inspect the repository's latest image and revalidate the desired revision.""" + session: AsyncSession, solution: Solution, expected_revision_id: UUID | None = None +) -> tuple[Revision, LongLinkMetadata]: + """Inspect the repository's latest image for the authorized desired revision.""" # Reuse authorized Solution access without holding command locks across registry calls. - solution_id = solution.id if expected_revision_id is not None and expected_revision_id != solution.desired_revision_id: raise HTTPException(status_code=409, detail="Desired revision changed since review. Check again.") revision = ( @@ -37,16 +36,11 @@ async def _inspect_update( # Follow latest for updates, including Solutions created with a version tag or digest. source = Image(revision.image) source = Image(f"{source.registry}/{source.repository}:latest") - revision_id = revision.id connection = await registries.resolve(session, solution.organization_id, revision.registry_connection_id, source) await session.commit() metadata = await images.required_metadata(source, connection) - # Revalidate permissions and the source after inspection before returning a candidate. - solution = await solutions.access(session, solution_id, user_id, lock=False) - if solution.desired_revision_id != revision_id: - raise HTTPException(status_code=409, detail="Desired revision changed during inspection. Check again.") - return solution, revision, metadata + return revision, metadata @router.patch("/solutions/{solution_id}/visibility", response_model=SolutionVisibility) @@ -65,8 +59,13 @@ async def update_visibility(solution_id: UUID, payload: SolutionVisibility, sess async def check_update(session: auth.Session, user: auth.CurrentUser, solution: auth.SolutionMaintainer) -> dict[str, object]: """Inspect the repository's latest image without changing deployment state.""" + # Revalidate maintenance access and the source after unlocked inspection. + revision, metadata = await _inspect_update(session, solution) + solution = await solutions.access(session, solution.id, user.id, lock=False) + if solution.desired_revision_id != revision.id: + raise HTTPException(status_code=409, detail="Desired revision changed during inspection. Check again.") + # Expose the reviewed revision and configured names, never environment values. - _, revision, metadata = await _inspect_update(session, solution, user.id) return { "current_image": revision.image, "current_version": revision.version, @@ -81,7 +80,7 @@ async def apply_update(session: auth.Session, user: auth.CurrentUser, solution: """Re-resolve latest and deploy a changed immutable image or configuration.""" # Inspect without command locks, then revalidate the desired state and maintenance access. - solution, revision, metadata = await _inspect_update(session, solution, user.id, payload.expected_revision_id) + revision, metadata = await _inspect_update(session, solution, payload.expected_revision_id) # Lock registry state before the Solution and fence concurrent deployment commands. if revision.registry_connection_id is not None: @@ -167,7 +166,7 @@ async def get_solution_logs(solution_id: UUID, access: auth.SolutionLogAccess) - # Map expected cluster log failures to a service-unavailable response. try: - cluster = Kubernetes(kubeconfig) + cluster = await client.api(kubeconfig) return await solution_resources.logs(cluster, organization_id, solution_id) # Do not expose cluster diagnostics through the public log endpoint. diff --git a/api/tests/alembic/test_versions.py b/api/tests/alembic/test_versions.py index aa953fb3e..1351848ae 100644 --- a/api/tests/alembic/test_versions.py +++ b/api/tests/alembic/test_versions.py @@ -6,7 +6,7 @@ from uuid import UUID, uuid4 from alembic import command from pathlib import Path -from conftest import DatabaseKubernetes +from conftest import database_api from datetime import UTC, datetime from longlink import LegalForm from factories import create_compute @@ -197,7 +197,7 @@ async def test_mysql_organization_deletion_removes_registry_backed_revisions(mon monkeypatch.setattr(session, "Session", async_sessionmaker(engine, expire_on_commit=False)) namespace_cleanup = AsyncMock() storage_cleanup = AsyncMock() - monkeypatch.setattr(src.operations.organizations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(src.operations.organizations.client, "api", database_api) monkeypatch.setattr(src.operations.organizations.utils, "delete_namespace", namespace_cleanup) monkeypatch.setattr(src.operations.organizations.Storage, "delete", storage_cleanup) diff --git a/api/tests/conftest.py b/api/tests/conftest.py index c72c4b3b6..55ca8264a 100644 --- a/api/tests/conftest.py +++ b/api/tests/conftest.py @@ -20,8 +20,6 @@ from src.kubernetes import databases as database_resources from collections.abc import AsyncIterator, AsyncGenerator from src.environments import env -from src.kubernetes.client import Kubernetes -from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine from src.database.models.users import User pytest_plugins = ["containers"] @@ -59,13 +57,10 @@ async def delete_solution(self, organization: UUID, solution: UUID) -> None: """Accept revocation and private-object cleanup without storage I/O.""" -class DatabaseKubernetes(Kubernetes): - """Provide the CNPG provider boundary without opening Kubernetes connections.""" +async def database_api(_kubeconfig: dict[str, object]) -> Api: + """Return an opaque API client consumed only by infrastructure fakes.""" - async def api(self) -> Api: - """Return an opaque API client consumed only by the Service fake.""" - - return cast(Api, object()) + return cast(Api, object()) class DatabasePostgres: @@ -136,7 +131,6 @@ def database_runtime(monkeypatch: pytest.MonkeyPatch) -> None: """Replace only external CNPG and SQL I/O for request and lifecycle tests.""" from src.kubernetes import organizations - from src.operations import databases class Service: """Provide the external database tunnel without Kubernetes I/O.""" @@ -172,7 +166,7 @@ async def certificate(_client: object, _organization: UUID) -> str: return "test-database-ca" - monkeypatch.setattr(databases, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr("src.kubernetes.client.api", database_api) monkeypatch.setattr(database_resources, "Service", Service) monkeypatch.setattr(database_resources, "apply", apply) monkeypatch.setattr(database_resources, "resize", resize) @@ -216,20 +210,17 @@ def unexpected_provider(*_args: object) -> object: monkeypatch.setattr(holder, name, unexpected_provider) -def kubernetes_client() -> Kubernetes: - """Return a lazy Kubernetes client with an opaque external API boundary.""" - - # Initialize the real lifecycle without opening a cluster connection. - return DatabaseKubernetes({}) +def kubernetes_client() -> Api: + """Return an opaque Kubernetes API boundary.""" + # Resource fakes consume this boundary without opening a cluster connection. + return cast(Api, object()) -class RegistryKubernetes(Kubernetes): - """Supply independent synthetic cluster identities without Kubernetes I/O.""" - async def cluster_uid(self) -> str: - """Return an independent identity for each registered test cluster.""" +async def cluster_uid(_api: Api) -> str: + """Return an independent identity for each registered test cluster.""" - return str(uuid4()) + return str(uuid4()) async def verify_compute_gateway(_cluster: object, _url: str, _certificate: str | None, **_kwargs: object) -> None: @@ -256,7 +247,8 @@ def compute_runtime(monkeypatch: pytest.MonkeyPatch) -> None: """Replace external infrastructure discovery and verification for Compute registration.""" # Keep provider replacements local to tests that explicitly register Compute infrastructure. - monkeypatch.setattr("src.kubernetes.client.Kubernetes.cluster_uid", RegistryKubernetes.cluster_uid) + monkeypatch.setattr("src.kubernetes.client.api", database_api) + monkeypatch.setattr("src.kubernetes.client.cluster_uid", cluster_uid) monkeypatch.setattr("src.kubernetes.tls.certificate", tls_certificate) monkeypatch.setattr("src.kubernetes.gateway.verify", verify_compute_gateway) monkeypatch.setattr("src.kubernetes.storageclasses.resolve", database_storage_class) @@ -309,15 +301,14 @@ async def reset_db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, request: pyt db_url = f"sqlite+aiosqlite:///{path}" monkeypatch.setattr(env, "DATABASE_URL", db_url) - engine = create_async_engine(db_url) - session.enable_sqlite_foreign_keys(engine) - monkeypatch.setattr(session, "Session", async_sessionmaker(engine, expire_on_commit=False)) + await session.dispose_engine() + session.get_session() try: # Keep shared test services bound for the complete test lifecycle. yield finally: - await engine.dispose() + await session.dispose_engine() def create_client(user: User | None = None) -> AsyncClient: diff --git a/api/tests/kubernetes/test_client.py b/api/tests/kubernetes/test_client.py index 78be60094..52b5c85eb 100644 --- a/api/tests/kubernetes/test_client.py +++ b/api/tests/kubernetes/test_client.py @@ -2,6 +2,7 @@ import asyncio import secrets from uuid import uuid4 +from typing import cast from contextlib import asynccontextmanager from kr8s.asyncio import Api from src.kubernetes import client as kubernetes_client @@ -24,26 +25,23 @@ def test_kubernetes_api_borrows_lazy_loop_local_factory_client(monkeypatch: pyte "current-context": "test", "users": [{"name": "test", "user": {"token": credential}}], } - version_requests: list[Api] = [] - async def version(api: Api) -> dict[str, str]: + async def version(_api: Api) -> dict[str, str]: """Replace only the external Kubernetes version endpoint.""" - version_requests.append(api) return {"gitVersion": "v1.35.0"} monkeypatch.setattr(Api, "async_version", version) - kubernetes = kubernetes_client.Kubernetes(kubeconfig) - other = kubernetes_client.Kubernetes(kubeconfig) - assert version_requests == [] async def borrow() -> Api: """Borrow concurrently and release ownership before this event loop shuts down.""" # Act try: - first, second, third = await asyncio.gather(kubernetes.api(), kubernetes.api(), other.api()) - repeated = await kubernetes.api() + first, second, third = await asyncio.gather( + kubernetes_client.api(kubeconfig), kubernetes_client.api(kubeconfig), kubernetes_client.api(kubeconfig) + ) + repeated = await kubernetes_client.api(kubeconfig) # Assert assert first is second is third is repeated @@ -81,18 +79,11 @@ def __init__(self, name: str, **_kwargs: object) -> None: async def refresh(self) -> None: """Return the configured namespace metadata.""" - async def api() -> object: - """Provide a local Kubernetes API boundary.""" - - return object() - - kubernetes = kubernetes_client.Kubernetes({"apiVersion": "v1"}) - monkeypatch.setattr(kubernetes, "api", api) monkeypatch.setattr(kubernetes_client, "Namespace", SystemNamespace) # Act and assert with pytest.raises(RuntimeError, match="Kubernetes cluster identity is unavailable"): - await kubernetes.cluster_uid() + await kubernetes_client.cluster_uid(cast(Api, object())) async def test_kubernetes_clients_leave_shared_http_session_to_lifespan(monkeypatch: pytest.MonkeyPatch) -> None: @@ -136,16 +127,14 @@ async def portforward(self, _port: int, **_kwargs: object) -> AsyncGenerator[int closed.append("tunnel") async def create_api(**_kwargs: object) -> Api: - """Share the same API between wrappers, matching the kr8s factory.""" + """Share the same API between borrowers, matching the kr8s factory.""" return api monkeypatch.setattr(kubernetes_client.kr8s.asyncio, "api", create_api) monkeypatch.setattr(databases, "Service", Service) - kubernetes = kubernetes_client.Kubernetes({"apiVersion": "v1"}) - other = kubernetes_client.Kubernetes({"apiVersion": "v1"}) - await kubernetes.api() - assert await other.api() is api + kubernetes = await kubernetes_client.api({"apiVersion": "v1"}) + assert await kubernetes_client.api({"apiVersion": "v1"}) is api organization = Organization(name="test", compute_id=uuid4()) @@ -155,7 +144,7 @@ async def create_api(**_kwargs: object) -> Api: # Assert assert closed == ["tunnel"] - assert await other.api() is api + assert await kubernetes_client.api({"apiVersion": "v1"}) is api # Shut down only after both borrowers have finished, then repeat disposal to check idempotency. await kubernetes_client.dispose_clients() diff --git a/api/tests/kubernetes/test_databases.py b/api/tests/kubernetes/test_databases.py index 56ede5a6d..54a17e206 100644 --- a/api/tests/kubernetes/test_databases.py +++ b/api/tests/kubernetes/test_databases.py @@ -2,9 +2,9 @@ from kr8s import NotFoundError from uuid import uuid4 from conftest import kubernetes_client +from kr8s.asyncio import Api from src.kubernetes import databases from kr8s.asyncio.objects import APIObject -from src.kubernetes.client import Kubernetes pytestmark = pytest.mark.no_db @@ -16,7 +16,7 @@ async def test_database_certificate_reads_cnpg_ca_in_database_namespace(monkeypa organization = uuid4() observed: list[tuple[str, str, str]] = [] - async def certificate(_client: Kubernetes, namespace: str, name: str, *, entry: str) -> str: + async def certificate(_client: Api, namespace: str, name: str, *, entry: str) -> str: """Capture the external trust lookup coordinates.""" observed.append((namespace, name, entry)) diff --git a/api/tests/kubernetes/test_gateway.py b/api/tests/kubernetes/test_gateway.py index 1ee372b66..085241ee1 100644 --- a/api/tests/kubernetes/test_gateway.py +++ b/api/tests/kubernetes/test_gateway.py @@ -171,35 +171,14 @@ def test_compute_package_keeps_gateway_tls_and_infrastructure_boundaries(rendere # RustFS keeps a stable single-instance StatefulSet identity. assert rustfs["spec"]["selector"] == {"matchLabels": {"app.kubernetes.io/name": "rustfs"}} assert rustfs["spec"]["replicas"] == 1 - assert rustfs["spec"]["volumeClaimTemplates"] == [ - { - "metadata": {"name": "data"}, - "spec": { - "accessModes": ["ReadWriteOnce"], - "resources": {"requests": {"storage": "100Gi"}}, - "storageClassName": "block-storage", - }, - } - ] - assert not any( - document and document["kind"] == "ConfigMap" and document["metadata"]["name"] == "rustfs-config" for document in documents - ) container = rustfs["spec"]["template"]["spec"]["containers"][0] - assert {environment["name"] for environment in container["env"]} == { - "RUSTFS_ADDRESS", - "RUSTFS_OBS_LOG_DIRECTORY", - "RUSTFS_OBS_LOGGER_LEVEL", - "RUSTFS_OBS_ENVIRONMENT", - "RUSTFS_VOLUMES", - "RUSTFS_CHART_POD_NAME", - } assert next(environment["value"] for environment in container["env"] if environment["name"] == "RUSTFS_VOLUMES") == "/data" assert container["envFrom"] == [{"secretRef": {"name": "longlink-rustfs"}}] - # Persistent data and logs retain their distinct mounted volumes. - assert container["volumeMounts"] == [{"name": "data", "mountPath": "/data"}, {"name": "logs", "mountPath": "/logs"}] - assert rustfs["spec"]["template"]["spec"]["volumes"] == [{"name": "logs", "emptyDir": {}}] + mount = next(mount for mount in container["volumeMounts"] if mount["mountPath"] == "/data") + claim = next(claim for claim in rustfs["spec"]["volumeClaimTemplates"] if claim["metadata"]["name"] == mount["name"]) + assert claim["spec"]["resources"]["requests"]["storage"] secret = next(document for document in documents if document["kind"] == "Secret" and document["metadata"]["name"] == "longlink-rustfs") assert set(secret["stringData"]) == {"RUSTFS_ACCESS_KEY", "RUSTFS_SECRET_KEY"} diff --git a/api/tests/kubernetes/test_organizations.py b/api/tests/kubernetes/test_organizations.py index 4caa3d70e..952424b71 100644 --- a/api/tests/kubernetes/test_organizations.py +++ b/api/tests/kubernetes/test_organizations.py @@ -117,7 +117,7 @@ async def pods(**_kwargs: object) -> AsyncGenerator[organizations.Pod]: ] }, }, - api=await kubernetes_client().api(), + api=kubernetes_client(), ) monkeypatch.setattr(organizations.utils, "apply", apply) @@ -146,7 +146,7 @@ async def apply(resource: organizations.Namespace) -> None: async def pods(**_kwargs: object) -> AsyncGenerator[organizations.Pod]: """Expose bounded old and new Knative revision Pods.""" - api = await kubernetes_client().api() + api = kubernetes_client() for index in range(revisions): yield organizations.Pod( { @@ -212,7 +212,7 @@ async def wait(resource: kubernetes_utils.Namespace, condition: str) -> None: # Act client = kubernetes_client() - await kubernetes_utils.delete_namespace(await client.api(), "longlink-compute-00000000000040008000000000000001") + await kubernetes_utils.delete_namespace(client, "longlink-compute-00000000000040008000000000000001") # Assert assert deleted == ["longlink-compute-00000000000040008000000000000001"] diff --git a/api/tests/kubernetes/test_solutions.py b/api/tests/kubernetes/test_solutions.py index f35d0d2f5..f80121ccb 100644 --- a/api/tests/kubernetes/test_solutions.py +++ b/api/tests/kubernetes/test_solutions.py @@ -154,7 +154,7 @@ async def test_solution_apply_waits_for_deployment_and_route_readiness( pod_templates: list[dict[str, object]] = [] client = kubernetes_client() - interrupted = solutions.Job({"metadata": {"name": "interrupted"}, "status": {}}, api=await client.api()) + interrupted = solutions.Job({"metadata": {"name": "interrupted"}, "status": {}}, api=client) listed_jobs.append(interrupted) async def patch(job: solutions.Job, patch: dict[str, object]) -> None: @@ -396,8 +396,7 @@ async def test_solution_logs_returns_pod_output( # Arrange client = kubernetes_client() pod = solutions.Pod( - {"metadata": {"labels": {"longlink.io/component": component}, "name": "migration-123"}, "status": {"phase": phase}}, - api=await client.api(), + {"metadata": {"labels": {"longlink.io/component": component}, "name": "migration-123"}, "status": {"phase": phase}}, api=client ) listed_pods.append(pod) @@ -423,7 +422,7 @@ async def test_solution_logs_reports_completed_migration_when_solution_pod_is_un client = kubernetes_client() pod = solutions.Pod( {"metadata": {"labels": {"longlink.io/component": "migration"}, "name": "migration-123"}, "status": {"phase": "Succeeded"}}, - api=await client.api(), + api=client, ) listed_pods.append(pod) @@ -441,9 +440,7 @@ async def test_solution_logs_reports_unavailable_without_usable_pods(listed_pods # Arrange client = kubernetes_client() if phase is not None: - pod = solutions.Pod( - {"metadata": {"labels": {"longlink.io/component": "solution"}}, "status": {"phase": phase}}, api=await client.api() - ) + pod = solutions.Pod({"metadata": {"labels": {"longlink.io/component": "solution"}}, "status": {"phase": phase}}, api=client) listed_pods.append(pod) # Act and assert diff --git a/api/tests/kubernetes/test_storage.py b/api/tests/kubernetes/test_storage.py index f93ba4c17..5ac5c6fd0 100644 --- a/api/tests/kubernetes/test_storage.py +++ b/api/tests/kubernetes/test_storage.py @@ -65,15 +65,9 @@ async def portforward(self, port: int, *, local_port: str) -> AsyncGenerator[int assert clients assert all(client.is_closed for client in clients) - class Cluster: - async def api(self) -> object: - """Return the borrowed cluster connection.""" - - return api - monkeypatch.setattr(storage, "Service", Service) monkeypatch.setattr(storage.httpx2, "AsyncClient", Client) - return Cluster() + return api async def test_storage_administration_uses_cluster_tunnel( diff --git a/api/tests/operations/test_databases.py b/api/tests/operations/test_databases.py index dda3cb77e..be735e11f 100644 --- a/api/tests/operations/test_databases.py +++ b/api/tests/operations/test_databases.py @@ -2,7 +2,7 @@ import asyncio from uuid import UUID, uuid4 from types import SimpleNamespace -from conftest import DatabasePostgres, reject_provider_construction +from conftest import DatabasePostgres, kubernetes_client, reject_provider_construction from datetime import UTC, datetime, timedelta from factories import create_organization from src.operations import databases @@ -76,7 +76,7 @@ async def test_prepare_verifies_readiness_before_opening_postgres( target = await organizations.infrastructure(session, organization.id) assert target is not None snapshot, compute = target - cluster = databases.Kubernetes(compute.kubeconfig) + cluster = kubernetes_client() verified = False async def wait_ready(_client: object, _organization: UUID) -> None: @@ -124,7 +124,7 @@ async def test_prepare_available_database_checks_readiness_without_reinitializin target = await organizations.infrastructure(session, organization.id) assert target is not None snapshot, compute = target - cluster = databases.Kubernetes(compute.kubeconfig) + cluster = kubernetes_client() verified = False async def wait_ready(client: object, organization_id: UUID) -> None: @@ -170,7 +170,7 @@ async def test_prepare_interrupts_provisioning_without_releasing_replacement_lea target = await organizations.infrastructure(session, organization.id) assert target is not None snapshot, compute = target - cluster = databases.Kubernetes(compute.kubeconfig) + cluster = kubernetes_client() started = asyncio.Event() interrupted = asyncio.Event() renew = asyncio.Event() @@ -250,7 +250,7 @@ async def test_prepare_cancellation_releases_owned_lease_and_allows_retry( target = await organizations.infrastructure(session, organization.id) assert target is not None snapshot, compute = target - cluster = databases.Kubernetes(compute.kubeconfig) + cluster = kubernetes_client() started = asyncio.Event() interrupted = asyncio.Event() diff --git a/api/tests/operations/test_organizations.py b/api/tests/operations/test_organizations.py index 46de0bd34..d17ec2ed6 100644 --- a/api/tests/operations/test_organizations.py +++ b/api/tests/operations/test_organizations.py @@ -4,7 +4,7 @@ import asyncio from uuid import UUID, uuid4 from fastapi import HTTPException -from conftest import DatabasePostgres, StorageKubernetes, DatabaseKubernetes, reject_provider_construction +from conftest import DatabasePostgres, StorageKubernetes, database_api, reject_provider_construction from datetime import UTC, datetime, timedelta from pydantic import ValidationError from factories import create_compute, claim_operation, create_solution, queue_operation, create_organization @@ -92,7 +92,7 @@ async def synchronize(_client: object, organization_id: UUID) -> None: monkeypatch.setattr(organization_operations.database_resources.postgres, "Postgres", Database) monkeypatch.setattr(organization_operations.database_resources, "wait_ready", wait_ready) monkeypatch.setattr(organization_operations.database_resources, "resize", resize) - monkeypatch.setattr(organization_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(organization_operations.client, "api", database_api) monkeypatch.setattr(organization_operations, "Storage", Storage) monkeypatch.setattr(organization_operations.organizations, "apply", apply) monkeypatch.setattr(organization_operations.registries, "synchronize", synchronize) @@ -138,7 +138,7 @@ async def wait_ready(_client: object, organization_id: UUID) -> None: assert organization_id == organization.id raise RuntimeError("database is unready") - monkeypatch.setattr(organization_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(organization_operations.client, "api", database_api) monkeypatch.setattr(organization_operations.database_resources, "wait_ready", wait_ready) reject_provider_construction( monkeypatch, @@ -187,7 +187,7 @@ async def apply(self, _organization: UUID, **_kwargs: object) -> None: raise RuntimeError("storage failed") - monkeypatch.setattr(organization_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(organization_operations.client, "api", database_api) monkeypatch.setattr(organization_operations, "Storage", Storage) # Act and assert @@ -233,7 +233,7 @@ async def boundary(_client: object, organization_id: UUID, *, cpu_millicores: in async def synchronize(_client: object, _organization_id: UUID) -> None: """Accept the external registry synchronization.""" - monkeypatch.setattr(organization_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(organization_operations.client, "api", database_api) monkeypatch.setattr(organization_operations, "Storage", StorageKubernetes) monkeypatch.setattr(organization_operations.organizations, "apply", boundary) monkeypatch.setattr(organization_operations.registries, "synchronize", synchronize) @@ -255,7 +255,7 @@ async def test_reconcile_skips_missing_organization_without_constructing_provide # Arrange reject_provider_construction( - monkeypatch, (organization_operations.database_resources.postgres, "Postgres"), (organization_operations, "Kubernetes") + monkeypatch, (organization_operations.database_resources.postgres, "Postgres"), (organization_operations.client, "api") ) # Act and assert @@ -276,7 +276,7 @@ async def test_reconcile_validates_stored_allocation_before_provider_work( operation = await claim_operation() assert operation is not None reject_provider_construction( - monkeypatch, (organization_operations.database_resources.postgres, "Postgres"), (organization_operations, "Kubernetes") + monkeypatch, (organization_operations.database_resources.postgres, "Postgres"), (organization_operations.client, "api") ) # Act and assert @@ -300,7 +300,7 @@ async def test_reconcile_skips_deleted_organization_without_constructing_provide persisted.deleted_at = datetime.now(UTC) await session.commit() reject_provider_construction( - monkeypatch, (organization_operations.database_resources.postgres, "Postgres"), (organization_operations, "Kubernetes") + monkeypatch, (organization_operations.database_resources.postgres, "Postgres"), (organization_operations.client, "api") ) # Act and assert @@ -325,7 +325,7 @@ async def test_reconcile_generic_request_does_not_publish_pending_allocation( async def synchronize(_client: object, _organization_id: UUID) -> None: """Accept external registry synchronization.""" - monkeypatch.setattr(organization_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(organization_operations.client, "api", database_api) monkeypatch.setattr(organization_operations, "Storage", StorageKubernetes) monkeypatch.setattr(organization_operations.registries, "synchronize", synchronize) @@ -371,7 +371,7 @@ async def synchronize(_client: object, _organization_id: UUID) -> None: current.lease_expires_at = datetime.now(UTC) + timedelta(hours=1) await session.commit() - monkeypatch.setattr(organization_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(organization_operations.client, "api", database_api) monkeypatch.setattr(organization_operations, "Storage", StorageKubernetes) monkeypatch.setattr(organization_operations.registries, "synchronize", synchronize) @@ -419,7 +419,7 @@ async def apply(self, organization_id: UUID, *, quota_bytes: int) -> None: async def synchronize(_client: object, _organization_id: UUID) -> None: """Accept external registry synchronization.""" - monkeypatch.setattr(organization_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(organization_operations.client, "api", database_api) monkeypatch.setattr(organization_operations, "Storage", Storage) monkeypatch.setattr(organization_operations.registries, "synchronize", synchronize) @@ -459,7 +459,7 @@ async def test_delete_rejects_active_organization_without_external_cleanup( # Arrange organization = await create_organization(users[0]) reject_provider_construction( - monkeypatch, (organization_operations.database_resources.postgres, "Postgres"), (organization_operations, "Kubernetes") + monkeypatch, (organization_operations.database_resources.postgres, "Postgres"), (organization_operations.client, "api") ) # Act and assert @@ -472,7 +472,7 @@ async def test_delete_skips_missing_organization_without_external_cleanup(monkey # Arrange reject_provider_construction( - monkeypatch, (organization_operations.database_resources.postgres, "Postgres"), (organization_operations, "Kubernetes") + monkeypatch, (organization_operations.database_resources.postgres, "Postgres"), (organization_operations.client, "api") ) # Act and assert @@ -500,7 +500,7 @@ async def delete(_client: object, name: str) -> None: assert name == f"longlink-compute-{organization.id.hex}" raise RuntimeError("namespace deletion failed") - monkeypatch.setattr(organization_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(organization_operations.client, "api", database_api) monkeypatch.setattr(organization_operations.utils, "delete_namespace", delete) reject_provider_construction(monkeypatch, (organization_operations, "Storage")) @@ -564,7 +564,7 @@ async def delete(_client: object, name: str) -> None: assert name == f"longlink-database-{organization.id.hex}" calls.append("database") - monkeypatch.setattr(organization_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(organization_operations.client, "api", database_api) monkeypatch.setattr(organization_operations, "Storage", Storage) monkeypatch.setattr(organization_operations.utils, "delete_namespace", delete) @@ -628,7 +628,7 @@ async def fail_storage(_self: object, organization_id: UUID, solutions: Sequence calls.append("storage failed") raise OSError("storage deletion unavailable") - monkeypatch.setattr(organization_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(organization_operations.client, "api", database_api) monkeypatch.setattr(organization_operations.utils, "delete_namespace", delete_namespace) monkeypatch.setattr(organization_operations.Storage, "delete", delete_storage) @@ -727,7 +727,7 @@ async def delete_storage(_self: object, organization_id: UUID, solutions: Sequen calls.append("storage") monkeypatch.setattr(stripe.HTTPXClient, "request_async", request) - monkeypatch.setattr(organization_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(organization_operations.client, "api", database_api) monkeypatch.setattr(organization_operations.utils, "delete_namespace", delete_namespace) monkeypatch.setattr(organization_operations.Storage, "delete", delete_storage) diff --git a/api/tests/operations/test_registries.py b/api/tests/operations/test_registries.py index 9b13b4657..e1a7748cf 100644 --- a/api/tests/operations/test_registries.py +++ b/api/tests/operations/test_registries.py @@ -24,8 +24,7 @@ async def test_registry_synchronization_updates_active_secret_and_removes_stale_ async with session_scope() as session: session.add_all([connection, foreign_connection]) await session.commit() - cluster = kubernetes_client() - api = await cluster.api() + api = kubernetes_client() active_name = f"registry-{connection.id}" # Record Secret reconciliation without connecting to a cluster. @@ -55,7 +54,7 @@ async def delete(secret: registries.Secret) -> None: monkeypatch.setattr(registries.Secret, "delete", delete) # Act - await registries.synchronize(cluster, organization.id) + await registries.synchronize(api, organization.id) # Assert assert len(applied) == 1 @@ -86,8 +85,7 @@ async def test_registry_synchronization_preserves_secrets_when_publication_fails async with session_scope() as session: session.add(connection) await session.commit() - cluster = kubernetes_client() - api = await cluster.api() + api = kubernetes_client() failure = RuntimeError("Secret publication failed") deleted: list[str] = [] @@ -115,7 +113,7 @@ async def delete(secret: registries.Secret) -> None: # Act with pytest.raises(RuntimeError, match="Secret publication failed") as error: - await registries.synchronize(cluster, organization.id) + await registries.synchronize(api, organization.id) # Assert assert error.value is failure diff --git a/api/tests/operations/test_solutions.py b/api/tests/operations/test_solutions.py index 3437fddbe..3eaff66ce 100644 --- a/api/tests/operations/test_solutions.py +++ b/api/tests/operations/test_solutions.py @@ -1,7 +1,7 @@ import pytest import asyncio from uuid import UUID, uuid4 -from conftest import DatabasePostgres, StorageKubernetes, DatabaseKubernetes, reject_provider_construction +from conftest import DatabasePostgres, StorageKubernetes, database_api, reject_provider_construction from factories import claim_operation, create_solution, fetch_operations, complete_operation, create_organization from src.utils import jobs from contextlib import asynccontextmanager @@ -72,7 +72,7 @@ def unexpected_provider(*args: object, **_kwargs: object) -> object: provider_attempts.append(args) raise AssertionError("provider cleanup ran before Kubernetes deletion completed") - monkeypatch.setattr(solution_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(solution_operations.client, "api", database_api) monkeypatch.setattr(solution_operations.solution_resources, "delete", delete) monkeypatch.setattr(solution_operations.database_resources.postgres, "Postgres", unexpected_provider) @@ -148,7 +148,7 @@ async def delete_prefix(_self: storage.s3.S3, bucket: str, prefix: str) -> None: assert bucket == f"longlink-{organization.id.hex}" calls.append(("prefix", prefix)) - monkeypatch.setattr(solution_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(solution_operations.client, "api", database_api) monkeypatch.setattr(storage, "Service", Service) monkeypatch.setattr(solution_operations.solution_resources, "delete", delete) monkeypatch.setattr(solution_operations, "Storage", storage.Storage) @@ -236,7 +236,7 @@ async def delete_storage(_self: StorageKubernetes, organization_id: UUID, soluti assert organization_id == organization.id calls.append(("storage", solution_id)) - monkeypatch.setattr(solution_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(solution_operations.client, "api", database_api) monkeypatch.setattr(solution_operations.solution_resources, "delete", delete) monkeypatch.setattr(solution_operations.database_resources.postgres, "Postgres", Postgres) monkeypatch.setattr(solution_operations, "Storage", StorageKubernetes) @@ -338,7 +338,7 @@ async def apply( monkeypatch.setattr(solution_operations.database_resources.postgres, "Postgres", FakePostgres) monkeypatch.setattr(solution_operations.database_resources, "Service", Service) - monkeypatch.setattr(solution_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(solution_operations.client, "api", database_api) monkeypatch.setattr(solution_operations.solution_resources, "apply", apply) monkeypatch.setattr(solution_operations, "Storage", Storage) @@ -442,7 +442,7 @@ async def solution_schema(self, *_args: object) -> str: raise RuntimeError("database unavailable") monkeypatch.setattr(solution_operations.database_resources.postgres, "Postgres", FailingPostgres) - monkeypatch.setattr(solution_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(solution_operations.client, "api", database_api) monkeypatch.setattr(solution_operations, "Storage", StorageKubernetes) async def service_account(_self: StorageKubernetes, _organization: UUID, _solution: UUID) -> Credentials: @@ -537,7 +537,7 @@ async def apply( monkeypatch.setattr(StorageKubernetes, "service_account", unexpected_provider) # Control only deployment boundaries while exercising real worker transitions. - monkeypatch.setattr(solution_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(solution_operations.client, "api", database_api) monkeypatch.setattr(solution_operations.solution_resources, "apply", apply) monkeypatch.setattr(solution_operations, "Storage", StorageKubernetes) @@ -594,7 +594,7 @@ async def test_solution_creation_skips_removed_solution_provider_construction( # Arrange _, solution = await create_deleted_solution(users[0]) reject_provider_construction( - monkeypatch, (solution_operations.database_resources.postgres, "Postgres"), (solution_operations, "Kubernetes") + monkeypatch, (solution_operations.database_resources.postgres, "Postgres"), (solution_operations.client, "api") ) # Act @@ -630,7 +630,7 @@ async def apply(_client: object, _organization_id: UUID, _id: UUID, _image: str, raise RuntimeError("rollout failed") # Run the real queue worker against the controlled rollout boundary. - monkeypatch.setattr(solution_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(solution_operations.client, "api", database_api) monkeypatch.setattr(solution_operations.solution_resources, "apply", apply) initial = await claim_operation() assert initial is not None @@ -680,7 +680,7 @@ async def apply( if image.endswith("@sha256:new") and migrate: raise asyncio.CancelledError - monkeypatch.setattr(solution_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(solution_operations.client, "api", database_api) monkeypatch.setattr(solution_operations.solution_resources, "apply", apply) # Execute the initial immutable snapshot before scheduling its replacement. @@ -771,7 +771,7 @@ async def apply( raise RuntimeError("rollout failed") # Execute the real worker with deterministic rollout failure and recovery boundaries. - monkeypatch.setattr(solution_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(solution_operations.client, "api", database_api) monkeypatch.setattr(solution_operations.solution_resources, "apply", apply) # Execute the initial claim before observing replacement recovery. @@ -947,7 +947,7 @@ async def apply( await solutions.delete(session, solution.id, owner.id) await session.commit() - monkeypatch.setattr(solution_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(solution_operations.client, "api", database_api) monkeypatch.setattr(solution_operations.solution_resources, "apply", apply) await execute(operation) @@ -1043,7 +1043,7 @@ async def apply( await session.commit() third_id = current.desired_revision_id - monkeypatch.setattr(solution_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(solution_operations.client, "api", database_api) # Exercise queue transitions with the controlled rollout boundary. monkeypatch.setattr(solution_operations.solution_resources, "apply", apply) @@ -1096,7 +1096,7 @@ async def test_solution_lifecycle_skips_missing_target_without_constructing_prov # Arrange reject_provider_construction( - monkeypatch, (solution_operations.database_resources.postgres, "Postgres"), (solution_operations, "Kubernetes") + monkeypatch, (solution_operations.database_resources.postgres, "Postgres"), (solution_operations.client, "api") ) # Act and assert @@ -1128,7 +1128,7 @@ async def solution_schema(self, *_args: object) -> str: monkeypatch.setattr(solution_operations.database_resources.postgres, "Postgres", Postgres) # Replace only cluster and storage boundaries for deletion cleanup. - monkeypatch.setattr(solution_operations, "Kubernetes", DatabaseKubernetes) + monkeypatch.setattr(solution_operations.client, "api", database_api) monkeypatch.setattr(solution_operations, "Storage", StorageKubernetes) # Act diff --git a/api/tests/routes/v1/test_computes.py b/api/tests/routes/v1/test_computes.py index ba0873d00..014c5db76 100644 --- a/api/tests/routes/v1/test_computes.py +++ b/api/tests/routes/v1/test_computes.py @@ -143,7 +143,7 @@ async def cluster_uid(_cluster: object) -> str: return "cluster-uid" - monkeypatch.setattr("src.kubernetes.client.Kubernetes.cluster_uid", cluster_uid) + monkeypatch.setattr("src.kubernetes.client.cluster_uid", cluster_uid) payload = { "name": "Duplicate Compute", "kubeconfig": { @@ -197,7 +197,7 @@ def unexpected_kubernetes(*_args: object) -> object: raise AssertionError("Kubernetes must not be constructed") - monkeypatch.setattr("src.kubernetes.client.Kubernetes.__init__", unexpected_kubernetes) + monkeypatch.setattr("src.kubernetes.client.api", unexpected_kubernetes) payload = { "name": "Unsafe Compute", "gateway_url": "https://gateway.example", @@ -229,7 +229,7 @@ def unexpected_kubernetes(*_args: object) -> object: ), *( pytest.param( - "client.Kubernetes.cluster_uid", + "client.cluster_uid", error("private-cluster-credential"), 503, "Compute infrastructure is unavailable; verify endpoints, credentials, and certificates", @@ -238,7 +238,7 @@ def unexpected_kubernetes(*_args: object) -> object: for error in (NotFoundError, ServerError, TimeoutError, OSError) ), pytest.param( - "client.Kubernetes.cluster_uid", + "client.cluster_uid", None, 503, "Compute infrastructure is unavailable; verify endpoints, credentials, and certificates", diff --git a/api/tests/routes/v1/test_organizations.py b/api/tests/routes/v1/test_organizations.py index e72735260..cb23b7e59 100644 --- a/api/tests/routes/v1/test_organizations.py +++ b/api/tests/routes/v1/test_organizations.py @@ -3,12 +3,14 @@ from kr8s import NotFoundError from uuid import UUID, uuid4 from httpx2 import AsyncClient, ASGITransport +from conftest import database_api from datetime import UTC, datetime from sqlmodel import col, select from factories import create_compute, create_solution, fetch_operations, create_organization, assert_no_new_operations from src.utils import s3, mail, postgres from contextlib import asynccontextmanager from sqlalchemy import func, event, update, literal_column +from kr8s.asyncio import Api from urllib.parse import urlencode from unittest.mock import AsyncMock from sqlalchemy.exc import SQLAlchemyError @@ -22,7 +24,6 @@ from src.models.statuses import Status from src.database.session import session_scope from src.database.services import operations, invitations, organizations -from src.kubernetes.client import Kubernetes from src.models.operations import OperationKind from src.database.models.tags import OrganizationTag from src.models.organizations import DatabaseState @@ -281,6 +282,7 @@ async def test_usage_edit_accepts_database_pools_larger_than_compute_and_files( "database_storage_bytes": organization.database_storage_bytes, "database_cpu_millicores": 1000, } + monkeypatch.setattr("src.kubernetes.client.api", database_api) monkeypatch.setattr(databases, "provisioned_storage_bytes", AsyncMock(return_value=organization.database_storage_bytes)) monkeypatch.setattr(s3.S3, "usage", AsyncMock(return_value=17)) @@ -324,6 +326,7 @@ async def test_usage_edit_rejects_desired_and_provisioned_database_shrinking( ) } provisioned = AsyncMock(return_value=capacity["database_storage_bytes"] * 2) + monkeypatch.setattr("src.kubernetes.client.api", database_api) monkeypatch.setattr(databases, "provisioned_storage_bytes", provisioned) smaller = {**capacity, "database_storage_bytes": capacity["database_storage_bytes"] // 2} same_disk = {**capacity, "compute_cpu_millicores": capacity["compute_cpu_millicores"] - 250} @@ -382,6 +385,7 @@ async def test_usage_edit_preserves_current_files_on_downsize( capacity["storage_bytes"] //= 2 quota = capacity["storage_bytes"] provisioned = AsyncMock(return_value=capacity["database_storage_bytes"]) + monkeypatch.setattr("src.kubernetes.client.api", database_api) monkeypatch.setattr(databases, "provisioned_storage_bytes", provisioned) measurement = AsyncMock(side_effect=[TimeoutError(), quota + 1, quota, quota]) monkeypatch.setattr(s3.S3, "usage", measurement) @@ -492,6 +496,7 @@ async def test_usage_edit_accepts_minimum_workload_capacity_and_positive_file_sh "database_ram_bytes": 256 * 1024**2, "database_storage_bytes": 100 * 1024**2, } + monkeypatch.setattr("src.kubernetes.client.api", database_api) monkeypatch.setattr(databases, "provisioned_storage_bytes", AsyncMock(return_value=capacity["database_storage_bytes"])) monkeypatch.setattr(s3.S3, "usage", AsyncMock(return_value=0)) @@ -538,6 +543,7 @@ async def test_usage_edit_can_update_desired_capacity_before_month_end_snapshot( ) } capacity["storage_bytes"] //= 2 + monkeypatch.setattr("src.kubernetes.client.api", database_api) monkeypatch.setattr(databases, "provisioned_storage_bytes", AsyncMock(return_value=capacity["database_storage_bytes"])) monkeypatch.setattr(s3.S3, "usage", AsyncMock(return_value=0)) @@ -991,7 +997,7 @@ async def measure(_database: postgres.Postgres, organization_id: UUID) -> int: return usage @asynccontextmanager - async def connection(target: Organization, _cluster: Kubernetes) -> AsyncGenerator[postgres.Postgres]: + async def connection(target: Organization, _cluster: Api) -> AsyncGenerator[postgres.Postgres]: """Provide the external tunnel while checking the caller released its transaction.""" assert target.id == organization.id @@ -1004,6 +1010,7 @@ async def connection(target: Organization, _cluster: Kubernetes) -> AsyncGenerat finally: released.append(target.id) + monkeypatch.setattr("src.kubernetes.client.api", database_api) monkeypatch.setattr(databases, "connection", connection) monkeypatch.setattr(postgres.Postgres, "usage", measure) @@ -1034,7 +1041,7 @@ def unexpected_provider(*_args: object) -> object: raise AssertionError("database usage reached a provider") - monkeypatch.setattr("src.routes.v1.organization.organizations.Kubernetes", unexpected_provider) + monkeypatch.setattr("src.kubernetes.client.api", unexpected_provider) # Act denied = await clients[1].get(f"/api/v1/organizations/{organization.id}/database") diff --git a/api/tests/routes/v1/test_permissions.py b/api/tests/routes/v1/test_permissions.py index 5e9515a1b..3d3012ee0 100644 --- a/api/tests/routes/v1/test_permissions.py +++ b/api/tests/routes/v1/test_permissions.py @@ -96,33 +96,40 @@ async def test_permission_management_requires_administration_in_the_solution_org assert saved_access.role == "read" -async def test_administrator_cannot_manage_access_for_a_foreign_organization_member( - clients: tuple[AsyncClient, AsyncClient, AsyncClient], permission_solution: tuple[Solution, User, User] +@pytest.mark.parametrize("membership", ["foreign", "removed"]) +async def test_administrator_cannot_manage_access_without_target_membership( + clients: tuple[AsyncClient, AsyncClient, AsyncClient], permission_solution: tuple[Solution, User, User], membership: str ) -> None: - """Reject foreign target members even when the caller can administer the Solution.""" + """Reject foreign and removed members before checking catalog revisions or saving access.""" # Arrange solution, member, foreign_owner = permission_solution revision_id = str(solution.deployed_revision_id) - access_url = f"/api/v1/solutions/{solution.id}/members/{foreign_owner.id}/access" + target = foreign_owner if membership == "foreign" else member + access_url = f"/api/v1/solutions/{solution.id}/members/{target.id}/access" client = clients[1] local_access = await client.get(f"/api/v1/solutions/{solution.id}/members/{member.id}/access") assert local_access.status_code == 200 assert local_access.json() == {"role": None, "revision_id": revision_id} async with session_scope() as session: - assignment = await session.get(SolutionMemberAccess, (foreign_owner.id, solution.id)) + if membership == "removed": + access = await session.get(UserOrganization, (member.id, solution.organization_id)) + assert access is not None + await session.delete(access) + await session.commit() + assignment = await session.get(SolutionMemberAccess, (target.id, solution.id)) assert assignment is None # Act access = await client.get(access_url) - update = await client.put(access_url, json={"role": "approver", "revision_id": revision_id}) + update = await client.put(access_url, json={"role": "approver", "revision_id": str(uuid4())}) # Assert for response in (access, update): assert response.status_code == 403 assert response.json() == {"detail": "Access required"} async with session_scope() as session: - assignment = await session.get(SolutionMemberAccess, (foreign_owner.id, solution.id)) + assignment = await session.get(SolutionMemberAccess, (target.id, solution.id)) assert assignment is None diff --git a/api/tests/routes/v1/test_registries.py b/api/tests/routes/v1/test_registries.py index c49aa4eb3..ba86547c3 100644 --- a/api/tests/routes/v1/test_registries.py +++ b/api/tests/routes/v1/test_registries.py @@ -12,7 +12,7 @@ assert_no_new_operations, ) from src.utils import github -from sqlalchemy import select +from sqlalchemy import select, update, literal from src.models.roles import OrganizationRoles from src.database.session import session_scope from src.models.operations import OperationKind @@ -245,13 +245,19 @@ async def username(token: SecretStr) -> str: async def test_registry_delete_commits_removal_and_fresh_reconciliation( clients: tuple[AsyncClient, AsyncClient, AsyncClient], users: tuple[User, User, User] ) -> None: - """Commit unused credential removal with new demand despite unfinished reconciliation.""" + """Remove unreadable credentials with new demand despite unfinished reconciliation.""" # Arrange organization = await create_organization(users[1]) connection = RegistryConnection(organization_id=organization.id, username="unused", credential="delete-token") async with session_scope() as session: session.add(connection) + await session.flush() + + # Bypass encryption to represent unreadable persisted ciphertext. + await session.execute( + update(RegistryConnection).where(RegistryConnection.id == connection.id).values(credential=literal("unreadable-ciphertext")) + ) await session.commit() await queue_operation(target_id=organization.id) await claim_operation() diff --git a/api/tests/routes/v1/test_solutions.py b/api/tests/routes/v1/test_solutions.py index f28fda618..9652384c5 100644 --- a/api/tests/routes/v1/test_solutions.py +++ b/api/tests/routes/v1/test_solutions.py @@ -6,7 +6,6 @@ from uuid import UUID, uuid4 from httpx2 import AsyncClient, ASGITransport from fastapi import HTTPException -from conftest import DatabaseKubernetes from datetime import UTC, datetime from sqlmodel import col from factories import add_member, create_solution, fetch_operations, create_organization, assert_no_new_operations @@ -549,7 +548,12 @@ async def logs(_client: object, organization_id: UUID, solution_id: UUID) -> lis captured["organization"] = organization_id return ["line 1", "line 2"] - monkeypatch.setattr("src.routes.v1.solutions.Kubernetes", DatabaseKubernetes) + async def cluster_api(_kubeconfig: object) -> object: + """Return an opaque cluster connection for log retrieval.""" + + return object() + + monkeypatch.setattr("src.routes.v1.solutions.client.api", cluster_api) monkeypatch.setattr("src.routes.v1.solutions.solution_resources.logs", logs) # Act @@ -587,12 +591,12 @@ async def test_app_logs_reject_non_maintainers_before_constructing_kubernetes( if role is not None: await add_member(user=member, organization=organization, role=role) - def unexpected_kubernetes(*_args: object) -> object: + async def unexpected_kubernetes(*_args: object) -> object: """Fail if authorization reaches the external cluster boundary.""" raise AssertionError("Kubernetes client was constructed") - monkeypatch.setattr("src.routes.v1.solutions.Kubernetes", unexpected_kubernetes) + monkeypatch.setattr("src.routes.v1.solutions.client.api", unexpected_kubernetes) # Act response = await clients[1].get(f"/api/v1/solutions/{app.id}/logs") @@ -616,20 +620,20 @@ async def test_app_logs_return_unavailable_when_backend_fails( organization = await create_organization(owner) app = await create_solution(organization) - def unavailable_kubernetes(_kubeconfig: object) -> DatabaseKubernetes: + async def unavailable_kubernetes(_kubeconfig: object) -> object: """Fail at the configured Kubernetes boundary.""" # Keep construction and retrieval failures as distinct provider scenarios. if failure_stage == "construction": raise RuntimeError("cluster credential unavailable") - return DatabaseKubernetes({}) + return object() async def unavailable_logs(_client: object, _organization_id: UUID, _solution_id: UUID) -> list[str]: """Fail retrieval separately from client construction.""" raise RuntimeError("logs unavailable") - monkeypatch.setattr("src.routes.v1.solutions.Kubernetes", unavailable_kubernetes) + monkeypatch.setattr("src.routes.v1.solutions.client.api", unavailable_kubernetes) monkeypatch.setattr("src.routes.v1.solutions.solution_resources.logs", unavailable_logs) # Act @@ -652,12 +656,12 @@ async def test_solution_logs_reject_deleted_solution_before_constructing_kuberne delete_response = await clients[0].delete(f"/api/v1/solutions/{solution.id}") assert delete_response.status_code == 204 - def unexpected_kubernetes(*_args: object) -> object: + async def unexpected_kubernetes(*_args: object) -> object: """Fail if a deleted Solution reaches the cluster boundary.""" raise AssertionError("Kubernetes client was constructed") - monkeypatch.setattr("src.routes.v1.solutions.Kubernetes", unexpected_kubernetes) + monkeypatch.setattr("src.routes.v1.solutions.client.api", unexpected_kubernetes) # Act response = await clients[0].get(f"/api/v1/solutions/{solution.id}/logs") @@ -1298,6 +1302,75 @@ async def metadata(_image: Image, _connection: object | None = None) -> LongLink await assert_no_new_operations(previous_operations) +@pytest.mark.parametrize(("method", "status", "detail"), [("GET", 403, "Access required"), ("POST", 409, "Organization is not available")]) +async def test_release_inspection_rejects_organization_deletion_during_metadata_wait( + clients: tuple[AsyncClient, AsyncClient, AsyncClient], + users: tuple[User, User, User], + monkeypatch: pytest.MonkeyPatch, + method: str, + status: int, + detail: str, +) -> None: + """Reject a private release after its Organization is deleted without changing deployment state.""" + + # Arrange + organization = await create_organization(users[0]) + solution = await create_solution(organization, envs={"KEEP": "private-value"}) + async with session_scope() as session: + connection = RegistryConnection(organization_id=organization.id, username="maintainer", credential="registry-secret") + session.add(connection) + await session.flush() + current = await solutions.access(session, solution.id, users[0].id) + await solutions.deploy( + session, + current, + users[0].id, + LongLinkMetadata(image=Image("ghcr.io/longlink/dashboard@sha256:private"), permissions=Catalog(endpoints=[])), + {"KEEP": "private-value"}, + registry_connection_id=connection.id, + ) + await session.commit() + previous_revision_id = current.desired_revision_id + previous_status = current.status + previous_deployed_id = current.deployed_revision_id + result = await session.scalars(select(col(Revision.id)).where(col(Revision.solution_id) == solution.id)) + previous_revisions = set(result.all()) + previous_operations = await fetch_operations() + + async def metadata(_image: Image, _connection: object | None = None) -> LongLinkMetadata: + """Tombstone the parent during the unlocked registry wait.""" + + async with session_scope() as session: + parent = await session.get(Organization, organization.id) + assert parent is not None + parent.deleted_at = datetime.now(UTC) + await session.commit() + return LongLinkMetadata(image=Image("ghcr.io/longlink/dashboard@sha256:candidate"), permissions=Catalog(endpoints=[])) + + monkeypatch.setattr(images, "required_metadata", metadata) + + # Act + response = await clients[0].request( + method, + f"/api/v1/solutions/{solution.id}/update", + json={"expected_revision_id": str(previous_revision_id), "envs": {"NEW": "new-value"}}, + ) + + # Assert + assert response.status_code == status + assert response.json() == {"detail": detail} + async with session_scope() as session: + current = await session.get(Solution, solution.id, options=(selectinload(Solution.desired_revision),)) + assert current is not None + assert current.status == previous_status + assert current.deployed_revision_id == previous_deployed_id + assert current.desired_revision_id == previous_revision_id + assert current.desired_revision.envs == {"KEEP": "private-value"} + result = await session.scalars(select(col(Revision.id)).where(col(Revision.solution_id) == solution.id)) + assert set(result.all()) == previous_revisions + await assert_no_new_operations(previous_operations) + + async def test_update_rolls_back_revision_and_pointer_after_queue_insert_failure( clients: tuple[AsyncClient, AsyncClient, AsyncClient], users: tuple[User, User, User], monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/api/tests/routes/v1/test_users.py b/api/tests/routes/v1/test_users.py index fe3d618f1..bf2dbcba6 100644 --- a/api/tests/routes/v1/test_users.py +++ b/api/tests/routes/v1/test_users.py @@ -165,7 +165,7 @@ async def unavailable(*_args: object, **_kwargs: object) -> None: pytest.fail("Profile updates must not access Organization databases") - monkeypatch.setattr("src.kubernetes.client.Kubernetes.api", unavailable) + monkeypatch.setattr("src.kubernetes.client.api", unavailable) # Act response = await clients[1].patch("/api/v1/me", json={"name": expected_name, "theme": "dark"}) diff --git a/api/tests/test_main.py b/api/tests/test_main.py index 4c52d3944..b3faad244 100644 --- a/api/tests/test_main.py +++ b/api/tests/test_main.py @@ -207,7 +207,7 @@ def unexpected_kubernetes(*_args: object, **_kwargs: object) -> None: raise AssertionError("untrusted Compute write must not verify infrastructure") - monkeypatch.setattr("src.kubernetes.client.Kubernetes.__init__", unexpected_kubernetes) + monkeypatch.setattr("src.kubernetes.client.api", unexpected_kubernetes) headers = untrusted_origin_headers(clients[0], origin) # Act