tenant-engine/tests/test_api_reads.py
tegwick 31e237cfa6 Fix: resolve tenants by identifier, not only internal tenant_id
Found via a real cross-service check while implementing key-cape's
KEY-WP-0005-T02: key-cape's Go adapter called GET /tenants/tenant:coulomb/roles
and got a genuine 404 for a tenant that existed. External callers
(key-cape, flex-auth) only ever have a tenant's profile identifier, never
tenant-engine's internal tenant_id (caller-chosen at creation, otherwise
opaque). Every existing test happened to use identical strings for both
fields, so this was invisible until a real, independent second caller
exercised the documented contract.

InMemoryTenantStore gained a _by_identifier index and a _resolve() helper
every method calls first; create_tenant now also rejects a duplicate
identifier under a different internal id (an oversight the same fix
surfaced). 5 new tests, including the exact HTTP-level scenario with colon
characters in the URL path. 65 total, all 60 pre-existing tests unaffected.

Re-verified end-to-end for real: fresh flex-auth + tenant-engine + key-cape's
actual adapter code, over real HTTP -- roles=[IAM] ok=true resolving by
identifier.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 00:15:26 +02:00

113 lines
3.6 KiB
Python

from datetime import UTC, datetime
from fastapi.testclient import TestClient
from tenant_engine.app import create_app
from tenant_engine.domain import CapabilityRole, Tenant, create_role_grant
from tenant_engine.store import InMemoryTenantStore, TenantStore
class _BrokenStore:
"""Test double: every active_roles() call raises, simulating an outage."""
def __init__(self, delegate: TenantStore) -> None:
self._delegate = delegate
def create_tenant(self, tenant):
return self._delegate.create_tenant(tenant)
def get_tenant(self, tenant_id):
return self._delegate.get_tenant(tenant_id)
def grant_role(self, grant):
return self._delegate.grant_role(grant)
def revoke_role(self, **kwargs):
return self._delegate.revoke_role(**kwargs)
def active_roles(self, tenant_id):
from tenant_engine.store import StoreUnavailableError
raise StoreUnavailableError("simulated outage")
def assign_plan(self, assignment):
return self._delegate.assign_plan(assignment)
def events(self):
return self._delegate.events()
def _seeded_store() -> InMemoryTenantStore:
store = InMemoryTenantStore()
tenant = Tenant.create(tenant_id="t-binky", identifier="tenant:friendly:binky")
store.create_tenant(tenant)
store.grant_role(
create_role_grant(
tenant=tenant,
grant_id="g-1",
role=CapabilityRole.CUS,
grant_reason="manual_grant",
plan_id=None,
granted_by="ops",
correlation_id="corr-1",
granted_at=datetime.now(UTC),
)
)
return store
def test_cache_read_roles_returns_active_roles() -> None:
client = TestClient(create_app(store=_seeded_store()))
response = client.get("/tenants/t-binky/roles")
assert response.status_code == 200
assert response.json() == {"tenant_id": "t-binky", "roles": ["CUS"]}
def test_cache_read_roles_resolves_by_identifier_not_only_internal_id() -> None:
"""The real scenario key-cape's KEY-WP-0005-T02 hits: it only knows the
tenant's profile identifier (the IAM Profile `tenant` claim value), via
a URL path segment containing colons -- never the internal tenant_id.
"""
client = TestClient(create_app(store=_seeded_store()))
response = client.get("/tenants/tenant:friendly:binky/roles")
assert response.status_code == 200
assert response.json() == {"tenant_id": "tenant:friendly:binky", "roles": ["CUS"]}
def test_cache_read_roles_unknown_tenant_is_404() -> None:
client = TestClient(create_app(store=_seeded_store()))
response = client.get("/tenants/does-not-exist/roles")
assert response.status_code == 404
def test_live_lookup_roles_returns_active_roles() -> None:
client = TestClient(create_app(store=_seeded_store()))
response = client.get("/tenants/t-binky/roles/live")
assert response.status_code == 200
assert response.json()["roles"] == ["CUS"]
def test_live_lookup_fails_closed_on_store_outage() -> None:
broken = _BrokenStore(_seeded_store())
client = TestClient(create_app(store=broken))
response = client.get("/tenants/t-binky/roles/live")
assert response.status_code == 503
assert response.json() != {"tenant_id": "t-binky", "roles": []}, (
"outage must not be indistinguishable from a legitimate empty role list"
)
def test_cache_read_also_fails_closed_on_store_outage() -> None:
broken = _BrokenStore(_seeded_store())
client = TestClient(create_app(store=broken))
response = client.get("/tenants/t-binky/roles")
assert response.status_code == 503