Skip to content
Open
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
36 changes: 26 additions & 10 deletions src/powercontext/server/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2805,7 +2805,9 @@ async def on_commit(connection, publication):
target.scope_id, family=target.artifact.family, artifact_id=target.artifact.artifact_id
),
principal,
idempotency_key=f"artifact-publication-owner:{target.artifact.artifact_id}",
idempotency_key=bounded_idempotency_key(
f"{target.artifact.family}-owner", target.scope_id, target.artifact.artifact_id
),
context=context,
)
owner_committed = True
Expand All @@ -2823,16 +2825,30 @@ async def on_commit(connection, publication):
)
await flush_owner_writes()
if access is None and result.target.artifact.family != "topic-memory":
await _establish_created_owner(
http_request,
ResourceRef.artifact(
result.target.scope_id,
family=result.target.artifact.family,
artifact_id=result.target.artifact.artifact_id,
),
idempotency_key=f"artifact-publication-owner:{result.target.artifact.artifact_id}",
operation=PUBLISH_ARTIFACT.operation_id,
target = result.target
resource = ResourceRef.artifact(
target.scope_id,
family=target.artifact.family,
artifact_id=target.artifact.artifact_id,
)
try:
await _establish_created_owner(
http_request,
resource,
idempotency_key=bounded_idempotency_key(
f"{target.artifact.family}-owner", target.scope_id, target.artifact.artifact_id
),
operation=PUBLISH_ARTIFACT.operation_id,
)
except AccessConflictError:
# Pre-upgrade publications recorded the same owner under artifact-publication-owner:<id>.
post_commit_access = access_control_for_mode(
http_request.app.state.access_control,
mode=http_request.app.state.access_mode,
)
existing = None if post_commit_access is None else await post_commit_access.artifact_owner(resource)
if existing is None or existing.owner != _require_principal():
raise
elif access is not None and not owner_committed and result.target.artifact.family != "topic-memory":
target = result.target
resource = ResourceRef.artifact(
Expand Down
10 changes: 9 additions & 1 deletion tests/e2e/test_access_control_regressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
BuiltinAuthorizationProvider,
PrincipalRef,
ResourceRef,
bounded_idempotency_key,
)
from powercontext.builtin.authz.composition import open_builtin_access_control, open_casbin_access_control
from powercontext.builtin.persistence.sqlite import SQLiteConfig
Expand Down Expand Up @@ -686,7 +687,7 @@ def test_hints_share_continue_manifest_authority_and_resolve_published_evidence_
tmp_path, backend
):
async def scenario():
async with _server(tmp_path, backend) as (_, client, _):
async with _server(tmp_path, backend) as (_, client, access):
scope_id = await _scope(client)
revision = await _handoff(client, scope_id)
await _grant(client, scope_id, "bob", "handoff.viewer", _resource(scope_id, "handoff", "handoff"))
Expand Down Expand Up @@ -727,6 +728,13 @@ async def scenario():
)
assert publication.status_code == 201, publication.text
published_revision = publication.json()["target"]["artifact"]
published_owner = await access.artifact_owner(
ResourceRef.artifact(target_id, family="handoff", artifact_id=published_revision["artifact_id"])
)
assert published_owner is not None
assert published_owner.idempotency_key == bounded_idempotency_key(
"handoff-owner", target_id, published_revision["artifact_id"]
)
published_access = await _grant(
client,
target_id,
Expand Down
168 changes: 168 additions & 0 deletions tests/e2e/test_access_ownership_migration.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import httpx
import pytest
from pydantic import SecretStr
from starlette.middleware import Middleware
from typer.testing import CliRunner

from powercontext.builtin.authz import (
Expand All @@ -44,14 +45,17 @@
BindingSearchRequest,
PrincipalRef,
ResourceRef,
bounded_idempotency_key,
)
from powercontext.builtin.authz.composition import open_builtin_access_control
from powercontext.builtin.persistence.sqlite import SQLiteConfig
from powercontext.builtin.runtime import RuntimeConfig
from powercontext.builtin.scope import ScopeApplication, ScopeDraft
from powercontext.cli.app import create_cli
from powercontext.server.app import create_app
from powercontext.server.authentication import AuthenticationResult, ProviderReadiness
from powercontext.server.factory import create_server_app
from powercontext.server.middleware import AuthenticationMiddleware
from powercontext.server.ownership import ArtifactOwnershipGap, apply_ownership_migration
from powercontext.server.settings import AccessControlConfig, BearerAuthConfig, McpConfig, MetricsConfig, ServerSettings

Expand Down Expand Up @@ -1185,6 +1189,170 @@ async def fail_first_approval_owner(resource, owner, *, idempotency_key, context
asyncio.run(scenario())


class _PostCommitApplication:
"""Delegate to BuiltinRuntime without joining its transaction for owner writes."""

def __init__(self, runtime: Any) -> None:
self._runtime = runtime

def __getattr__(self, name: str) -> Any:
return getattr(self._runtime, name)


@pytest.mark.parametrize(("migration_owner", "retry_status"), [(AGENT, 201), (ADMIN, 409)])
def test_publication_retry_after_migration_accepts_only_the_publisher(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, migration_owner: PrincipalRef, retry_status: int
) -> None:
async def scenario() -> None:
database = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'publication-retry.db'}")
bootstrap = create_server_app(settings=_settings(database, "disabled"))
async with bootstrap.router.lifespan_context(bootstrap):
pass
async with open_builtin_access_control(
database, bootstrap_administrators=(ADMIN,), deployment_id=DEPLOYMENT
) as access:
auth = _Authentication()
backing = create_server_app(
settings=_settings(database, "enforced"),
authentication_provider=auth,
access_control=access,
)
async with backing.router.lifespan_context(backing):
app = create_app(
application=_PostCommitApplication(backing.state.application),
access_control=access,
access_mode="enforced",
authentication_provider=auth,
middleware=(Middleware(AuthenticationMiddleware, provider=auth),),
)
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://test",
) as client:
source_scope = checked(
await client.post(
"/v1/scopes",
json={"title": "Source", "summary": "Source", "idempotency_key": "pub-source"},
),
201,
)["scope_id"]
target_scope = checked(
await client.post(
"/v1/scopes",
json={"title": "Target", "summary": "Target", "idempotency_key": "pub-target"},
),
201,
)["scope_id"]
for scope_id, role, key in (
(source_scope, "scope.admin", "agent-source-admin"),
(source_scope, "scope.contributor", "agent-source-contributor"),
(target_scope, "scope.admin", "agent-target-admin"),
):
checked(
await client.post(
"/v1/access/bindings/create",
json={
"subject": {"type": AGENT.type, "id": AGENT.id},
"resource": {"type": "scope", "scope_id": scope_id},
"role": role,
"idempotency_key": key,
},
),
201,
)
agent = {"Authorization": f"Bearer {AGENT.id}"}
checked(
await client.post(
"/v1/sources/content",
headers=agent,
json={"scope_id": source_scope, "source_id": "evidence", "content": "Verified."},
),
202,
)
original = checked(
await client.post(
f"/v1/scopes/{source_scope}/artifacts",
headers=agent,
json={
"family": "handoff",
"content": {
"schema": "powercontext.handoff.v1",
"objective": "Completed task.",
"state": [
{
"text": "Verified task state.",
"citations": [
{
"kind": "source",
"source_ref": {"name": "content", "source_id": "evidence"},
}
],
}
],
"disposition": "complete",
"next_action": None,
"omissions": [],
},
},
),
201,
)
original_establish = access.establish_artifact_owner
failed: list[ResourceRef] = []

async def fail_first_publication_owner(resource, owner, *, idempotency_key, context):
if resource.scope_id == target_scope and not failed:
failed.append(resource)
raise AccessUnavailableError("owner_store_unavailable")
return await original_establish(
resource, owner, idempotency_key=idempotency_key, context=context
)

monkeypatch.setattr(access, "establish_artifact_owner", fail_first_publication_owner)
publish = {
"source": {
"scope_id": source_scope,
"artifact": {
"family": "handoff",
"artifact_id": "handoff",
"revision": original["revision"],
},
},
"target_scope_id": target_scope,
"idempotency_key": "publish-handoff-1",
}
checked(await client.post("/v1/artifact-publications", headers=agent, json=publish), 503)
[resource] = failed
assert resource.artifact_id is not None
artifact_id = resource.artifact_id
applied = checked(
await client.post(
"/v1/access/ownership/apply",
json={
"scope_ids": [target_scope],
"owner": {"type": migration_owner.type, "id": migration_owner.id},
},
),
200,
)
assert [item["artifact_id"] for item in applied["applied"]] == [artifact_id]

retry = await client.post("/v1/artifact-publications", headers=agent, json=publish)
assert retry.status_code == retry_status, retry.json()
if retry_status == 201:
assert retry.json()["target"]["artifact"]["artifact_id"] == artifact_id
else:
assert retry.json()["error"]["code"] == "artifact-owner"
relation = await access.artifact_owner(resource)
assert relation is not None
assert relation.owner == migration_owner
assert relation.idempotency_key == bounded_idempotency_key(
"handoff-owner", target_scope, artifact_id
)

asyncio.run(scenario())


def test_apply_reports_conflicting_ownership_without_failing(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
async def scenario() -> None:
database = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'conflict.db'}")
Expand Down
17 changes: 14 additions & 3 deletions tests/e2e/test_owner_recovery_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,13 @@
import pytest
from typer.testing import CliRunner

from powercontext.builtin.authz import AccessUnavailableError, PrincipalRef, RelationshipStore, ResourceRef
from powercontext.builtin.authz import (
AccessUnavailableError,
PrincipalRef,
RelationshipStore,
ResourceRef,
bounded_idempotency_key,
)
from powercontext.builtin.authz.composition import open_builtin_access_control
from powercontext.builtin.persistence.sqlite import SQLiteConfig
from powercontext.builtin.records import ArtifactWrite
Expand Down Expand Up @@ -501,8 +507,13 @@ async def unavailable(_event):
pending = await app.state.owner_recovery.pending()
assert len(pending) == 1
resource = pending[0].resource
assert resource is not None
assert (await access.artifact_owner(resource)).owner == ALICE
assert resource is not None and resource.artifact_id is not None
stored_owner = await access.artifact_owner(resource)
assert stored_owner is not None
assert stored_owner.owner == ALICE
assert stored_owner.idempotency_key == bounded_idempotency_key(
"handoff-owner", destination, resource.artifact_id
)
retried = await client.post(
path, json=payload, headers={"X-PowerContext-Request-ID": "retry-owner-request"}
)
Expand Down
Loading
Loading