Initial curated RAGcore source from c16667f0c9397e2bfc8dd0255b114fba23c8d05e

This commit is contained in:
Public Source Publisher committed 2026-10-01 01:34:21 +02:00
commit 7ca726caf2
659 files changed
+98171

No files matched your search

@@ -0,0 +1,278 @@
from __future__ import annotations
from pathlib import Path
from uuid import UUID, uuid4
import yaml
from fastapi.testclient import TestClient
from ragcore.api.v1.control.dependencies import (
get_control_application,
get_credential_service,
get_principal,
)
from ragcore.application.authorization import AuthorizationService
from ragcore.application.control.api import ControlPlaneApplication
from ragcore.application.identity.credentials import ServiceAccountCredentialService
from ragcore.domain.authorization import Principal, PrincipalType
from ragcore.domain.control import (
Application,
Grant,
KnowledgeSpace,
Policy,
Role,
ServiceAccount,
UserGrant,
Workspace,
)
from ragcore.infrastructure.database.identity.memory import InMemoryCredentialRepository
from ragcore.main import create_app
class FakeControlRepository:
def __init__(self, workspace: Workspace) -> None:
self.workspace = workspace
self.applications: list[Application] = []
self.service_accounts: list[ServiceAccount] = []
self.spaces: list[KnowledgeSpace] = []
self.grants: list[Grant] = []
self.policies: list[Policy] = []
async def get_workspace(self, workspace_id: UUID) -> Workspace | None:
return self.workspace if workspace_id == self.workspace.id else None
async def create_application(self, entity: Application) -> Application:
self.applications.append(entity)
return entity
async def get_application(self, application_id: UUID, workspace_id: UUID) -> Application | None:
return next(
(
item
for item in self.applications
if item.id == application_id and item.workspace_id == workspace_id
),
None,
)
async def list_applications(self, workspace_id: UUID) -> tuple[Application, ...]:
return tuple(item for item in self.applications if item.workspace_id == workspace_id)
async def create_service_account(self, entity: ServiceAccount) -> ServiceAccount:
self.service_accounts.append(entity)
return entity
async def get_service_account(
self, service_account_id: UUID, workspace_id: UUID
) -> ServiceAccount | None:
return next(
(
item
for item in self.service_accounts
if item.id == service_account_id and item.workspace_id == workspace_id
),
None,
)
async def get_service_account_by_id(self, service_account_id: UUID) -> ServiceAccount | None:
return next((item for item in self.service_accounts if item.id == service_account_id), None)
async def create_space(self, entity: KnowledgeSpace) -> KnowledgeSpace:
self.spaces.append(entity)
return entity
async def list_spaces(self, workspace_id: UUID) -> tuple[KnowledgeSpace, ...]:
return tuple(item for item in self.spaces if item.workspace_id == workspace_id)
async def create_grant(self, entity: Grant) -> Grant:
self.grants.append(entity)
return entity
async def create_user_grant(self, entity: UserGrant) -> UserGrant:
self.grants.append(entity)
return entity
async def create_policy(self, entity: Policy) -> Policy:
self.policies.append(entity)
return entity
async def list_policies(self, workspace_id: UUID) -> tuple[Policy, ...]:
return tuple(item for item in self.policies if item.workspace_id == workspace_id)
def _fixture():
workspace = Workspace(uuid4(), "Contract workspace", "contract-workspace")
principal = Principal(
uuid4(), workspace.id, PrincipalType.HUMAN, frozenset({Role.WORKSPACE_ADMIN})
)
repository = FakeControlRepository(workspace)
service = ControlPlaneApplication(repository, AuthorizationService())
credential_repository = InMemoryCredentialRepository()
credential_service = ServiceAccountCredentialService(
credential_repository,
"x" * 32,
repository.get_service_account_by_id,
)
app = create_app()
app.dependency_overrides[get_principal] = lambda: principal
app.dependency_overrides[get_control_application] = lambda: service
app.dependency_overrides[get_credential_service] = lambda: credential_service
return app, repository, principal
def test_openapi_and_runtime_expose_same_control_operations() -> None:
app, _, _ = _fixture()
document = yaml.safe_load(
(Path(__file__).parents[4] / "docs" / "contracts" / "openapi.yaml").read_text()
)
documented = {
path: set(operations)
for path, operations in document["paths"].items()
if path.startswith("/v1/") and "control" in str(document["paths"][path])
}
runtime = {
path: set(operations)
for path, operations in app.openapi()["paths"].items()
if path.startswith("/v1/") and "control" in str(operations)
}
assert set(runtime) == set(documented)
assert all(
{method.lower() for method in methods} == documented[path]
for path, methods in runtime.items()
)
def test_missing_authentication_is_problem_details() -> None:
app, _, _ = _fixture()
app.dependency_overrides.pop(get_principal)
response = TestClient(app).get("/v1/applications")
assert response.status_code == 401
assert response.headers["content-type"].startswith("application/problem+json")
assert response.json()["code"] == "AUTHENTICATION_REQUIRED"
def test_missing_idempotency_key_is_problem_details() -> None:
app, _, _ = _fixture()
response = TestClient(app).post(
"/v1/applications",
json={"slug": "missing-key", "display_name": "Missing key"},
)
assert response.status_code == 422
assert response.headers["content-type"].startswith("application/problem+json")
assert response.json()["code"] == "VALIDATION_ERROR"
def test_pagination_and_invalid_cursor_error_code() -> None:
app, repository, principal = _fixture()
client = TestClient(app)
headers = {"Idempotency-Key": "pagination-key-0001"}
for slug in ("first-app", "second-app"):
response = client.post(
"/v1/applications",
json={"slug": slug, "display_name": slug, "scopes": ["search"]},
headers=headers | {"Idempotency-Key": f"{slug}-idempotency"},
)
assert response.status_code == 201
first = client.get("/v1/applications?limit=1")
assert first.status_code == 200
assert len(first.json()["items"]) == 1
assert first.json()["next_cursor"] == "1"
second = client.get(f"/v1/applications?limit=1&cursor={first.json()['next_cursor']}")
assert second.status_code == 200
assert len(second.json()["items"]) == 1
invalid = client.get("/v1/applications?cursor=not-a-cursor")
assert invalid.status_code == 400
assert invalid.json()["code"] == "INVALID_CURSOR"
assert len(repository.applications) == 2
assert principal.workspace_id == repository.workspace.id
def test_idempotency_replay_and_conflict_do_not_duplicate() -> None:
app, repository, _ = _fixture()
client = TestClient(app)
headers = {"Idempotency-Key": "stable-create-key-01"}
payload = {"slug": "stable-app", "display_name": "Stable app", "scopes": ["search"]}
first = client.post("/v1/applications", json=payload, headers=headers)
replay = client.post("/v1/applications", json=payload, headers=headers)
conflict = client.post(
"/v1/applications",
json={"slug": "other-app", "display_name": "Other app"},
headers=headers,
)
assert first.status_code == 201
assert replay.status_code == 200
assert replay.json()["id"] == first.json()["id"]
assert conflict.status_code == 409
assert conflict.json()["code"] == "IDEMPOTENCY_KEY_REUSED"
assert len(repository.applications) == 1
def test_operation_policy_and_credentials_are_enforced() -> None:
app, repository, principal = _fixture()
client = TestClient(app)
create = client.post(
"/v1/applications",
json={"slug": "credential-app", "display_name": "Credential app", "scopes": ["search"]},
headers={"Idempotency-Key": "application-create-key"},
)
assert create.status_code == 201
application_id = create.json()["id"]
credential = client.post(
f"/v1/applications/{application_id}/credentials",
json={"name": "runtime", "scopes": ["search"]},
headers={"Idempotency-Key": "credential-create-key"},
)
assert credential.status_code == 201
assert credential.json()["token"].startswith("rc_sa_")
assert len(repository.service_accounts) == 1
replay = client.post(
f"/v1/applications/{application_id}/credentials",
json={"name": "runtime", "scopes": ["search"]},
headers={"Idempotency-Key": "credential-create-key"},
)
assert replay.status_code == 200
assert replay.json()["id"] == credential.json()["id"]
policy = client.post(
"/v1/policies",
json={"operation": "answer", "required_scopes": ["search"]},
headers={"Idempotency-Key": "policy-create-key"},
)
assert policy.status_code == 201
assert client.get("/v1/policies").status_code == 200
assert principal.roles == frozenset({Role.WORKSPACE_ADMIN})
def test_non_admin_cannot_manage_spaces() -> None:
app, _, principal = _fixture()
denied = Principal(
principal.id, principal.workspace_id, PrincipalType.HUMAN, frozenset({Role.VIEWER})
)
app.dependency_overrides[get_principal] = lambda: denied
response = TestClient(app).post(
"/v1/knowledge-spaces",
json={"slug": "private", "display_name": "Private", "data_policy": "local_only"},
headers={"Idempotency-Key": "space-create-key"},
)
assert response.status_code == 403
assert response.json()["code"] == "RESOURCE_NOT_FOUND"
def test_user_grant_is_workspace_authorized():
app, repository, principal = _fixture()
client = TestClient(app)
space = client.post(
"/v1/knowledge-spaces",
json={"slug": "user-space", "display_name": "User space", "data_policy": "local_only"},
headers={"Idempotency-Key": "user-space-create-key"},
)
assert space.status_code == 201
user_id = uuid4()
grant = client.post(
f"/v1/knowledge-spaces/{space.json()['id']}/grants",
json={"principal_type": "user", "principal_id": str(user_id), "permissions": ["read"]},
headers={"Idempotency-Key": "user-grant-create-key"},
)
assert grant.status_code == 201
assert grant.json()["principal_type"] == "user"
assert grant.json()["principal_id"] == str(user_id)
assert len(repository.grants) == 1
assert principal.workspace_id == repository.workspace.id