Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions api/src/database/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from typing import Protocol
from src.utils import urls
from sqlalchemy import event
from sqlalchemy.orm import Session as SyncSession
from collections.abc import AsyncGenerator
from src.environments import env
from longlink.database import audit
Expand Down Expand Up @@ -92,4 +91,4 @@ async def session_dependency() -> AsyncGenerator[AsyncSession, None]:


# Register shared audit listeners after the Platform audit models are available.
audit.install_listener(SyncSession, AuditTable)
audit.install_listener(AuditTable)
22 changes: 13 additions & 9 deletions sdk/longlink/cli/dev.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,17 @@ def dev_command(

# Keep the selected socket bound while Uvicorn supervises reloads.
with _bind_socket(host, port) as server_socket:
sys.path.insert(0, str(Path.cwd()))
config = uvicorn.Config("main:app", host=host, port=server_socket.getsockname()[1], reload=True, reload_includes=["*.jsx"])
server = uvicorn.Server(config=config)
supervisor = ChangeReload(config, target=server.run, sockets=[server_socket])
address = f"[{host}]" if ":" in host else host
logger.info("Development server running on http://%s:%s", address, config.port)
original_path = sys.path.copy()
try:
supervisor.run()
except KeyboardInterrupt:
pass
sys.path.insert(0, str(Path.cwd()))
config = uvicorn.Config("main:app", host=host, port=server_socket.getsockname()[1], reload=True, reload_includes=["*.jsx"])
server = uvicorn.Server(config=config)
supervisor = ChangeReload(config, target=server.run, sockets=[server_socket])
address = f"[{host}]" if ":" in host else host
logger.info("Development server running on http://%s:%s", address, config.port)
try:
supervisor.run()
except KeyboardInterrupt:
pass
finally:
sys.path[:] = original_path
4 changes: 2 additions & 2 deletions sdk/longlink/database/audit.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,10 @@ def actor(user_id: UUID | None) -> Generator[None]:
current_actor.reset(token)


def install_listener(session_type: type[SyncSession], audit_type: type[object]) -> None:
def install_listener(audit_type: type[object]) -> None:
"""Register audit attribution for one application's ORM session and model bases."""

@event.listens_for(session_type, "before_flush")
@event.listens_for(SyncSession, "before_flush")
def apply_audit_fields(session: SyncSession, _flush_context: object, _instances: object) -> None:
"""Apply request-scoped audit fields before ORM flushes changes."""

Expand Down
8 changes: 4 additions & 4 deletions sdk/longlink/database/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from uuid import UUID
from datetime import UTC, datetime
from sqlmodel import Field, SQLModel
from sqlmodel import Session as SyncSession
from contextlib import asynccontextmanager
from sqlalchemy.orm import relationship, declared_attr
from collections.abc import AsyncGenerator
Expand Down Expand Up @@ -156,13 +155,14 @@ async def sync_user(self, user: User) -> None:
# Upserts serialize concurrent first requests and ignore equal or older profile snapshots.
engine = await self._get_engine()
users = SQLModel.metadata.tables["users"]
profile = user.model_dump()
statement = postgresql.insert(users) if engine.dialect.name == "postgresql" else sqlite.insert(users)
statement = statement.values(user.model_dump())
statement = statement.values(profile)
async with engine.begin() as connection:
await connection.execute(
statement.on_conflict_do_update(
index_elements=[users.c.id],
set_={name: statement.excluded[name] for name in ("name", "email", "avatar", "updated_at")},
set_={name: statement.excluded[name] for name in profile if name != "id"},
# Older assertions must not overwrite a newer local profile.
where=users.c.updated_at < statement.excluded.updated_at,
)
Expand All @@ -172,4 +172,4 @@ async def sync_user(self, user: User) -> None:
# Register audit listeners after Audit is fully defined.
from longlink.database import audit

audit.install_listener(SyncSession, Audit)
audit.install_listener(Audit)
2 changes: 0 additions & 2 deletions sdk/longlink/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,6 @@ def discover(routes: Sequence[RouteContext]) -> Catalog:
for route in routes:
declared = (route.openapi_extra or {}).get("x-longlink-roles")
for method in sorted(route.methods or set()):
if method not in METHODS:
raise ValueError(f"Unsupported permission method: {method}")
defaults = ["read", "write"] if method in READ_ONLY_METHODS else ["write"]
endpoint = Endpoint.model_validate(
{"path": route.path, "method": method, "roles": declared if declared is not None else defaults}
Expand Down
8 changes: 1 addition & 7 deletions sdk/tests/cli/test_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -368,13 +368,7 @@ def test_read_env_spec_rejects_malformed_child_response(build_project: Path, mon
"""Reject corrupted subprocess responses rather than using them as image labels."""

# Arrange
def run_child(command: list[str], *, check: bool) -> subprocess.CompletedProcess[bytes]:
"""Emulate an inspector that exits successfully but returns malformed metadata."""

Path(command[-1]).write_bytes(response)
return subprocess.CompletedProcess(command, 0)

monkeypatch.setattr(build.subprocess, "run", run_child)
monkeypatch.setattr(build, "_inspect", lambda *_args: response)
config = build.read_pyproject(build_project)

# Act and assert
Expand Down
8 changes: 4 additions & 4 deletions sdk/tests/cli/test_dev.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import sys
import errno
import pytest
import shutil
Expand All @@ -20,11 +21,12 @@ def test_dev_command_reserves_ephemeral_port_until_reload_supervisor_exits(
# Arrange
sockets: list[socket.socket] = []
monkeypatch.chdir(tmp_path)
monkeypatch.syspath_prepend(str(tmp_path))
original_path = sys.path.copy()

def run(supervisor: basereload.BaseReload) -> None:
"""Attempt a competing bind while the real reload supervisor owns the socket."""

assert sys.path[0] == str(tmp_path)
selected = supervisor.sockets[0]
sockets.append(selected)
assert selected.getsockname()[1] > 0
Expand All @@ -41,6 +43,7 @@ def run(supervisor: basereload.BaseReload) -> None:
main(["dev", "--port", "0"])

# Assert
assert sys.path == original_path
assert len(sockets) == 1
assert sockets[0].fileno() == -1

Expand Down Expand Up @@ -89,7 +92,6 @@ def test_dev_command_warns_only_for_public_hosts(

# Arrange
monkeypatch.chdir(tmp_path)
monkeypatch.syspath_prepend(str(tmp_path))
monkeypatch.setenv("LONGLINK_ENV", "development")

def run(supervisor: basereload.BaseReload) -> None:
Expand Down Expand Up @@ -117,7 +119,6 @@ def test_dev_command_applies_migrations_and_refreshes_declarations_before_servin

# Arrange
monkeypatch.chdir(tmp_path)
monkeypatch.syspath_prepend(str(tmp_path))
monkeypatch.setenv("LONGLINK_ENV", "development")
migrations_path = tmp_path / "migrations"
migrations_path.mkdir()
Expand Down Expand Up @@ -186,7 +187,6 @@ def test_dev_command_skips_consecutive_occupied_ports(

# Arrange
monkeypatch.chdir(tmp_path)
monkeypatch.syspath_prepend(str(tmp_path))
if family == socket.AF_INET6 and not socket.has_ipv6:
pytest.skip("IPv6 is unavailable")
for _attempt in range(100):
Expand Down
10 changes: 1 addition & 9 deletions sdk/tests/database/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,16 +364,14 @@ def test_company_collector_preserves_logos_within_byte_capacity(company_model: t

# Act
company = company_model.model_validate(profile)
validated = company_model.validate_logo(image)

# Assert
assert company.logo is image
assert validated is image
assert company.logo_url == ("/api/v1/companies/company/logo" if image is not None else None)


def test_company_collector_rejects_logo_byte_overflow(company_model: type[Company]) -> None:
"""Reject oversized images through model and direct boundary validation."""
"""Reject oversized images at the model boundary."""

# Arrange
image = b"RIFF" + (65536 - 8).to_bytes(4, "little") + b"WEBP" + bytes(65536 - 12)
Expand All @@ -382,8 +380,6 @@ def test_company_collector_rejects_logo_byte_overflow(company_model: type[Compan
# Act and assert
with pytest.raises(ValidationError, match="Logo must contain at most 65535 bytes of image data"):
company_model.model_validate(profile)
with pytest.raises(ValueError, match="Logo must contain at most 65535 bytes of image data"):
company_model.validate_logo(image)


@pytest.mark.parametrize(
Expand All @@ -408,8 +404,6 @@ def test_company_collector_rejects_non_webp_images(company_model: type[Company],
# Act and assert
with pytest.raises(ValidationError, match="WebP"):
company_model.model_validate(profile)
with pytest.raises(ValueError, match="WebP"):
company_model.validate_logo(image)


@pytest.mark.parametrize(
Expand All @@ -430,8 +424,6 @@ def test_company_rejects_logo_type_coercion(company_model: type[Company], image:
# Act and assert
with pytest.raises(ValidationError):
company_model.model_validate(profile)
with pytest.raises(ValueError, match="Logo"):
company_model.validate_logo(image)


@pytest.mark.parametrize(
Expand Down
34 changes: 15 additions & 19 deletions sdk/tests/middleware/test_identity.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,7 @@ def identity_headers(user_id: UUID) -> dict[str, str]:

@pytest.mark.parametrize(
("secret", "identity_header", "actor_id"),
[
(IDENTITY_SECRET, "invalid-token", str(LOCAL_USER_ID)),
("", None, str(LOCAL_USER_ID)),
(IDENTITY_SECRET, identity.create_identity_token(None, IDENTITY_SECRET, permissions.Access(catalog="a" * 64, endpoints=[])), None),
],
[(IDENTITY_SECRET, "invalid-token", str(LOCAL_USER_ID)), ("", None, str(LOCAL_USER_ID)), (IDENTITY_SECRET, "guest", None)],
)
def test_context_middleware_distinguishes_signed_guests_from_untrusted_identity(
secret: str, identity_header: str | None, actor_id: str | None
Expand All @@ -88,10 +84,14 @@ async def get_identity() -> dict[str, str | None]:

client = TestClient(app)

# Act
# Arrange
if identity_header == "guest":
identity_header = identity.create_identity_token(None, IDENTITY_SECRET, permissions.Access(catalog="a" * 64, endpoints=[]))
headers = {} if identity_header is None else {"x-longlink-identity": identity_header}
if not secret:
headers = identity_headers(UUID("00000000-0000-0000-0000-000000000001"))

# Act
with client:
response = client.get("/", headers=headers)

Expand Down Expand Up @@ -143,28 +143,24 @@ async def events(socket: WebSocket) -> None:
HTTP_IDENTITY_CASES = [
pytest.param({}, None, 401, {"detail": "Authentication required"}, id="missing"),
pytest.param({"x-longlink-identity": "invalid-token"}, None, 401, {"detail": "Authentication required"}, id="malformed"),
pytest.param({}, "wrong-identity-secret-01234567890", 401, {"detail": "Authentication required"}, id="wrong-key"),
pytest.param({}, IDENTITY_SECRET, 200, {"authenticated": True}, id="valid"),
pytest.param(
{"x-longlink-identity": identity.create_identity_token(None, IDENTITY_SECRET, permissions.Access(catalog="a" * 64, endpoints=[]))},
None,
200,
{"authenticated": False},
id="guest",
),
pytest.param({}, "wrong-key", 401, {"detail": "Authentication required"}, id="wrong-key"),
pytest.param({}, "user", 200, {"authenticated": True}, id="valid"),
pytest.param({}, "guest", 200, {"authenticated": False}, id="guest"),
]


@pytest.mark.parametrize(("headers", "signing_secret", "status", "payload"), HTTP_IDENTITY_CASES)
@pytest.mark.parametrize(("headers", "identity_case", "status", "payload"), HTTP_IDENTITY_CASES)
def test_production_context_requires_signed_http_identity(
production_client: TestClient, headers: dict[str, str], signing_secret: str | None, status: int, payload: dict[str, str | bool]
production_client: TestClient, headers: dict[str, str], identity_case: str | None, status: int, payload: dict[str, str | bool]
) -> None:
"""Admit protected HTTP requests only with a valid Platform assertion."""

# Arrange
if signing_secret is not None:
if identity_case is not None:
signing_secret = "wrong-identity-secret-01234567890" if identity_case == "wrong-key" else IDENTITY_SECRET
user = None if identity_case == "guest" else User(id=UUID(int=1), name="Test User", email="test@example.com")
access = permissions.Access(catalog="a" * 64, endpoints=[])
token = identity.create_identity_token(User(id=UUID(int=1), name="Test User", email="test@example.com"), signing_secret, access)
token = identity.create_identity_token(user, signing_secret, access)
headers = {"x-longlink-identity": token}

# Act
Expand Down
18 changes: 18 additions & 0 deletions sdk/tests/test_permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,24 @@
from longlink.app import LongLink


@pytest.mark.usefixtures("solution_source")
def test_discovery_rejects_unsupported_route_methods() -> None:
"""Reject routes that cannot be represented by the permission contract."""

# Arrange
app = LongLink()

@app.api_route("/items", methods=["TRACE"], response_model=int)
async def endpoint() -> int:
"""Return a business response."""

return 1

# Act and assert
with pytest.raises(ValueError, match="TRACE"):
permissions.discover(app.permission_routes())


@pytest.mark.usefixtures("solution_source")
@pytest.mark.parametrize("declaration", ["decorator", "openapi"])
@pytest.mark.parametrize(
Expand Down