diff --git a/docs/sources/2026-10-05-implementation-decisions.md b/docs/sources/2026-10-05-implementation-decisions.md index 22ae233..dad445c 100644 --- a/docs/sources/2026-10-05-implementation-decisions.md +++ b/docs/sources/2026-10-05-implementation-decisions.md @@ -98,3 +98,24 @@ readiness remains separate from enablement. already-applied and fresh databases — cost if wrong: 0048 must apply to activate. - Ruling: retain daily FSSP/exchange and 30-day Checko intervals/monthly claims — minimal requested change — cost if wrong: 30-day cadence is not a calendar month. + +## Live acceptance continuation + +- Ruling: accept nullable Checko publisher only when the canonical subject still + matches the publisher or an exact participant — observed real upstream null, + no invented identifier — cost if wrong: messages without confirmed subject + remain rejected; generated clients must accept null. +- Ruling: preserve specific SnapshotValidationError before its ValueError base + handler — real diagnostics otherwise conceal the rejected field — cost if + wrong: safe error codes become more specific for existing rejected inputs. +- Ruling: stop the broken messages run cooperatively, keep all monthly claims, + and rerun only eligible unclaimed scopes after release — avoids repeated costs + for known adapter failures — cost if wrong: first-month coverage stays partial. +- Ruling: use the two already verified official FSSP daily files for separate + manual import acceptance when dev receives HTTP 474 — no network bypass or + invented freshness — cost if wrong: manual publication does not prove the + automatic upstream download is operational. +- Ruling: enable the existing Russian CA only in SPB's dedicated allowlisted + session behind a default-off setting and a dev-only host compose flag after + explicit user consent — cost if wrong: only SPB gains this extra trust; + MOEX/system/main trust remains unchanged, certificate verification stays on. diff --git a/docs/sources/checko-sections.md b/docs/sources/checko-sections.md index cf88ad7..fddaaa6 100644 --- a/docs/sources/checko-sections.md +++ b/docs/sources/checko-sections.md @@ -36,3 +36,25 @@ Claim берётся атомарно до первого запроса и со Artifact — приватный NDJSON с нормализованными наблюдениями и upstream-полями, SHA-256/size; credentials/meta balance не сохраняются. `completeness=full|partial`; непересекающиеся категории: `organizations_updated + organizations_empty + organizations_failed + quota_skipped = organizations_total`. `organizations_preserved = organizations_failed + quota_skipped`, это пересекающийся диагностический счётчик, его не суммируют второй раз. `updated_records_count` — записи завершённого scope, `retained_records_count` — сохранённые записи, published/snapshot counts — весь текущий опубликованный набор. Partial success не двигает `latest_success_load` полного прохода; последний job/load показывает partial metadata. API и экспорт читают все текущие записи, включая сохранённые из прежних batches. Итоговая проверка и конкретная dev-приёмка — в [передаче реализации](2026-10-05-implementation-handoff.md). Прежние PostgreSQL 42 passed проверяли schema/locks, но использовали pytest `--nomigrations`; фактический граф доказан позднее отдельным `--migrations --create-db` прогоном. Пересечение страниц с неполным числом уникальных GUID теперь отклоняется до публикации и до фильтра лизинга; старые записи и месячный claim сохраняются. Платные реальные вызовы не выполнялись. + +## Реальный dev запуск 5 октября 2026 + +Пользователь разрешил ручной полный сбор. Лизинг опубликовал 3 158 записей: +3 236 организаций успешно завершены, 2 523 запроса завершились отказом, +269 некорректных/неоднозначных канонических организаций не запрашивались. +Этот результат partial; полный last-success не подменяется. Read-only проверка +развёрнутых DRF list/detail против реальной БД подтвердила pagination total, +UUID и совпадение payload. Внешний запрос без аутентификации возвращает 401. + +Реальный `/fedresurs` также возвращает `Публикатор: null` при наличии нашего +ИНН/ОГРН в `Участники`. Ранее адаптер ошибочно отклонял весь раздел такой +организации. Publisher теперь nullable, принадлежность по точному участнику +сохраняется обязательной, если publisher не совпадает. Null сохраняется в raw, +list/detail и canonical OpenAPI. Ошибки SnapshotValidationError сохраняют +конкретную безопасную причину вместо общего invalid_checko_section_schema. + +Месячные claims после первого прогона и остановленного сбора сообщений +сохраняются. Исправление не разрешает их сброс, повторную оплату или фиктивную +публикацию неуспешных организаций. Последующий штатный запуск обработает только +ещё не заявленные организации; полный охват потребует следующего периода либо +отдельно согласованной политики повторного сбора. diff --git a/docs/sources/exchanges.md b/docs/sources/exchanges.md index 3d4e669..8957993 100644 --- a/docs/sources/exchanges.md +++ b/docs/sources/exchanges.md @@ -103,3 +103,17 @@ CSV/XLSX/JSON exports через штатные generations/tickets сохран Если ISS возвращает cursor, обход завершён после валидированной страницы, достигшей TOTAL; для ответов без cursor сохраняется terminal-empty обход. Регрессии TOTAL=1/100/101 прошли после воспроизведения ошибки. + +## Dev trust acceptance, 5 October 2026 + +Реальный штатный job на dev получил SSLError от СПБ. Пользователь явно разрешил +повторное использование существующего bundle Минцифры именно сборщиком СПБ на dev. +`EXCHANGE_SPB_RUSSIAN_TRUST_ENABLED` по умолчанию false. При true только отдельная +SPB session использует `clients/common/eis_russian_trusted_ca.pem`; все её запросы +проходят существующий allowlist spbexchange.ru. MOEX session, другие источники и +системное хранилище не меняются; verify=False отсутствует. + +Оператор включает этот несекретный флаг только в Mostovik environment anchor +host-owned compose dev, с резервной копией, release lock и config --quiet +проверкой до штатного CI release. Root checkout/StateCorp/main не изменяются. +Флаг не включается автоматически при последующем развёртывании в другом контуре. diff --git a/src/apps/parsers/checko_sections.py b/src/apps/parsers/checko_sections.py index 3422577..2c51c98 100644 --- a/src/apps/parsers/checko_sections.py +++ b/src/apps/parsers/checko_sections.py @@ -124,7 +124,7 @@ def _message_record(raw, organization, source, fetched_at): guid = _text(raw.get("GUID"), required=True) message_type = _text(raw.get("Тип"), required=True) label = _text(raw.get("ТипНаим")) - publisher = _text(raw.get("Публикатор"), required=True) + publisher = _text(raw.get("Публикатор")) participants = raw.get("Участники") if not isinstance(participants, list): raise SnapshotValidationError("invalid_checko_participants") @@ -259,5 +259,7 @@ def collect_checko_section( raise SnapshotValidationError( f"checko_collection_failed:{type(exc).__name__}" ) from exc + except SnapshotValidationError: + raise except (ValueError, TypeError, KeyError) as exc: raise SnapshotValidationError("invalid_checko_section_schema") from exc diff --git a/src/apps/parsers/exchange_spb.py b/src/apps/parsers/exchange_spb.py index ad68a03..b3f6947 100644 --- a/src/apps/parsers/exchange_spb.py +++ b/src/apps/parsers/exchange_spb.py @@ -10,6 +10,7 @@ from io import BytesIO, TextIOWrapper from typing import BinaryIO from urllib.parse import urljoin, urlparse +from apps.parsers.clients.common.structured import EIS_CA_BUNDLE_PATH from apps.parsers.models import ParserSourceArtifact from apps.parsers.registry_http import ( limited_bytes, @@ -170,7 +171,9 @@ def download_spb_artifact( ) try: with registry_session() as session: - # Existing EIS trust is deliberately NOT reused: approval was probe-only. + # This session serves only allowlisted SPB requests; MOEX has its own. + if getattr(settings, "EXCHANGE_SPB_RUSSIAN_TRUST_ENABLED", False): + session.verify = str(EIS_CA_BUNDLE_PATH) with registry_response(session, SPB_INDEX, hosts=SPB_HOSTS) as response: before = discover_spb_date( limited_bytes(response, 4 * 1024**2).decode("utf-8") diff --git a/src/core/openapi.json b/src/core/openapi.json index dcecc04..2ab2658 100644 --- a/src/core/openapi.json +++ b/src/core/openapi.json @@ -22194,7 +22194,8 @@ "nullable": true }, "publisher_identifier": { - "type": "string" + "type": "string", + "nullable": true }, "participant_identifiers": { "type": "array", @@ -22258,7 +22259,8 @@ "nullable": true }, "publisher_identifier": { - "type": "string" + "type": "string", + "nullable": true }, "participant_identifiers": { "type": "array", diff --git a/src/organizations/checko_section_payload_serializers.py b/src/organizations/checko_section_payload_serializers.py index 8d613f3..0e691b7 100644 --- a/src/organizations/checko_section_payload_serializers.py +++ b/src/organizations/checko_section_payload_serializers.py @@ -11,7 +11,7 @@ class CheckoMessagePayloadSerializer(serializers.Serializer): publication_date = serializers.DateField(allow_null=True) message_type = serializers.CharField() message_type_name = serializers.CharField(allow_null=True) - publisher_identifier = serializers.CharField() + publisher_identifier = serializers.CharField(allow_null=True) participant_identifiers = serializers.ListField(child=serializers.CharField()) source_url = serializers.CharField(allow_null=True) fetched_at = RegistryUTCDateTimeField() diff --git a/src/settings/base.py b/src/settings/base.py index c61aac3..18805ea 100644 --- a/src/settings/base.py +++ b/src/settings/base.py @@ -532,6 +532,9 @@ SRO_MAX_REQUESTS_PER_RUN = int(os.getenv("SRO_MAX_REQUESTS_PER_RUN", "10000")) # Public exchange collection bounds; TLS verification stays enabled. EXCHANGE_SPB_MAX_BYTES = 50 * 1024**2 EXCHANGE_SPB_MAX_ROWS = 100000 +EXCHANGE_SPB_RUSSIAN_TRUST_ENABLED = _env_bool( + "EXCHANGE_SPB_RUSSIAN_TRUST_ENABLED", default=False +) EXCHANGE_MOEX_MAX_RESPONSE_BYTES = 10 * 1024**2 EXCHANGE_MOEX_MAX_PAGES = 1000 EXCHANGE_MOEX_MAX_REQUESTS = 10000 diff --git a/tests/apps/organizations/test_checko_section_contract.py b/tests/apps/organizations/test_checko_section_contract.py index 95ad32d..97da5e6 100644 --- a/tests/apps/organizations/test_checko_section_contract.py +++ b/tests/apps/organizations/test_checko_section_contract.py @@ -151,6 +151,27 @@ class CheckoSectionContractTests(TestCase): == "partial" ) + def test_nullable_publisher_survives_public_list_and_detail(self): + first = fixture("messages-page-1.json") + first["data"]["Записи"][0]["Публикатор"] = None + with patch.object( + snapshots, + "_client", + return_value=client_with(first, fixture("messages-page-2.json")), + ): + snapshots.refresh_checko_section(source="checko_messages", load_batch=1) + response = self.client.get(self.url, {"source_group": "company_messages"}) + assert response.status_code == 200, response.data + row = next( + row + for row in response.data["data"] + if row["payload"]["publisher_identifier"] is None + ) + detail = self.client.get(self.url + row["uid"] + "/") + assert detail.status_code == 200, detail.data + assert detail.data["payload"] == row["payload"] + assert row["payload"]["participant_identifiers"] == [self.org.inn] + def test_no_completed_failure_exposes_rejected_counters(self): source = "checko_messages" claim_monthly_collection(organization_id=str(self.org.uid), source=source) diff --git a/tests/apps/organizations/test_openapi_runtime_fixtures.py b/tests/apps/organizations/test_openapi_runtime_fixtures.py index 255d412..a01faed 100644 --- a/tests/apps/organizations/test_openapi_runtime_fixtures.py +++ b/tests/apps/organizations/test_openapi_runtime_fixtures.py @@ -141,12 +141,12 @@ def _canonical_records(): ) sections = [] for source in ("checko_leasing", "checko_messages", "checko_licenses"): + message_page = fixture("messages-page-1.json") + message_page["data"]["Записи"][0]["Публикатор"] = None client = ( client_with(fixture("license.json")) if source == "checko_licenses" - else client_with( - fixture("messages-page-1.json"), fixture("messages-page-2.json") - ) + else client_with(message_page, fixture("messages-page-2.json")) ) row = next(collect_checko_section(client, organization=fssp_org, source=source)) row.payload["upstream"]["future_nested"] = { diff --git a/tests/apps/parsers/test_checko_sections.py b/tests/apps/parsers/test_checko_sections.py index a97497c..a1b78df 100644 --- a/tests/apps/parsers/test_checko_sections.py +++ b/tests/apps/parsers/test_checko_sections.py @@ -177,7 +177,7 @@ def test_overlapping_pages_cannot_prove_total_before_leasing_filter(source): response["data"]["ЗапВсего"] = 4 with pytest.raises(SnapshotValidationError) as error: collect(client_with(first, second), source) - assert str(error.value.__cause__) == "incomplete_checko_record_count" + assert str(error.value) == "incomplete_checko_record_count" def test_license_unknown_raw_fields_survive(): @@ -200,3 +200,23 @@ def test_malformed_license_section_rejected(value): response["data"]["Лиценз"] = value with pytest.raises(SnapshotValidationError): collect(client_with(response), "checko_licenses") + + +@pytest.mark.parametrize("source", ["checko_messages", "checko_leasing"]) +def test_nullable_publisher_keeps_message_when_canonical_subject_is_participant(source): + first = fixture("messages-page-1.json") + first["data"]["Записи"][0]["Публикатор"] = None + rows = collect(client_with(first, fixture("messages-page-2.json")), source) + assert rows[0].payload["publisher_identifier"] is None + assert rows[0].payload["participant_identifiers"] == [ORG.inn] + assert rows[0].payload["upstream"]["Публикатор"] is None + + +def test_nullable_publisher_does_not_admit_message_for_another_subject(): + first = fixture("messages-page-1.json") + first["data"]["Записи"][0]["Публикатор"] = None + first["data"]["Записи"][0]["Участники"] = ["0000000000"] + with pytest.raises( + SnapshotValidationError, match="^checko_message_subject_mismatch$" + ): + collect(client_with(first, fixture("messages-page-2.json"))) diff --git a/tests/apps/parsers/test_exchange_spb.py b/tests/apps/parsers/test_exchange_spb.py index 61b5838..c92d74d 100644 --- a/tests/apps/parsers/test_exchange_spb.py +++ b/tests/apps/parsers/test_exchange_spb.py @@ -105,7 +105,8 @@ def test_tls_trust_stays_default(): @pytest.mark.django_db -def test_download_checksum_date_private_file_and_three_bounded_reads(tmp_path): +@pytest.mark.parametrize("trusted", [False, True]) +def test_download_checksum_date_private_file_and_three_bounded_reads(tmp_path, trusted): import hashlib from contextlib import contextmanager from unittest.mock import patch @@ -117,6 +118,9 @@ def test_download_checksum_date_private_file_and_three_bounded_reads(tmp_path): @contextmanager def response(session, url, **kwargs): + from apps.parsers.clients.common.structured import EIS_CA_BUNDLE_PATH + + assert session.verify == (str(EIS_CA_BUNDLE_PATH) if trusted else True) urls.append(url) class Response: @@ -125,14 +129,16 @@ def test_download_checksum_date_private_file_and_three_bounded_reads(tmp_path): yield Response() - with override_settings(PARSER_PRIVATE_ARTIFACT_ROOT=str(tmp_path)), patch.object( - module, "registry_response", response - ): + with override_settings( + PARSER_PRIVATE_ARTIFACT_ROOT=str(tmp_path), + EXCHANGE_SPB_RUSSIAN_TRUST_ENABLED=trusted, + ), patch.object(module, "registry_response", response): artifact = module.download_spb_artifact(load_batch=1) assert artifact.sha256 == hashlib.sha256(body).hexdigest() assert artifact.source_published_at.isoformat() == "2026-10-05" assert artifact.metadata["input_only"] is True assert len(urls) == 3 + assert module.registry_session().verify is True with pytest.raises(ValueError): _ = artifact.file.url diff --git a/tools/openapi/source-record-extensions.json b/tools/openapi/source-record-extensions.json index 8309fa4..92398a0 100644 --- a/tools/openapi/source-record-extensions.json +++ b/tools/openapi/source-record-extensions.json @@ -995,7 +995,8 @@ "nullable": true }, "publisher_identifier": { - "type": "string" + "type": "string", + "nullable": true }, "participant_identifiers": { "type": "array", @@ -1059,7 +1060,8 @@ "nullable": true }, "publisher_identifier": { - "type": "string" + "type": "string", + "nullable": true }, "participant_identifiers": { "type": "array",