From 2aaf28eca8a7c5e72fefba628252ac1a51b91f3f Mon Sep 17 00:00:00 2001 From: busya Date: Sun, 11 Oct 2026 21:12:14 +0300 Subject: [PATCH] fix(publication): refuse source repository before intent --- .../dashboard_testing/catalog_publications.py | 11 +- .../execution/publication_source_guard.py | 98 ++++++++++ .../execution/publication_worker.py | 108 +++++------ backend/src/services/mcp_publish_dispatch.py | 4 +- .../api/test_catalog_publications_api.py | 36 +++- backend/tests/scripts/test_publish_catalog.py | 8 +- .../test_publication_failure_state.py | 10 +- .../test_publication_git_repository.py | 7 +- .../test_publication_remote_observation.py | 3 +- .../test_publication_source_guard.py | 179 ++++++++++++++++++ .../test_publication_transaction_recovery.py | 7 +- .../execution/test_publication_worker.py | 35 +++- .../test_catalog_write_transfer.py | 39 +++- .../test_native_result_lifecycle.py | 6 +- ...-10-10-chart-type-stabilization-journal.md | 8 + .../2026-10-10-chart-type-stabilization.md | 2 +- 16 files changed, 477 insertions(+), 84 deletions(-) create mode 100644 backend/src/services/dashboard_testing/execution/publication_source_guard.py create mode 100644 backend/tests/services/dashboard_testing/execution/test_publication_source_guard.py diff --git a/backend/src/api/routes/dashboard_testing/catalog_publications.py b/backend/src/api/routes/dashboard_testing/catalog_publications.py index ef27b7b3c..6ed9cc21b 100644 --- a/backend/src/api/routes/dashboard_testing/catalog_publications.py +++ b/backend/src/api/routes/dashboard_testing/catalog_publications.py @@ -6,8 +6,8 @@ # the curated MCP tool (MCPX-FR-030 parity); an authenticated-but-unauthorized principal # is denied before any worker call. # @INVARIANT The repository and branch are server-resolved from the deployment publish-source config; -# the caller supplies only the envelope, the reviewed expected branch head and the -# idempotency key. Every failure is typed and leaves a durable `publish_failed` row. +# the caller supplies only the exact revision, the reviewed expected branch head and the +# idempotency key. Admission refuses before intent; attempt failures retain `publish_failed` rows. # @RATIONALE MCPX-FR-030 parity: the curated MCP publish tool and this REST surface share one worker # service, one permission class and one idempotency/CAS contract. # @REJECTED Letting the caller choose the repository or branch was rejected — the deployment @@ -22,6 +22,7 @@ from pydantic import BaseModel, ConfigDict, Field from sqlalchemy.orm import Session from src.dependencies import get_current_user, get_db, has_permission +from src.core.source_repository_identity import FORBIDDEN, SourceRepositoryRefusal from src.models.dashboard_release import DashboardRelease from src.models.publication_operation import PublicationOperation from src.models.scenario_registry import ScenarioActivationStatus, ScenarioRegistryEntry, ScenarioRevision @@ -108,6 +109,9 @@ def publish_visual_candidate( expected_branch_head=request.expected_branch_head, idempotency_key=request.idempotency_key, ) + except SourceRepositoryRefusal as exc: + db.rollback() + raise HTTPException(status_code=409 if exc.code == FORBIDDEN else 503, detail={"code": exc.code}) from None except (ValueError, PublicationError) as exc: db.rollback() code = exc.code if isinstance(exc, PublicationError) else str(exc) @@ -155,6 +159,9 @@ def create_catalog_publication(request: CatalogPublicationRequest, db: Session = try: return publish_baseline_catalog(db, selector=request.catalog_selection, expected_branch_head=request.expected_branch_head, idempotency_key=idempotency_key, actor=str(user.id)) + except SourceRepositoryRefusal as exc: + db.rollback() + raise HTTPException(status_code=409 if exc.code == FORBIDDEN else 503, detail={"code": exc.code}) from None except (PublicationError, ValueError) as exc: db.rollback() code = exc.code if isinstance(exc, PublicationError) else str(exc) diff --git a/backend/src/services/dashboard_testing/execution/publication_source_guard.py b/backend/src/services/dashboard_testing/execution/publication_source_guard.py new file mode 100644 index 000000000..83e91d86f --- /dev/null +++ b/backend/src/services/dashboard_testing/execution/publication_source_guard.py @@ -0,0 +1,98 @@ +# #region ScenarioExecution.PublicationSourceGuard [C:4] [TYPE Module] [SEMANTICS publication,source,repository,admission] +# @BRIEF Refuse publishing into the immutable source repository before durable intent or external Git writes. +# @PRE One deployment-owned source identity and an authenticated exact repository metadata read are available. +# @POST Any exact official source identity match refuses; same-path unproved aliases remain unavailable. +# @RATIONALE Official repository URLs resolve configured internal/public aliases without guessing host equivalence. +# @REJECTED Destination-only trust, runtime Git, guessed origins and hostname-only differences cannot authorize writes. +import httpx + +from src.core.logger import logger +from src.core.source_repository_identity import ( + FORBIDDEN, SourceRepositoryRefusal, load_source_identity, normalize_repository_url, +) + +_SRC = "ScenarioExecution.PublicationSourceGuard" + + +# #region ScenarioExecution.PublicationSourceGuard.Refusal [C:2] [TYPE Class] +class RepositoryObservationUnavailable(SourceRepositoryRefusal): + def __init__(self, reason, *, status=None, error_class=None): + super().__init__() + self.facts = {"observation_stage": "repository_metadata", "observation_reason": reason} + if status is not None: + self.facts["http_status"] = status + if error_class is not None: + self.facts["http_error_class"] = error_class +# #endregion ScenarioExecution.PublicationSourceGuard.Refusal + + +# #region ScenarioExecution.PublicationSourceGuard.TransportClass [C:2] [TYPE Function] +def transport_error_class(failure): + for kind, name in ((httpx.TimeoutException, "timeout"), (httpx.ConnectError, "connect_error"), + (httpx.ProtocolError, "protocol_error")): + if isinstance(failure, kind): + return name + return "http_error" +# #endregion ScenarioExecution.PublicationSourceGuard.TransportClass + + +# #region ScenarioExecution.PublicationSourceGuard.Observation [C:3] [TYPE Function] +def observe_repository(client, repository): + try: + response = client.get(f"/api/v1/repos/{repository}") + except httpx.HTTPError as failure: + raise RepositoryObservationUnavailable("transport_error", error_class=transport_error_class(failure)) from None + if response.status_code != 200: + raise RepositoryObservationUnavailable("http_status", status=response.status_code) + try: + value = response.json() + except ValueError: + raise RepositoryObservationUnavailable("invalid_json", status=200) from None + if (not isinstance(value, dict) or type(value.get("id")) is not int or value["id"] <= 0 + or not isinstance(value.get("full_name"), str)): + raise RepositoryObservationUnavailable("metadata_shape", status=200) + if value["full_name"].casefold() != repository.casefold(): + raise RepositoryObservationUnavailable("full_name_conflict", status=200) + try: + identities = [normalize_repository_url(value.get(field)) for field in ("clone_url", "html_url", "ssh_url")] + except SourceRepositoryRefusal: + raise RepositoryObservationUnavailable("url_identity_invalid", status=200) from None + if any(identity.repository.casefold() != value["full_name"].casefold() for identity in identities): + raise RepositoryObservationUnavailable("url_identity_conflict", status=200) + return value["id"], identities +# #endregion ScenarioExecution.PublicationSourceGuard.Observation + + +# #region ScenarioExecution.PublicationSourceGuard.Require [C:4] [TYPE Function] +# @INVARIANT Read-only admission precedes the durable operation; it cannot perform Git writes or create a DB intent. +def require_publication_destination(client, repository): + logger.reason("Check publication destination against immutable source identity", src=_SRC, + claim="Publication: destination differs from observed source") + facts = {"match_class": "source_identity_unavailable", "observation_stage": "source_metadata"} + try: + source = load_source_identity() + facts = {"source_commit": source.source_commit, "source_host": source.origin.host, + "source_port": source.origin.port, "source_repository": source.origin.repository, + "match_class": "target_identity_unavailable", "observation_stage": "repository_metadata"} + repository_id, identities = observe_repository(client, repository) + facts.update(repository_id=repository_id, target_repository=identities[0].repository, + target_identities=[{"host": identity.host, "port": identity.port, + "repository": identity.repository} for identity in identities]) + if any(identity.host == source.origin.host and identity.port == source.origin.port + and identity.repository.casefold() == source.origin.repository.casefold() for identity in identities): + facts["match_class"] = "source_repository_match" + raise SourceRepositoryRefusal(FORBIDDEN) + if any(identity.repository.casefold() == source.origin.repository.casefold() for identity in identities): + facts["match_class"] = "same_path_unresolved_host" + raise SourceRepositoryRefusal() + except SourceRepositoryRefusal as failure: + if isinstance(failure, RepositoryObservationUnavailable): + facts.update(failure.facts) + logger.explore("Publication destination admission refused", src=_SRC, + claim="Publication: source identity must be distinct", error_code=failure.code, payload=facts) + raise + facts["match_class"] = "disjoint_repository_path" + logger.reflect("Publication destination is distinct from immutable source repository", src=_SRC, + claim="Publication: exact repository admission observed", payload=facts) +# #endregion ScenarioExecution.PublicationSourceGuard.Require +# #endregion ScenarioExecution.PublicationSourceGuard diff --git a/backend/src/services/dashboard_testing/execution/publication_worker.py b/backend/src/services/dashboard_testing/execution/publication_worker.py index 5766dc84a..c99c8dcb6 100644 --- a/backend/src/services/dashboard_testing/execution/publication_worker.py +++ b/backend/src/services/dashboard_testing/execution/publication_worker.py @@ -3,7 +3,7 @@ # @RELATION CALLS -> [BaselineEngine.CatalogStore.Render] # @RELATION CALLS -> [BaselineEngine.NativeRevisionPublication.Validate] # @INVARIANT Git bytes establish publication digest only; runtime content always comes from the retained DB revision. -# @INVARIANT Durable intent precedes external Git I/O; DB finalization records status and receipt atomically. +# @INVARIANT Durable intent precedes external Git writes; read-only destination admission precedes intent; DB finalization records status and receipt atomically. # @RATIONALE A crash after the Git commit reconciles only the same operation marker and exact DB render. # @REJECTED Operation content envelopes, local file inputs and foreign identical-content commits cannot provide authority. import base64 @@ -27,6 +27,7 @@ from src.services.dashboard_testing.native_revision_publication import require_p from src.services.dashboard_testing.materialization import require_snapshot_release from .publication_config import publication_connection from .publication_errors import PublicationError +from .publication_source_guard import require_publication_destination _SRC = "ScenarioExecution.PublicationWorker" _HEAD = re.compile(r"(?:[a-f0-9]{40}|[a-f0-9]{64})\Z") @@ -199,48 +200,46 @@ def _finalize(db, operation, snapshot, head): # #region ScenarioExecution.PublicationWorker.Attempt [C:5] [TYPE Function] -def _attempt(db, operation, snapshot, connection, target, rendered, transport): +def _attempt(db, operation, snapshot, connection, target, rendered, client): operation.attempts += 1 operation.state = "publish_pending" operation.error_code = None operation.updated_at = datetime.now(UTC) _commit(db, operation.id) - headers = {"Authorization": f"token {connection.token.get_secret_value()}"} - with httpx.Client(base_url=connection.base_url, headers=headers, timeout=30, transport=transport) as client: + head = _branch_head(client, connection.repository, connection.branch) + if head is None: + _refuse("PUBLISH_UNAVAILABLE", operation_id=operation.id, observation="branch_head_absent") + if operation.commit_sha is not None: + if head != operation.commit_sha: + _refuse("PUBLISH_HEAD_MOVED", operation_id=operation.id, required_head=operation.commit_sha, observed_head=head) + elif head != operation.expected_branch_head: + if operation.attempts <= 1: + _refuse("PUBLISH_HEAD_MOVED", operation_id=operation.id, required_head=operation.expected_branch_head, observed_head=head) + retained_commit = _observe_own_commit(client, connection.repository, head, operation) + if not retained_commit.matches: + _refuse("PUBLISH_HEAD_MOVED", operation_id=operation.id, operation="reconcile_commit", + required_head=operation.expected_branch_head, observed_head=head, + observed_parent_sha=retained_commit.observed_parent_sha, commit_reason=retained_commit.reason) + else: + result = publish_catalog_bytes(client, target, rendered.content, + f"Publish catalog revision {operation.catalog_revision_id} {_operation_marker(operation)}") + commit = result.get("commit") if isinstance(result, dict) else None + written = commit.get("sha") if isinstance(commit, dict) else None head = _branch_head(client, connection.repository, connection.branch) - if head is None: - _refuse("PUBLISH_UNAVAILABLE", operation_id=operation.id, observation="branch_head_absent") - if operation.commit_sha is not None: - if head != operation.commit_sha: - _refuse("PUBLISH_HEAD_MOVED", operation_id=operation.id, required_head=operation.commit_sha, observed_head=head) - elif head != operation.expected_branch_head: - if operation.attempts <= 1: - _refuse("PUBLISH_HEAD_MOVED", operation_id=operation.id, required_head=operation.expected_branch_head, observed_head=head) - retained_commit = _observe_own_commit(client, connection.repository, head, operation) - if not retained_commit.matches: - _refuse("PUBLISH_HEAD_MOVED", operation_id=operation.id, operation="reconcile_commit", - required_head=operation.expected_branch_head, observed_head=head, - observed_parent_sha=retained_commit.observed_parent_sha, commit_reason=retained_commit.reason) - else: - result = publish_catalog_bytes(client, target, rendered.content, - f"Publish catalog revision {operation.catalog_revision_id} {_operation_marker(operation)}") - commit = result.get("commit") if isinstance(result, dict) else None - written = commit.get("sha") if isinstance(commit, dict) else None - head = _branch_head(client, connection.repository, connection.branch) - if not isinstance(written, str) or head != written or not _HEAD.fullmatch(written): - _refuse("PUBLISH_COMMIT_RECEIPT_INVALID", operation_id=operation.id, observed_head=head) - operation.commit_sha, operation.state = head, "committed" - operation.updated_at = datetime.now(UTC) - _commit(db, operation.id) - commit_observation = _observe_own_commit(client, connection.repository, head, operation) - observed = _observe_published_content(client, connection.repository, target, head, rendered.content) - if not commit_observation.matches or not observed.matches: - _refuse("PUBLISH_RENDER_MISMATCH", operation_id=operation.id, operation="verify_remote_render", - required_render_sha256=rendered.render_sha256, observed_render_sha256=observed.observed_sha256, - observed_commit_sha=head, commit_matches=commit_observation.matches, - commit_reason=commit_observation.reason, required_parent_sha=operation.expected_branch_head, - observed_parent_sha=commit_observation.observed_parent_sha, - observed_http_status=observed.http_status, observation_reason=observed.reason) + if not isinstance(written, str) or head != written or not _HEAD.fullmatch(written): + _refuse("PUBLISH_COMMIT_RECEIPT_INVALID", operation_id=operation.id, observed_head=head) + operation.commit_sha, operation.state = head, "committed" + operation.updated_at = datetime.now(UTC) + _commit(db, operation.id) + commit_observation = _observe_own_commit(client, connection.repository, head, operation) + observed = _observe_published_content(client, connection.repository, target, head, rendered.content) + if not commit_observation.matches or not observed.matches: + _refuse("PUBLISH_RENDER_MISMATCH", operation_id=operation.id, operation="verify_remote_render", + required_render_sha256=rendered.render_sha256, observed_render_sha256=observed.observed_sha256, + observed_commit_sha=head, commit_matches=commit_observation.matches, + commit_reason=commit_observation.reason, required_parent_sha=operation.expected_branch_head, + observed_parent_sha=commit_observation.observed_parent_sha, + observed_http_status=observed.http_status, observation_reason=observed.reason) return _finalize(db, operation, snapshot, head) # #endregion ScenarioExecution.PublicationWorker.Attempt @@ -265,22 +264,25 @@ def publish_baseline_catalog(db, *, selector: ExactCatalogRevision, expected_bra logger.reason("Publish the exact retained DB revision render", src=_SRC, payload={"catalog_id": selector.catalog_id, "catalog_revision_id": selector.catalog_revision_id, "render_sha256": rendered.render_sha256, "expected_branch_head": expected_branch_head}) - operation = _prepare(db, selector, expected_branch_head, idempotency_key, actor, destination, rendered, snapshot) - if operation.state == "published": - from .publication_receipt_binding import load_receipted_published_catalog - load_receipted_published_catalog(db, selector) - return _view(operation) - target = GiteaTarget(base_url=connection.base_url, repo=connection.repository, ref=connection.branch, - token=connection.token.get_secret_value(), path=rendered.path) - try: - return _attempt(db, operation, snapshot, connection, target, rendered, transport) - except (PublicationError, PublishError, httpx.HTTPError) as exc: - code = exc.code if isinstance(exc, (PublicationError, PublishError)) else "PUBLISH_UNAVAILABLE" - db.rollback() - retained = db.get(PublicationOperation, operation.id) - retained.state, retained.error_code, retained.updated_at = "publish_failed", code, datetime.now(UTC) - _commit(db, retained.id) - _refuse(code, operation_id=retained.id, catalog_revision_id=selector.catalog_revision_id) + headers = {"Authorization": f"token {connection.token.get_secret_value()}"} + with httpx.Client(base_url=connection.base_url, headers=headers, timeout=30, transport=transport) as client: + require_publication_destination(client, connection.repository) + operation = _prepare(db, selector, expected_branch_head, idempotency_key, actor, destination, rendered, snapshot) + if operation.state == "published": + from .publication_receipt_binding import load_receipted_published_catalog + load_receipted_published_catalog(db, selector) + return _view(operation) + target = GiteaTarget(base_url=connection.base_url, repo=connection.repository, ref=connection.branch, + token=connection.token.get_secret_value(), path=rendered.path) + try: + return _attempt(db, operation, snapshot, connection, target, rendered, client) + except (PublicationError, PublishError, httpx.HTTPError) as exc: + code = exc.code if isinstance(exc, (PublicationError, PublishError)) else "PUBLISH_UNAVAILABLE" + db.rollback() + retained = db.get(PublicationOperation, operation.id) + retained.state, retained.error_code, retained.updated_at = "publish_failed", code, datetime.now(UTC) + _commit(db, retained.id) + _refuse(code, operation_id=retained.id, catalog_revision_id=selector.catalog_revision_id) # #endregion ScenarioExecution.PublicationWorker.Publish diff --git a/backend/src/services/mcp_publish_dispatch.py b/backend/src/services/mcp_publish_dispatch.py index af863bf94..a212da0cb 100644 --- a/backend/src/services/mcp_publish_dispatch.py +++ b/backend/src/services/mcp_publish_dispatch.py @@ -5,8 +5,8 @@ # @RELATION DEPENDS_ON -> [Services.McpOpsDispatch.Validation] # @INVARIANT The payload is re-validated before any I/O; the repository and branch are server-resolved # from the deployment publish-source config — the caller never picks the destination. -# @INVARIANT A typed worker failure surfaces as a dispatch failure while the durable operation row -# retains the reconcile state (publish_failed with the typed code). +# @INVARIANT Post-intent worker failures retain the durable reconcile state; source admission +# refusals surface unchanged before intent, without a publication operation row. # @RATIONALE Extracted from McpOpsDispatch (INV_7): the publish adapter is a distinct reviewed domain; # the ops module stays under the module-size limit. from __future__ import annotations diff --git a/backend/tests/api/test_catalog_publications_api.py b/backend/tests/api/test_catalog_publications_api.py index ab2164834..7764c7e3b 100644 --- a/backend/tests/api/test_catalog_publications_api.py +++ b/backend/tests/api/test_catalog_publications_api.py @@ -9,6 +9,7 @@ # -> VERIFIED_BY: tests below import uuid import base64 +import json from copy import deepcopy from types import SimpleNamespace from unittest.mock import patch @@ -47,6 +48,7 @@ from tests.services.dashboard_testing.execution.test_publication_worker import ( HEAD as _CURRENT_HEAD, WRITTEN as _CURRENT_COMMIT, Server, + publication_source_identity as publication_source_identity, ) from tests.services.dashboard_testing.test_native_result_lifecycle import ( _CONSUME_COMMIT, @@ -164,7 +166,7 @@ def _publication_rows(db): @pytest.fixture -def current_publication_env(native_lifecycle, monkeypatch): +def current_publication_env(native_lifecycle, monkeypatch, publication_source_identity): from src.models.auth import Role, User item = native_lifecycle @@ -285,6 +287,38 @@ def test_create_rejects_nested_envelope_with_422(current_publication_env): assert _publication_rows(env.db) == before +# #region Test.Api.CatalogPublications.SourceAdmission [C:3] [TYPE Function] +# @TEST_INVARIANT Real native revision admission surfaces source refusals before any publication row or HTTP write. +@pytest.mark.parametrize('case,status,code,expected_requests', [ + ('missing_source', 503, 'SOURCE_REPOSITORY_IDENTITY_UNAVAILABLE', []), + ('source_repository', 409, 'SOURCE_REPOSITORY_FORBIDDEN', [('GET', '/api/v1/repos/fixture/catalog')]), + ('metadata_401', 503, 'SOURCE_REPOSITORY_IDENTITY_UNAVAILABLE', [('GET', '/api/v1/repos/fixture/catalog')]), +]) +def test_source_admission_refuses_before_operation(current_publication_env, publication_source_identity, + monkeypatch, case, status, code, expected_requests): + env = current_publication_env + before = _publication_rows(env.db) + if case == 'missing_source': + monkeypatch.delenv('SOURCE_REPOSITORY_IDENTITY_FILE') + elif case == 'source_repository': + publication_source_identity.write_text(json.dumps({'source_commit': 'a' * 40, + 'origin': {'host': 'git.test', 'port': None, 'repository': 'fixture/catalog'}})) + else: + def metadata_denied(request): + assert (request.method, request.url.path) == ('GET', '/api/v1/repos/fixture/catalog') + return httpx.Response(401, text='private-metadata-body-sentinel') + + monkeypatch.setattr(env.server, 'handler', metadata_denied) + response = env.client.post('/api/catalog-publications', headers={'Idempotency-Key': env.key}, + json={'catalog_selection': env.selector.model_dump(mode='json'), 'expected_branch_head': _CURRENT_HEAD}) + assert response.status_code == status + assert response.json()['detail']['code'] == code + assert 'private-metadata-body-sentinel' not in response.text + assert env.requests == expected_requests and env.server.writes == [] + assert _publication_rows(env.db) == before +# #endregion Test.Api.CatalogPublications.SourceAdmission + + def test_read_unknown_operation_is_404(monkeypatch): env = CatalogPublicationsEnv(monkeypatch) response = env.client.get(f"/api/catalog-publications/{uuid.uuid4()}") diff --git a/backend/tests/scripts/test_publish_catalog.py b/backend/tests/scripts/test_publish_catalog.py index 961829fd5..6ca5d8c72 100644 --- a/backend/tests/scripts/test_publish_catalog.py +++ b/backend/tests/scripts/test_publish_catalog.py @@ -29,7 +29,9 @@ from tests.services.dashboard_testing.execution.test_publication_transaction_rec pending_publication as pending_publication, publication_trace as publication_trace, ) -from tests.services.dashboard_testing.execution.test_publication_worker import attempt_case, Server, HEAD, WRITTEN +from tests.services.dashboard_testing.execution.test_publication_worker import ( + attempt_case, Server, HEAD, WRITTEN, publication_source_identity as publication_source_identity, +) from tests.services.dashboard_testing.test_baseline_catalog import exact_selector @@ -239,7 +241,7 @@ def test_main_creates_via_post_when_absent(pending_publication): writes = [] def observe(request): - assert str(request.url).startswith("https://git.test/api/v1/repos/fixture/catalog/") + assert str(request.url) == "https://git.test/api/v1/repos/fixture/catalog" or str(request.url).startswith("https://git.test/api/v1/repos/fixture/catalog/") assert request.headers["Authorization"] == "token offline-token" if request.method in {"POST", "PUT"}: writes.append((request.method, request.url.path, json.loads(request.content))) @@ -264,6 +266,8 @@ def test_main_types_transport_errors(pending_publication): operation_id, key = operation.id, operation.idempotency_key def unavailable(request): + if request.url.path == "/api/v1/repos/fixture/catalog": + return Server(b"").handler(request) raise httpx.ConnectError("private transport error", request=request) with pytest.raises(PublicationError) as raised: diff --git a/backend/tests/services/dashboard_testing/execution/test_publication_failure_state.py b/backend/tests/services/dashboard_testing/execution/test_publication_failure_state.py index f4f8774a9..5ba845f6e 100644 --- a/backend/tests/services/dashboard_testing/execution/test_publication_failure_state.py +++ b/backend/tests/services/dashboard_testing/execution/test_publication_failure_state.py @@ -17,14 +17,16 @@ from src.services.dashboard_testing.execution.publication_config import Publicat from src.services.dashboard_testing.execution.publication_errors import PublicationError from src.services.dashboard_testing.execution.publication_worker import publish_baseline_catalog from tests.services.dashboard_testing.execution.test_publication_transaction_recovery import pending_publication as pending_publication, publication_trace as publication_trace -from tests.services.dashboard_testing.execution.test_publication_worker import Server, HEAD, WRITTEN +from tests.services.dashboard_testing.execution.test_publication_worker import ( + Server, HEAD, WRITTEN, publication_source_identity as publication_source_identity, +) _CONFIG = {'PUBLISHED_CATALOG_BASE_URL':'https://git.test', 'PUBLISHED_CATALOG_REPO':'fixture/catalog', 'PUBLISHED_CATALOG_REF':'main', 'PUBLISHED_CATALOG_TOKEN':'offline-token'} @pytest.fixture(autouse=True) -def publication_configuration(monkeypatch): +def publication_configuration(monkeypatch, publication_source_identity): for name, value in _CONFIG.items(): monkeypatch.setenv(name, value) @@ -99,7 +101,7 @@ def test_idempotency_conflict_on_different_digest(pending_publication, change): catalog_revision_id=successor.revision.catalog_revision_id) count = db.query(PublicationOperation).count() with pytest.raises(PublicationError) as raised: - _publish(db, selector, operation.idempotency_key, None, **changes) + _publish(db, selector, operation.idempotency_key, httpx.MockTransport(Server(b'').handler), **changes) assert raised.value.code == 'PUBLISH_IDEMPOTENCY_CONFLICT' assert db.query(PublicationOperation).count() == count assert _stored_state(db, operation.id) == ('publish_pending', None, None, None, 0) @@ -111,6 +113,8 @@ def test_transport_error_is_typed_and_marks_row_failed(pending_publication): db, selector, operation = pending_publication def unavailable(request): + if request.url.path == '/api/v1/repos/fixture/catalog': + return Server(b'').handler(request) raise httpx.ConnectError('offline transport unavailable', request=request) with pytest.raises(PublicationError) as raised: diff --git a/backend/tests/services/dashboard_testing/execution/test_publication_git_repository.py b/backend/tests/services/dashboard_testing/execution/test_publication_git_repository.py index 7f6277983..6f8624192 100644 --- a/backend/tests/services/dashboard_testing/execution/test_publication_git_repository.py +++ b/backend/tests/services/dashboard_testing/execution/test_publication_git_repository.py @@ -7,8 +7,7 @@ import json from pathlib import Path import subprocess import httpx -from tests.services.dashboard_testing.execution.test_publication_worker import attempt_case -from src.services.dashboard_testing.execution.publication_worker import _attempt +from tests.services.dashboard_testing.execution.test_publication_worker import attempt_case, attempt_with_client def git(repo, *args): @@ -51,12 +50,12 @@ def test_receipt_names_real_commit_with_exact_db_render(tmp_path): return httpx.Response(201, json={"commit":{"sha":git(repo, "rev-parse", "HEAD").decode()}}) raise AssertionError("Unexpected Git API operation") - result = _attempt(*case, httpx.MockTransport(handler)) + result = attempt_with_client(*case, httpx.MockTransport(handler)) commit = result["published_receipt"]["commit_sha"] assert git(repo, "show", f"{commit}:{target.path}") + b"\n" == rendered.content assert result["published_receipt"]["catalog_revision_id"] == "11111111-1111-4111-8111-111111111112" assert result["published_receipt"]["head_after"] == git(repo, "rev-parse", "HEAD").decode() - repeated = _attempt(*case, httpx.MockTransport(handler)) + repeated = attempt_with_client(*case, httpx.MockTransport(handler)) assert repeated["commit_sha"] == commit and repeated["attempts"] == 2 assert git(repo, "rev-list", "--count", "HEAD") == b"2" # #endregion Test.PublicationGitRender diff --git a/backend/tests/services/dashboard_testing/execution/test_publication_remote_observation.py b/backend/tests/services/dashboard_testing/execution/test_publication_remote_observation.py index b5ef3ede1..a6adef6ec 100644 --- a/backend/tests/services/dashboard_testing/execution/test_publication_remote_observation.py +++ b/backend/tests/services/dashboard_testing/execution/test_publication_remote_observation.py @@ -45,6 +45,7 @@ def test_exact_linewrapped_render(): # @TEST_INVARIANT [ScenarioExecution.PublicationWorker.Attempt] The actual refusal names observed bytes independently of commit marker identity. def test_attempt_logs_observed_digest_on_wrong_remote_bytes(monkeypatch, caplog): from pydantic import SecretStr + from tests.services.dashboard_testing.execution.test_publication_worker import attempt_with_client from src.core.cot_logger import seed_trace_id from src.services.dashboard_testing.execution import publication_worker as worker from src.services.dashboard_testing.execution.publication_errors import PublicationError @@ -63,7 +64,7 @@ def test_attempt_logs_observed_digest_on_wrong_remote_bytes(monkeypatch, caplog) connection = SimpleNamespace(token=SecretStr('nonsecret-fixture-token'), base_url='http://fixture.invalid', repository='repo', branch='main') with pytest.raises(PublicationError) as error: - worker._attempt(None, operation, None, connection, SimpleNamespace(path='catalogs/id/rev.yaml'), + attempt_with_client(None, operation, None, connection, SimpleNamespace(path='catalogs/id/rev.yaml'), SimpleNamespace(content=b'exact render', render_sha256=sha256(b'exact render').hexdigest()), httpx.MockTransport(response)) assert error.value.code == 'PUBLISH_RENDER_MISMATCH' diff --git a/backend/tests/services/dashboard_testing/execution/test_publication_source_guard.py b/backend/tests/services/dashboard_testing/execution/test_publication_source_guard.py new file mode 100644 index 000000000..fa6a660d1 --- /dev/null +++ b/backend/tests/services/dashboard_testing/execution/test_publication_source_guard.py @@ -0,0 +1,179 @@ +# #region Test.PublicationSourceGuard [C:4] [TYPE Module] [SEMANTICS publication,source,admission,privacy] +# @BRIEF Literal source/official repository fixtures prove pre-intent refusals and safe observed classifications. +# @RELATION VERIFIES -> [ScenarioExecution.PublicationSourceGuard.Require] +import json +from copy import deepcopy + +import httpx +import pytest + +from src.core.cot_formatter import CotJsonFormatter +from src.core.cot_logger import seed_trace_id +from src.core.source_repository_identity import SourceRepositoryRefusal +from src.services.dashboard_testing.execution.publication_source_guard import require_publication_destination + + +# #region Test.PublicationSourceGuard.Source [C:2] [TYPE Fixture] +@pytest.fixture +def source_metadata(tmp_path, monkeypatch): + path = tmp_path / 'source.json' + path.write_text('{"source_commit":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",' + '"origin":{"host":"source.example","port":null,"repository":"team/source"}}') + monkeypatch.setenv('SOURCE_REPOSITORY_IDENTITY_FILE', str(path)) + seed_trace_id() + return path +# #endregion Test.PublicationSourceGuard.Source + + +# #region Test.PublicationSourceGuard.Metadata [C:1] [TYPE Function] +def metadata(repository='team/source', host='internal.example'): + return {'id': 17, 'full_name': repository, 'clone_url': f'https://{host}/{repository}.git', + 'html_url': f'https://{host}/{repository}', 'ssh_url': f'git@{host}:{repository}.git'} +# #endregion Test.PublicationSourceGuard.Metadata + + +# #region Test.PublicationSourceGuard.Run [C:2] [TYPE Function] +def observe(response, repository='team/source'): + requests = [] + + def handler(request): + requests.append((request.method, request.url.path)) + return response + + with httpx.Client(base_url='https://internal.example', transport=httpx.MockTransport(handler)) as client: + require_publication_destination(client, repository) + return requests +# #endregion Test.PublicationSourceGuard.Run + + +# #region Test.PublicationSourceGuard.ExactMatch [C:3] [TYPE Function] +@pytest.mark.parametrize('field,url', [ + ('clone_url', 'https://SOURCE.EXAMPLE/team/source.git'), + ('html_url', 'https://source.example/TEAM/SOURCE'), + ('ssh_url', 'git@Source.Example:team/source.git'), +]) +def test_any_official_source_alias_refuses(source_metadata, caplog, field, url): + value = metadata() + value[field] = url + with pytest.raises(SourceRepositoryRefusal) as failure: + observe(httpx.Response(200, json=value)) + assert failure.value.code == 'SOURCE_REPOSITORY_FORBIDDEN' + event = next(record for record in caplog.records if getattr(record, 'error_code', None) == failure.value.code) + assert event.payload['repository_id'] == 17 + assert event.payload['match_class'] == 'source_repository_match' +# #endregion Test.PublicationSourceGuard.ExactMatch + + +# #region Test.PublicationSourceGuard.UnprovedAlias [C:2] [TYPE Function] +@pytest.mark.parametrize('host', ['internal.example', 'source.example:443']) +def test_same_path_unproved_host_or_port_never_authorizes(source_metadata, host): + value = metadata(host=host) + if ':' in host: + value['ssh_url'] = 'ssh://git@source.example:443/team/source.git' + with pytest.raises(SourceRepositoryRefusal) as failure: + observe(httpx.Response(200, json=value)) + assert failure.value.code == 'SOURCE_REPOSITORY_IDENTITY_UNAVAILABLE' +# #endregion Test.PublicationSourceGuard.UnprovedAlias + + +# #region Test.PublicationSourceGuard.Distinct [C:2] [TYPE Function] +def test_official_distinct_repository_path_is_allowed(source_metadata, caplog): + requests = observe(httpx.Response(200, json=metadata('other/catalog', 'source.example')), 'other/catalog') + assert requests == [('GET', '/api/v1/repos/other/catalog')] + event = next(record for record in caplog.records if getattr(record, 'marker', None) == 'REFLECT' + and getattr(record, 'src', None) == 'ScenarioExecution.PublicationSourceGuard') + assert event.payload['match_class'] == 'disjoint_repository_path' +# #endregion Test.PublicationSourceGuard.Distinct + + +# #region Test.PublicationSourceGuard.ObservationFailure [C:3] [TYPE Function] +@pytest.mark.parametrize('response,reason,status', [ + (httpx.Response(401), 'http_status', 401), (httpx.Response(404), 'http_status', 404), + (httpx.Response(200, text='private-response-sentinel'), 'invalid_json', 200), + (httpx.Response(200, json={'id': True}), 'metadata_shape', 200), + (httpx.Response(200, json=metadata('foreign/repo')), 'full_name_conflict', 200), + (httpx.Response(200, json={**metadata(), 'ssh_url': None}), 'url_identity_invalid', 200), + (httpx.Response(200, json={**metadata(), 'clone_url': 'https://user:private-url-sentinel@host/foreign/repo'}), + 'url_identity_conflict', 200), +]) +def test_exact_safe_observation_reason_is_retained(source_metadata, caplog, response, reason, status): + with pytest.raises(SourceRepositoryRefusal) as failure: + observe(response) + assert failure.value.code == 'SOURCE_REPOSITORY_IDENTITY_UNAVAILABLE' + events = [json.loads(CotJsonFormatter().format(record)) for record in caplog.records + if getattr(record, 'error_code', None) == failure.value.code] + assert len(events) == 1 + event = events[0] + assert event['marker'] == 'EXPLORE' + assert event['contract_id'] == 'ScenarioExecution.PublicationSourceGuard' + assert event['payload']['observation_stage'] == 'repository_metadata' + assert event['payload']['observation_reason'] == reason + assert event['payload']['http_status'] == status + assert 'private-response-sentinel' not in json.dumps(events) + assert 'private-url-sentinel' not in json.dumps(events) +# #endregion Test.PublicationSourceGuard.ObservationFailure + + +# #region Test.PublicationSourceGuard.NoSource [C:2] [TYPE Function] +def test_missing_source_refuses_without_external_io(monkeypatch, caplog): + monkeypatch.delenv('SOURCE_REPOSITORY_IDENTITY_FILE', raising=False) + + def forbidden(request): + pytest.fail('Missing source identity must refuse before HTTP') + + with httpx.Client(base_url='https://internal.example', transport=httpx.MockTransport(forbidden)) as client: + with pytest.raises(SourceRepositoryRefusal) as failure: + require_publication_destination(client, 'team/source') + assert failure.value.code == 'SOURCE_REPOSITORY_IDENTITY_UNAVAILABLE' + event = next(record for record in caplog.records if getattr(record, 'error_code', None) == failure.value.code) + assert event.payload == {'match_class': 'source_identity_unavailable', 'observation_stage': 'source_metadata'} +# #endregion Test.PublicationSourceGuard.NoSource + + +# #region Test.PublicationSourceGuard.Transport [C:3] [TYPE Function] +@pytest.mark.parametrize('kind,error_class', [(httpx.ConnectError, 'connect_error'), + (httpx.ReadTimeout, 'timeout'), (httpx.RemoteProtocolError, 'protocol_error')]) +def test_transport_failure_keeps_safe_class_without_private_message(source_metadata, caplog, kind, error_class): + def unavailable(request): + raise kind('private-transport-sentinel', request=request) + + with httpx.Client(base_url='https://internal.example', transport=httpx.MockTransport(unavailable)) as client: + with pytest.raises(SourceRepositoryRefusal) as failure: + require_publication_destination(client, 'team/source') + assert failure.value.code == 'SOURCE_REPOSITORY_IDENTITY_UNAVAILABLE' + event = next(record for record in caplog.records if getattr(record, 'error_code', None) == failure.value.code) + assert event.payload['observation_reason'] == 'transport_error' + assert event.payload['http_error_class'] == error_class + assert 'private-transport-sentinel' not in CotJsonFormatter().format(event) +# #endregion Test.PublicationSourceGuard.Transport + + +# #region Test.PublicationSourceGuard.PreIntent [C:3] [TYPE Function] +# @TEST_INVARIANT Actual worker source refusal precedes any operation/commit or HTTP write; literal DB render is not native authority. +def test_actual_worker_refuses_source_repository_before_intent(source_metadata, monkeypatch): + monkeypatch.setenv('DATABASE_URL', 'sqlite:///:memory:') # Import configuration only; no application DB fixture. + from src.services.dashboard_testing.execution.publication_worker import publish_baseline_catalog + from tests.services.dashboard_testing.test_baseline_catalog import Database, exact_selector + + db = Database() + before = deepcopy(db.rows) + for name, value in {'PUBLISHED_CATALOG_BASE_URL': 'https://internal.example', + 'PUBLISHED_CATALOG_REPO': 'team/source', 'PUBLISHED_CATALOG_REF': 'main', + 'PUBLISHED_CATALOG_TOKEN': 'private-token-sentinel'}.items(): + monkeypatch.setenv(name, value) + requests = [] + + def handler(request): + requests.append((request.method, request.url.path)) + assert request.method == 'GET' and request.url.path == '/api/v1/repos/team/source' + return httpx.Response(200, json=metadata(host='source.example')) + + with pytest.raises(SourceRepositoryRefusal) as failure: + publish_baseline_catalog(db, selector=exact_selector(), expected_branch_head='8' * 40, + idempotency_key='explicit-source-refusal', actor='fixture', transport=httpx.MockTransport(handler)) + assert failure.value.code == 'SOURCE_REPOSITORY_FORBIDDEN' + assert requests == [('GET', '/api/v1/repos/team/source')] + assert db.rows == before + assert db.commits == 0 +# #endregion Test.PublicationSourceGuard.PreIntent +# #endregion Test.PublicationSourceGuard diff --git a/backend/tests/services/dashboard_testing/execution/test_publication_transaction_recovery.py b/backend/tests/services/dashboard_testing/execution/test_publication_transaction_recovery.py index 864c68d83..c2678c557 100644 --- a/backend/tests/services/dashboard_testing/execution/test_publication_transaction_recovery.py +++ b/backend/tests/services/dashboard_testing/execution/test_publication_transaction_recovery.py @@ -18,10 +18,9 @@ from src.schemas.dashboard_testing.catalog_revision import ExactCatalogRevision from src.services.dashboard_testing.catalog_store import load_catalog_revision, render_catalog_revision from src.services.dashboard_testing.execution.publication_config import PublicationConnection from src.services.dashboard_testing.execution.publication_errors import PublicationError -from src.services.dashboard_testing.execution.publication_worker import _attempt from src.scripts.publish_catalog import GiteaTarget from tests.services.dashboard_testing.execution.pg_consumer_fixture import database, close_database -from tests.services.dashboard_testing.execution.test_publication_worker import Server, HEAD, WRITTEN +from tests.services.dashboard_testing.execution.test_publication_worker import Server, HEAD, WRITTEN, attempt_with_client # #region Test.Publication.TransactionRecovery.Trace [C:1] [TYPE Function] @@ -78,7 +77,7 @@ def test_git_commit_survives_db_failure_without_false_receipt_and_retry_reuses_i with monkeypatch.context() as patch: patch.setattr(db, 'commit', commit) with pytest.raises(PublicationError) as raised: - _attempt(db, operation, snapshot, connection, target, rendered, httpx.MockTransport(server.handler)) + attempt_with_client(db, operation, snapshot, connection, target, rendered, httpx.MockTransport(server.handler)) assert raised.value.code == 'PUBLISH_DATABASE_UNAVAILABLE' assert 'PRIVATE_SQL_BODY_SENTINEL' not in ''.join(traceback.format_exception(raised.value)) assert len(server.writes) == 1 and server.head == WRITTEN and server.content == rendered.content @@ -96,7 +95,7 @@ def test_git_commit_survives_db_failure_without_false_receipt_and_retry_reuses_i from src.services.dashboard_testing.execution.publication_receipt_binding import load_receipted_published_catalog with pytest.raises(ValueError, match='^BASELINE_NOT_PUBLISHED$'): load_receipted_published_catalog(fresh, exact) - restored = _attempt(fresh, pending, snapshot, connection, target, rendered, httpx.MockTransport(server.handler)) + restored = attempt_with_client(fresh, pending, snapshot, connection, target, rendered, httpx.MockTransport(server.handler)) assert restored['state'] == 'published' and restored['commit_sha'] == WRITTEN assert restored['attempts'] == 2 and len(server.writes) == 1 assert restored['published_receipt']['catalog_revision_id'] == selector.catalog_revision_id diff --git a/backend/tests/services/dashboard_testing/execution/test_publication_worker.py b/backend/tests/services/dashboard_testing/execution/test_publication_worker.py index 267ab7d42..8ebc2e4df 100644 --- a/backend/tests/services/dashboard_testing/execution/test_publication_worker.py +++ b/backend/tests/services/dashboard_testing/execution/test_publication_worker.py @@ -34,12 +34,39 @@ def attempt_case(): return db, operation, snapshot, connection, target, rendered +# #region Test.PublicationWorker.Client [C:2] [TYPE Function] +# @PRE Component callers supply explicit authored transport; public source admission is tested separately. +# @POST The actual attempt uses and closes one real httpx client, with no optional transport/client fallback. +def attempt_with_client(db, operation, snapshot, connection, target, rendered, transport): + with httpx.Client(base_url=connection.base_url, + headers={"Authorization": f"token {connection.token.get_secret_value()}"}, timeout=30, + transport=transport) as client: + return _attempt(db, operation, snapshot, connection, target, rendered, client) +# #endregion Test.PublicationWorker.Client + + +# #region Test.PublicationWorker.SourceIdentity [C:2] [TYPE Fixture] +# @BRIEF Explicit synthetic build identity for publication tests; no actual image/build or native authority claim. +@pytest.fixture +def publication_source_identity(tmp_path, monkeypatch): + path = tmp_path / "synthetic-source-repository.json" + path.write_text('{"source_commit":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",' + '"origin":{"host":"source.example","port":null,"repository":"team/source"}}') + monkeypatch.setenv("SOURCE_REPOSITORY_IDENTITY_FILE", str(path)) + return path +# #endregion Test.PublicationWorker.SourceIdentity + + class Server: def __init__(self, content, *, head=HEAD, message=None): self.head, self.content, self.message = head, content, message self.writes = [] def handler(self, request): path = request.url.path + if request.method == "GET" and path == "/api/v1/repos/fixture/catalog": + return httpx.Response(200, json={"id": 17, "full_name": "fixture/catalog", + "clone_url": "https://git.test/fixture/catalog.git", "html_url": "https://git.test/fixture/catalog", + "ssh_url": "git@git.test:fixture/catalog.git"}) if "/branches/" in path: return httpx.Response(200, json={"commit":{"id":self.head}}) if "/git/commits/" in path: @@ -62,7 +89,7 @@ def test_publish_attempt_writes_exact_render_and_six_field_receipt(): case = attempt_case() db, operation, _, _, _, rendered = case server = Server(rendered.content) - result = _attempt(*case, httpx.MockTransport(server.handler)) + result = attempt_with_client(*case, httpx.MockTransport(server.handler)) assert result["state"] == "published" and result["commit_sha"] == WRITTEN assert len(server.writes) == 1 and base64.b64decode(server.writes[0]["content"]) == rendered.content assert set(result["published_receipt"]) == {"catalog_revision_id", "render_sha256", "integrity_sha256", "commit_sha", "head_after", "verified_at"} @@ -78,7 +105,7 @@ def test_retry_reconciles_same_operation_without_second_write(committed): operation.attempts = 1 operation.commit_sha = WRITTEN if committed else None server = Server(rendered.content, head=WRITTEN, message=f"Publish (publication {operation.id})") - result = _attempt(*case, httpx.MockTransport(server.handler)) + result = attempt_with_client(*case, httpx.MockTransport(server.handler)) assert result["state"] == "published" and result["attempts"] == 2 assert server.writes == [] @@ -88,7 +115,7 @@ def test_foreign_commit_with_identical_render_cannot_be_adopted(): case[1].attempts = 1 server = Server(case[-1].content, head=WRITTEN, message="Foreign commit with identical content") with pytest.raises(PublicationError) as raised: - _attempt(*case, httpx.MockTransport(server.handler)) + attempt_with_client(*case, httpx.MockTransport(server.handler)) assert raised.value.code == "PUBLISH_HEAD_MOVED" assert server.writes == [] and case[1].published_receipt is None @@ -99,7 +126,7 @@ def test_matching_marker_with_wrong_render_refuses(): operation.commit_sha = WRITTEN server = Server(b"foreign-render", head=WRITTEN, message=f"(publication {operation.id})") with pytest.raises(PublicationError) as raised: - _attempt(*case, httpx.MockTransport(server.handler)) + attempt_with_client(*case, httpx.MockTransport(server.handler)) assert raised.value.code == "PUBLISH_RENDER_MISMATCH" assert operation.published_receipt is None and server.writes == [] diff --git a/backend/tests/services/dashboard_testing/test_catalog_write_transfer.py b/backend/tests/services/dashboard_testing/test_catalog_write_transfer.py index 707940469..bd06d7904 100644 --- a/backend/tests/services/dashboard_testing/test_catalog_write_transfer.py +++ b/backend/tests/services/dashboard_testing/test_catalog_write_transfer.py @@ -7,6 +7,7 @@ import logging import sys from uuid import uuid4 +import httpx import pytest from sqlalchemy import select @@ -20,10 +21,13 @@ from src.schemas.dashboard_testing.catalog_revision import CatalogRevisionOperat from src.services.dashboard_testing.catalog_store import seed_catalog, append_catalog_revision, CatalogStoreError from src.services.dashboard_testing.execution.publication_worker import publish_baseline_catalog from src.services.dashboard_testing.execution.publication_errors import PublicationError +from tests.services.dashboard_testing.execution.test_publication_worker import ( + Server, publication_source_identity as publication_source_identity, +) @pytest.fixture -def catalog(monkeypatch): +def catalog(monkeypatch, publication_source_identity): for key, value in {'PUBLISHED_CATALOG_BASE_URL': 'https://git.test', 'PUBLISHED_CATALOG_REPO': 'fixture/catalog', 'PUBLISHED_CATALOG_REF': 'main', 'PUBLISHED_CATALOG_TOKEN': 'nonsecret-test-token'}.items(): @@ -165,14 +169,26 @@ def test_append_retry_changed_body_preserves_complete_database_state(catalog, re # @TEST_INVARIANT [ScenarioExecution.PublicationWorker.Publish] A published retry validates its retained receipt without network writes. def test_published_retry_has_no_external_io(catalog, monkeypatch): db, selector, operation = catalog - monkeypatch.setattr('src.services.dashboard_testing.execution.publication_worker.httpx.Client', - lambda **kwargs: pytest.fail('Published retry must not perform external I/O')) + before = _catalog_rows(db, selector.catalog_id) + receipt = dict(operation.published_receipt) + requests = [] + + def repository_admission(request): + requests.append((request.method, request.url.path)) + assert request.headers['Authorization'] == 'token nonsecret-test-token' + assert (request.method, request.url.path) == ('GET', '/api/v1/repos/fixture/catalog') + return Server(b'').handler(request) + result = publish_baseline_catalog(db, selector=selector, expected_branch_head='8' * 40, - idempotency_key=operation.idempotency_key, actor='fixture') + idempotency_key=operation.idempotency_key, actor='fixture', + transport=httpx.MockTransport(repository_admission)) assert result['state'] == 'published' assert result['operation_id'] == operation.id assert result['attempts'] == 1 assert result['published_receipt']['commit_sha'] == '7' * 40 + assert result['published_receipt'] == receipt + assert requests == [('GET', '/api/v1/repos/fixture/catalog')] + assert _catalog_rows(db, selector.catalog_id) == before # #endregion Test.CatalogWriteTransfer.PublicationRetry @@ -181,11 +197,24 @@ def test_published_retry_has_no_external_io(catalog, monkeypatch): def test_destination_drift_refuses_without_mutating_receipt(catalog, monkeypatch): db, selector, operation = catalog monkeypatch.setenv('PUBLISHED_CATALOG_REPO', 'foreign/catalog') + before = _catalog_rows(db, selector.catalog_id) + requests = [] + + def repository_admission(request): + requests.append((request.method, request.url.path)) + assert (request.method, request.url.path) == ('GET', '/api/v1/repos/foreign/catalog') + return httpx.Response(200, json={'id': 18, 'full_name': 'foreign/catalog', + 'clone_url': 'https://git.test/foreign/catalog.git', + 'html_url': 'https://git.test/foreign/catalog', 'ssh_url': 'git@git.test:foreign/catalog.git'}) + with pytest.raises(PublicationError) as raised: publish_baseline_catalog(db, selector=selector, expected_branch_head='8' * 40, - idempotency_key=operation.idempotency_key, actor='fixture') + idempotency_key=operation.idempotency_key, actor='fixture', + transport=httpx.MockTransport(repository_admission)) assert raised.value.code == 'PUBLISH_DESTINATION_DRIFT' assert operation.state == 'published' assert operation.attempts == 1 + assert requests == [('GET', '/api/v1/repos/foreign/catalog')] + assert _catalog_rows(db, selector.catalog_id) == before # #endregion Test.CatalogWriteTransfer.DestinationDrift # #endregion Test.CatalogWriteTransfer diff --git a/backend/tests/services/dashboard_testing/test_native_result_lifecycle.py b/backend/tests/services/dashboard_testing/test_native_result_lifecycle.py index ceb3d67af..e7100cb8e 100644 --- a/backend/tests/services/dashboard_testing/test_native_result_lifecycle.py +++ b/backend/tests/services/dashboard_testing/test_native_result_lifecycle.py @@ -28,7 +28,9 @@ from src.services.dashboard_testing.execution.baseline_resolver import resolve_b from src.services.dashboard_testing.result_values import canonical_json from src.services.agent_runs.artifacts import get_draft_storage from src.services.storage_holds import load_index -from tests.services.dashboard_testing.execution.test_publication_worker import Server, HEAD, WRITTEN +from tests.services.dashboard_testing.execution.test_publication_worker import ( + Server, HEAD, WRITTEN, publication_source_identity as publication_source_identity, +) def meta(): @@ -168,7 +170,7 @@ def confirm(lifecycle): # #region Test.NativeResultLifecycle.CurrentPublication [C:3] [TYPE Function] # @TEST_INVARIANT [BaselineEngine.NativeRevisionPublication.Validate] Actual capture/request/confirm/hold/consume owners authorize the exact DB revision, actual worker HTTP protocol, and unchanged frozen pin; a receipt is never inserted directly. # @PRE PG guard authored for the final migrated isolated database. HTTP is an external synthetic Gitea simulator, not a live publication claim. -def test_real_request_confirmation_materialization_primary_publication_and_frozen_pin(lifecycle, monkeypatch): +def test_real_request_confirmation_materialization_primary_publication_and_frozen_pin(lifecycle, monkeypatch, publication_source_identity): item = lifecycle root = item.storage._storage._root source = deepcopy(item.draft.capture_meta['reference_source']) diff --git a/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization-journal.md b/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization-journal.md index bde052ac6..c1965547a 100644 --- a/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization-journal.md +++ b/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization-journal.md @@ -1308,4 +1308,12 @@ Exact immutable949 indices21–24/179 differed only by required environment_id. Two earlier harness failures remain retained: SQLite app-import URL triggered root autouse Alembic and CATALOG_POSTGRESQL_REQUIRED before all five calls; the next default-sandbox attempt failed PostgreSQL preflight before any node. The authorized existing fixture-PG URL/require_escalated boundary corrected execution context without changing product or business fixtures. Actual targeted110+owner26 leaves88 baseline cases/60 classes; no fresh fullbackend green or347 acceptance, N120 unchanged. Soak explicit-input cut d5a7cf3e separately passed22SQL-free guards and compose config --quiet; this proves admission/config syntax, not container startup or current M01 acceptance. +### 2026-10-11 — immutable source identity and publication admission + +Metadata owner/plumbing021328c9 records one observed clean HEAD/origin, rejects ordinary untracked source and ambiguous origin, and requires one explicit deployment-owned runtime file. Thirty-nine SQL-free/temp-Git guards passed; no image build or runtime reload occurred. Publication now uses the same authenticated HTTP client for exact official repository metadata admission before DB intent and subsequent writes. Any canonical source match refuses SOURCE_REPOSITORY_FORBIDDEN; same-path unproved aliases or unavailable/malformed metadata refuse SOURCE_REPOSITORY_IDENTITY_UNAVAILABLE. Safe Molecular facts distinguish HTTP status, transport class and metadata conflicts without private bodies/credentials. REST preserves409/503; MCP already rolls back/rethrows the typed refusal. Post-intent reconciliation remains unchanged. + +The old published-retry zero-network-read premise is deliberately superseded by mandatory readonly destination admission: exactly one metadata GET, no branch/content request or write, unchanged full six-field receipt/attempt count/scoped DB rows. The existing test identity remains referenced by accounting; no ledger expansion. Direct attempt components use an explicit real client and do not claim public source admission. Thirty-nine pure publication checks and one actual bounded PostgreSQL run of44 nodes/all132 phases passed, private0, source hashes unchanged; native approval/consume plus current REST positive, stale HEAD, malformed input and three source-refusal guards all ran. Initial/final RR READ ONLY capacity stayed1quota/0leases/0active/0charged consistent; watcher closed. Three REST refusal events join exact node traces; other fixture-owned trace resets are explicitly not invented as HealthFixture joins. Frozen packet: artifacts/evidence-curation-20261011/publication-source-gate-freeze.json; actual receipt: publication-source-gate-actual-receipt.json. This is SQL/savepoint readback with external HTTP doubles, not independent durability, live Git, wholebackend or347 acceptance. N120/targeted110/owner26/88remaining/60classes unchanged; final cleanup POST audit pending. + +Separate live C56 orchestration remains OPEN (original134/136/137): deployment reaches ACTUAL_EVIDENCE_REQUIRED without actual input/persistence; scheduler lacks an explicit selector. Actual deployment invokes plugin.execute before verification admission. These required positive properties need fresh current owned observation/exact pin and persistence, not expected-only self-comparison or deferred SDK substitution; no implementation or count closure is claimed here. + ## @} Stage2.ChartTypeStabilizationJournal20261010 diff --git a/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization.md b/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization.md index a1f55ebee..b3808128d 100644 --- a/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization.md +++ b/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization.md @@ -53,7 +53,7 @@ D17 не блокирует мерж. Отклонённый PNGd8c01a0d не п ## Очистка evidence перед мержем -Шаги1–7 выполняются отдельными проверенными коммитами. После PREDELETE CLEAR afac удалены406 файлов050/evidence (00232b); индекс191 точного каталога сохранён (2d477477),52 документа переведены на проверенные архивные ссылки (bc070d94). Текущие writers используют artifacts или внешние каталоги; parser использует синтетические данные, действует запрет новых запрещённых файлов в specs. Soak требует явный существующий вход (d5a7cf3e). Защита публикации от SOURCE-репозитория и итоговый POST-аудит секретов ещё выполняются. Старые неизменённые прототипы вне050 не переносим по догадке. Master и история не меняются. Настоящий архив artifacts выполняется после мержа; любые записи в origin и push тега — только в согласованном окне мержа по точным командам/ссылкам и явному решению владельца. Сейчас эти действия не выполняются. +Шаги1–7 выполняются отдельными проверенными коммитами. После PREDELETE CLEAR afac удалены406 файлов050/evidence (00232b); индекс191 точного каталога сохранён (2d477477),52 документа переведены на проверенные архивные ссылки (bc070d94). Текущие writers используют artifacts или внешние каталоги; parser использует синтетические данные, действует запрет новых запрещённых файлов в specs. Soak требует явный существующий вход (d5a7cf3e). Защита публикации от SOURCE-репозитория проверена: неизменяемая build identity, официальный authenticated repository GET до intent, точные публичные отказы409/503;39 pure и44 PG/component проверки прошли. Image/runtime запуск не выполнялся. Итоговый POST-аудит секретов ещё требуется. Старые неизменённые прототипы вне050 не переносим по догадке. Master и история не меняются. Настоящий архив artifacts выполняется после мержа; любые записи в origin и push тега — только в согласованном окне мержа по точным командам/ссылкам и явному решению владельца. Сейчас эти действия не выполняются. ## Будущий режим обновления Superset