Compare commits

..

1 Commits

Author SHA1 Message Date
Aleksandr Meshchryakov
666876d10f style(auth): format SSO implementation 2026-09-21 16:44:44 +02:00
10 changed files with 35 additions and 445 deletions

View File

@@ -254,11 +254,3 @@ make pre-commit
Дополнительный SSO-вход включается переменной `SSO_ENABLED=true`. Публичный P-256 PEM-ключ провайдера должен быть смонтирован вне репозитория и webroot, а путь к нему передан в `SSO_PUBLIC_KEY_PATH`.
Используются настройки `SSO_PROVIDER_URL`, `SSO_SERVICE_CODE` (по умолчанию `fkc`), `SSO_ISSUER` (по умолчанию `dvr`) и `SSO_SESSION_TTL_SECONDS` (по умолчанию `7200`). Перед включением зарегистрируйте callback `https://<state-corp-host>/api/v1/auth/sso/` в ИАС ЕЦП и сначала включите backend, затем frontend-кнопку. Для отката достаточно установить `SSO_ENABLED=false`; JWT-вход продолжит работать.
### Контракт callback ИАС
ИАС отправляет `POST /api/v1/auth/sso/` с `Content-Type: application/x-www-form-urlencoded`: обязательное поле `sso_token`, необязательное `redirect_path` (локальный путь, по умолчанию `/main`). Вариант URL без завершающего `/` тоже принимает форму напрямую: промежуточного 301, теряющего POST, нет. Для регистрации в ИАС используйте канонический URL со слешем.
После успешной проверки одноразового ES256 JWT backend устанавливает Django session cookie и CSRF cookie и отвечает `303 Location: <redirect_path>`. GET callback возвращает 405; токен в URL не принимается. Пустая форма при включённом SSO возвращает 400, при выключенном — 503.
Перед выпуском проверяйте каждый контур отдельно: `SSO_ENABLED`, issuer, service code/target, соответствие callback у ИАС и доступность публичного ключа в контейнере. Включение dev не включает main. Правка маршрута не заменяет настройку провайдера и полный вход с настоящим SSO-токеном. Не копируйте токены/cookie в логи или отчёты.

View File

@@ -1,15 +0,0 @@
# Выгрузка за все годы
Годовая задача `apps.external_data.tasks.refresh_source_record_export_artifacts` сохраняет прежнее поведение.
Новая задача `apps.external_data.tasks.refresh_all_years_source_record_export_artifacts` собирает все доступные записи каждого поддерживаемого источника без ограничения по году, включая все финансовые строки. Для источников с заменяемыми snapshot выгружается текущее опубликованное состояние: удалённые прежние snapshot не восстанавливаются.
Результат размещается в `SOURCE_RECORD_EXPORT_DIRECTORY/all-years`. У него отдельные `current.json`, `generations` и очистка старых поколений. Публикация атомарна; незавершённая сборка не заменяет опубликованные файлы. Общий lock с годовой задачей ограничивает одновременную нагрузку. Manifest содержит `export_scope: all_years` и `export_year: null`; годовой manifest — `export_scope: current_year` и числовой год. Старые годовые manifest без `export_scope` продолжают читаться.
Ручной запуск:
```sh
python src/manage.py build_source_record_exports --all-years
```
Периодический запуск настраивается отдельной записью django-celery-beat либо системным таймером на контуре без Beat. Задачу следует ставить после годовой сборки. Имена файлов, группировка JSON по ОКПО и форматы CSV/XLSX/JSON сохраняются. API скачивания продолжает отдавать годовой пакет; доступ к полному пакету предоставляется отдельно.

View File

@@ -47,20 +47,9 @@ JavaScript. Ticket не попадает в URL и после первого з
Итого формируется 25 логических артефактов. Финансовые показатели всегда
выгружаются в JSON с вложенным массивом `financial_lines`. Промышленная группа
объединяет три таблицы, а поле `record_type` различает тип строки. CSV и XLSX
сохраняют плоские строки с реквизитами организации и полями `payload.*`.
JSON каждого источника использует тот же контракт, что и Mostovik: массив
организаций с `okpo` и массивом записей под ключом группы API. Например:
```json
[{"okpo":"12345678","bankruptcy":[{"uid":"...","source_group":"bankruptcy","payload.case_number":"..."}]}]
```
`ОКПО` переносится из записи в `okpo` оболочки; остальные поля записи остаются
в прежнем виде. Записи одной организации собираются вместе независимо от
порядка чтения таблиц. При отсутствии ОКПО экспортируется `null`, а для
группировки используются ИНН, ОГРН и наименование. При выборе нескольких
источников ZIP содержит отдельный JSON-файл для каждого.
объединяет три таблицы, а поле `record_type` различает тип строки. Все строки
используют тот же контракт, что и Mostovik: реквизиты организации, включая ОКПО,
общие поля записи источника и специфичные поля в `payload.*`.
Все записи текущего года включаются в публичные файлы, а техническое
наименование внешнего поставщика нейтрализуется. Исходные значения в БД
@@ -79,9 +68,8 @@ Celery Beat запускает
1. читает каждую нормализованную таблицу один раз без model-level сортировки;
предметные даты и fallback по `created_at` индексированы;
2. создаёт плоский spool и группирует JSON по ОКПО через временный дисковый
индекс SQLite, без загрузки всех строк в память;
3. потоково формирует CSV и write-only XLSX из того же spool;
2. создаёт компактный JSON-массив и переиспользует его как готовый JSON;
3. потоково формирует CSV и write-only XLSX;
4. записывает календарный `export_year` в manifest;
5. атомарно публикует `current.json` только после готовности всей матрицы;
6. при ошибке удаляет staging и продолжает отдавать предыдущее поколение того же года;
@@ -91,10 +79,7 @@ Web и Celery worker должны использовать общий read-write
## Первый запуск и настройки
Первое поколение можно сформировать вручную. После обновления формата JSON
поколения с manifest версии 2 не раздаются: до первой успешной сборки версии 3
API возвращает `503 source_export_not_ready`. Запустите команду ниже после
развёртывания, чтобы восстановить доступность выгрузок сразу:
Первое поколение можно сформировать вручную:
```bash
PYTHONPATH=src uv run python src/manage.py build_source_record_exports
@@ -109,8 +94,7 @@ PYTHONPATH=src uv run python src/manage.py build_source_record_exports
| `SOURCE_RECORD_EXPORT_DOWNLOAD_TICKET_TTL_SECONDS` | `300` | Срок действия download-ticket |
Для атомарной генерации требуется свободное место не меньше
`(GENERATIONS_TO_KEEP + 1) * размер поколения` плюс исходный spool,
временная база SQLite размером порядка spool и рабочий запас файловой системы.
`(GENERATIONS_TO_KEEP + 1) * размер поколения` плюс запас файловой системы.
На локальном снимке от 2026-08-04 поколение за 2026 год содержит 1 962 записи
и занимает 4 738 872 байта (4,52 MiB) для всей матрицы. Архив со всеми

View File

@@ -14,18 +14,8 @@ class Command(BaseAppCommand):
help = "Формирует готовые CSV/XLSX/JSON выгрузки внешних источников"
use_transaction = False
def add_arguments(self, parser) -> None:
super().add_arguments(parser)
parser.add_argument(
"--all-years",
action="store_true",
help="Все доступные годы в отдельном каталоге all-years",
)
def execute_command(self, *args, **options) -> str:
generation = build_source_record_export_artifacts(
all_years=options["all_years"]
)
generation = build_source_record_export_artifacts()
rendered = json.dumps(
{
"generation_id": generation.generation_id,

View File

@@ -8,7 +8,6 @@ import os
import re
import secrets
import shutil
import sqlite3
import zipfile
from collections.abc import Iterable, Iterator, Sequence
from dataclasses import dataclass
@@ -45,7 +44,7 @@ EXPORT_FORMAT_XLSX = "xlsx"
EXPORT_FORMAT_JSON = "json"
EXPORT_FORMATS = (EXPORT_FORMAT_CSV, EXPORT_FORMAT_XLSX, EXPORT_FORMAT_JSON)
FINANCIAL_SOURCE_GROUP = "financial_indicators"
EXPORT_MANIFEST_VERSION = 3
EXPORT_MANIFEST_VERSION = 2
CURRENT_EXPORT_MANIFEST_FILE_NAME = "current.json"
GENERATION_MANIFEST_FILE_NAME = "manifest.json"
GENERATION_DIRECTORY_NAME = "generations"
@@ -442,7 +441,7 @@ class SourceRecordExportGeneration:
generation_id: str
generated_at: str
export_year: int | None
export_year: int
artifacts: tuple[SourceRecordExportArtifact, ...]
records_count: int
@@ -512,19 +511,16 @@ def build_source_record_export_artifacts(
*,
now: datetime | None = None,
export_directory: str | Path | None = None,
all_years: bool = False,
) -> SourceRecordExportGeneration:
"""Build annual or all-years files and atomically publish their generation."""
"""Build all files on disk and atomically publish a new generation."""
root_directory = _resolve_export_directory(export_directory)
if all_years:
root_directory /= "all-years"
generations_directory = root_directory / GENERATION_DIRECTORY_NAME
root_directory.mkdir(parents=True, exist_ok=True)
generations_directory.mkdir(parents=True, exist_ok=True)
generated_at_datetime = _normalize_generation_datetime(now or timezone.now())
export_year = None if all_years else _export_year(generated_at_datetime)
export_year = _export_year(generated_at_datetime)
generation_id = (
f"{generated_at_datetime.strftime('%Y%m%dT%H%M%SZ')}-{uuid4().hex[:8]}"
)
@@ -552,7 +548,6 @@ def build_source_record_export_artifacts(
file_format=file_format,
)
artifact_paths = _render_source_group_artifact(
source_group=source_group,
row_spool_path=row_spool_path,
output_path=staging_directory / file_name,
headers=headers,
@@ -864,14 +859,12 @@ def _build_source_group_file_name(*, source_group: str, file_format: str) -> str
def _source_model_queryset(
model_spec: SourceModelExportSpec,
*,
export_year: int | None,
export_year: int,
) -> QuerySet:
queryset = cast(
QuerySet,
model_spec.model.objects.select_related("organization").order_by(),
)
if export_year is None:
return queryset
if model_spec.export_year_lookup:
return queryset.filter(
**{model_spec.export_year_lookup: export_year}
@@ -892,7 +885,7 @@ def _source_model_queryset(
def _iter_source_model_records(
model_spec: SourceModelExportSpec,
*,
export_year: int | None,
export_year: int,
) -> Iterator[Any]:
iterator = _source_model_queryset(
model_spec,
@@ -907,7 +900,7 @@ def _iter_source_model_records(
Prefetch(
related_name,
queryset=FinancialReportLine.objects.filter(
**({"year": export_year} if export_year is not None else {})
year=export_year
).order_by(),
)
if related_name == "lines"
@@ -940,7 +933,7 @@ def _spool_source_group_rows(
*,
source_spec: SourceGroupExportSpec,
output_path: Path,
export_year: int | None,
export_year: int,
) -> tuple[list[str], int]:
records_count = 0
with output_path.open("w", encoding="utf-8", newline="") as output:
@@ -971,7 +964,6 @@ def _spool_source_group_rows(
def _render_source_group_artifact(
*,
source_group: str,
row_spool_path: Path,
output_path: Path,
headers: Sequence[str],
@@ -992,87 +984,10 @@ def _render_source_group_artifact(
headers=headers,
records_count=records_count,
)
_render_json_file(
source_group=source_group,
row_spool_path=row_spool_path,
output_path=output_path,
)
os.link(row_spool_path, output_path)
return (output_path,)
def _render_json_file(
*,
source_group: str,
row_spool_path: Path,
output_path: Path,
) -> None:
grouping_path = output_path.with_name(f".{output_path.name}.grouping.sqlite3")
grouping = sqlite3.connect(grouping_path)
try:
# The published spool can contain millions of unsorted records. Sort on
# local disk instead of sorting the source queryset or loading it in RAM.
grouping.execute("PRAGMA journal_mode=OFF")
grouping.execute(
"CREATE TABLE rows (group_key TEXT, position INTEGER, okpo TEXT, data TEXT)"
)
batch: list[tuple[str, int, str | None, str]] = []
for position, row in enumerate(_iter_spooled_rows(row_spool_path)):
raw_okpo = row.pop("ОКПО", None)
okpo = str(raw_okpo) if raw_okpo else None
fallback = [row.get("ИНН"), row.get("ОГРН"), row.get("Наименование")]
if not any(fallback):
fallback.append(row.get("uid"))
group_key = json.dumps(
[okpo] if okpo else [None, *fallback],
ensure_ascii=False,
)
batch.append(
(
group_key,
position,
okpo,
json.dumps(row, ensure_ascii=False, separators=(",", ":")),
)
)
if len(batch) >= SOURCE_RECORD_EXPORT_ITERATOR_CHUNK_SIZE:
grouping.executemany("INSERT INTO rows VALUES (?, ?, ?, ?)", batch)
batch.clear()
if batch:
grouping.executemany("INSERT INTO rows VALUES (?, ?, ?, ?)", batch)
grouping.commit()
grouping.execute("CREATE INDEX rows_by_group ON rows (group_key, position)")
with output_path.open("w", encoding="utf-8") as output:
output.write("[")
current_group: str | None = None
first_record = True
for group_key, okpo, data in grouping.execute(
"SELECT group_key, okpo, data FROM rows ORDER BY group_key, position"
):
if group_key != current_group:
if current_group is not None:
output.write("]},")
output.write(
'{"okpo":'
+ json.dumps(okpo, ensure_ascii=False)
+ ","
+ json.dumps(source_group)
+ ":["
)
current_group = group_key
first_record = True
if not first_record:
output.write(",")
output.write(data)
first_record = False
if current_group is not None:
output.write("]}")
output.write("]")
finally:
grouping.close()
grouping_path.unlink(missing_ok=True)
def _iter_spooled_rows(row_spool_path: Path) -> Iterator[dict[str, Any]]:
with row_spool_path.open("r", encoding="utf-8") as rows_file:
for line in rows_file:
@@ -1321,9 +1236,6 @@ def _generation_manifest_payload(
"generation_id": generation.generation_id,
"generated_at": generation.generated_at,
"export_year": generation.export_year,
"export_scope": "all_years"
if generation.export_year is None
else "current_year",
"records_count": generation.records_count,
"artifacts_count": generation.artifacts_count,
"files_count": generation.files_count,
@@ -1344,19 +1256,6 @@ def _generation_manifest_payload(
}
def _manifest_export_year(payload: dict[str, Any]) -> int | None:
raw_year = payload["export_year"]
scope = payload.get("export_scope", "current_year")
if scope == "all_years" and raw_year is None:
return None
if scope != "current_year" or raw_year is None or isinstance(raw_year, bool):
raise ValueError("Source-record export scope is invalid.")
year = int(raw_year)
if not 1 <= year <= 9999:
raise ValueError("Source-record export year is invalid.")
return year
def _generation_from_manifest(
payload: Any,
*,
@@ -1368,7 +1267,9 @@ def _generation_from_manifest(
generation_id = str(payload["generation_id"])
generated_at = str(payload["generated_at"])
datetime.fromisoformat(generated_at)
export_year = _manifest_export_year(payload)
export_year = int(payload["export_year"])
if not 1 <= export_year <= 9999:
raise ValueError("Source-record export year is invalid.")
records_count = int(payload["records_count"])
artifact_payloads = payload["artifacts"]
if not isinstance(artifact_payloads, list):

View File

@@ -17,16 +17,6 @@ logger = logging.getLogger(__name__)
def refresh_source_record_export_artifacts(self) -> dict: # noqa: ARG001
"""Build and atomically publish the nightly external-data export matrix."""
return _refresh_source_record_export_artifacts(self, all_years=False)
@shared_task(bind=True, base=CorePeriodicTask)
def refresh_all_years_source_record_export_artifacts(self) -> dict:
"""Publish all available years independently of the annual generation."""
return _refresh_source_record_export_artifacts(self, all_years=True)
def _refresh_source_record_export_artifacts(task, *, all_years: bool) -> dict:
lock_key = getattr(
settings,
"SOURCE_RECORD_EXPORT_LOCK_KEY",
@@ -36,13 +26,11 @@ def _refresh_source_record_export_artifacts(task, *, all_years: bool) -> dict:
getattr(settings, "SOURCE_RECORD_EXPORT_LOCK_TTL_SECONDS", 6 * 60 * 60)
)
if not cache.add(lock_key, "1", timeout=lock_ttl):
if all_years:
raise task.retry(countdown=60, max_retries=lock_ttl // 60 + 2)
logger.info("Source-record export generation skipped: lock is already held")
return {"status": "skipped", "reason": "locked"}
try:
generation = build_source_record_export_artifacts(all_years=all_years)
generation = build_source_record_export_artifacts()
result = {
"status": "success",
"generation_id": generation.generation_id,

View File

@@ -183,9 +183,3 @@ class SsoCallbackView(APIView):
response = HttpResponse(status=303)
response["Location"] = redirect_path
return response
class SsoCallbackWithoutSlashView(SsoCallbackView):
"""Accept legacy callback URLs without duplicating the public API schema."""
swagger_schema = None

View File

@@ -11,11 +11,7 @@ from apps.core.views import (
BackgroundJobStatusView,
BackgroundJobStreamView,
)
from apps.user.sso_views import (
SsoCallbackView,
SsoCallbackWithoutSlashView,
SsoStartView,
)
from apps.user.sso_views import SsoCallbackView, SsoStartView
from django.urls import include, path
app_name = "api_v1"
@@ -27,8 +23,6 @@ jobs_urlpatterns = [
]
urlpatterns = [
# Accept IAS POST forms without a slash without CommonMiddleware's 301.
path("auth/sso", SsoCallbackWithoutSlashView.as_view()),
path("auth/sso/", SsoCallbackView.as_view(), name="sso-callback"),
path("auth/sso/start/", SsoStartView.as_view(), name="sso-start"),
path("analytics/", include("apps.organization.analytics_root_urls")),

View File

@@ -4,7 +4,6 @@ import json
import zipfile
from datetime import UTC, datetime
from io import BytesIO, StringIO
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
@@ -13,7 +12,6 @@ from apps.external_data.source_record_export import (
SOURCE_GROUP_EXPORT_SPECS,
SOURCE_RECORD_EXPORT_FIELDS,
SourceRecordExportArtifactsUnavailable,
_render_json_file,
_source_group_headers,
build_source_record_export_artifacts,
build_source_records_export_archive,
@@ -41,40 +39,6 @@ from tests.apps.organization.factories import OrganizationFactory
from tests.apps.user.factories import UserFactory
def _source_records(groups, source_group):
return [record for group in groups for record in group[source_group]]
def test_json_groups_interleaved_rows_by_okpo():
rows = [
{"ОКПО": "00123456", "ИНН": "111", "uid": "first"},
{"ОКПО": "87654321", "ИНН": "222", "uid": "other"},
{"ОКПО": "00123456", "ИНН": "111", "uid": "last"},
]
with TemporaryDirectory() as directory:
spool_path = Path(directory) / "rows.json"
output_path = Path(directory) / "output.json"
spool_path.write_text(
"[\n" + ",\n".join(json.dumps(row) for row in rows) + "\n]",
encoding="utf-8",
)
_render_json_file(
source_group="bankruptcy",
row_spool_path=spool_path,
output_path=output_path,
)
groups = json.loads(output_path.read_text(encoding="utf-8"))
self_groups = {group["okpo"]: group["bankruptcy"] for group in groups}
assert [row["uid"] for row in self_groups["00123456"]] == ["first", "last"]
assert [row["uid"] for row in self_groups["87654321"]] == ["other"]
assert all(
"ОКПО" not in record for record in _source_records(groups, "bankruptcy")
)
assert not list(Path(directory).glob("*.sqlite3"))
class SourceRecordExportApiTest(APITestCase):
"""Check admin access and zero-query delivery of prepared files."""
@@ -157,8 +121,7 @@ class SourceRecordExportApiTest(APITestCase):
if artifact.source_group == "industrial_production"
and artifact.file_format == "json"
)
industrial_groups = json.loads(industrial_path.read_text(encoding="utf-8"))
industrial_rows = _source_records(industrial_groups, "industrial_production")
industrial_rows = json.loads(industrial_path.read_text(encoding="utf-8"))
self.assertEqual(
{row["record_type"] for row in industrial_rows},
{
@@ -167,8 +130,11 @@ class SourceRecordExportApiTest(APITestCase):
"manufacturer_registry_entry",
},
)
self.assertEqual([group["okpo"] for group in industrial_groups], ["12345678"])
self.assertNotIn("ОКПО", industrial_rows[0])
self.assertEqual({row["ОКПО"] for row in industrial_rows}, {"12345678"})
self.assertEqual(
list(industrial_rows[0])[: len(expected_prefix)],
expected_prefix,
)
self.assertNotIn("organization", industrial_rows[0])
self.assertIn("payload.product_name", industrial_rows[0])
@@ -177,10 +143,7 @@ class SourceRecordExportApiTest(APITestCase):
for artifact in generation.artifacts
if artifact.source_group == "financial_indicators"
)
financial_rows = _source_records(
json.loads(financial_path.read_text(encoding="utf-8")),
"financial_indicators",
)
financial_rows = json.loads(financial_path.read_text(encoding="utf-8"))
self.assertEqual(financial_rows[0]["financial_lines"][0]["line_code"], "1600")
arbitration_path = next(
@@ -188,9 +151,7 @@ class SourceRecordExportApiTest(APITestCase):
for artifact in generation.artifacts
if artifact.source_group == "arbitration" and artifact.file_format == "json"
)
arbitration_row = _source_records(
json.loads(arbitration_path.read_text(encoding="utf-8")), "arbitration"
)[0]
arbitration_row = json.loads(arbitration_path.read_text(encoding="utf-8"))[0]
self.assertEqual(arbitration_row["source"], "arbitration")
self.assertEqual(
arbitration_row["external_id"], arbitration_row["payload.case_number"]
@@ -258,9 +219,7 @@ class SourceRecordExportApiTest(APITestCase):
)
for artifact in artifacts:
if artifact.file_format == "json":
groups = json.loads(artifact.path.read_text(encoding="utf-8"))
self.assertEqual([group["okpo"] for group in groups], ["11223344"])
exported_values = _source_records(groups, "bankruptcy")
exported_values = json.loads(artifact.path.read_text(encoding="utf-8"))
self.assertEqual(
[key for key in exported_values[0] if key.startswith("payload.")],
[
@@ -285,8 +244,7 @@ class SourceRecordExportApiTest(APITestCase):
serialized_values = str(exported_values)
self.assertIn(str(excluded_record.id), serialized_values)
self.assertIn(str(included_record.id), str(exported_values))
if artifact.file_format != "json":
self.assertIn("11223344", str(exported_values))
self.assertIn("11223344", str(exported_values))
self.assertNotRegex(
serialized_values,
r"(?i)(?<![a-zа-яё0-9])(?:checko(?:\.ru)?|чеко|чекало|чекко)"
@@ -303,17 +261,6 @@ class SourceRecordExportApiTest(APITestCase):
self.assertEqual(generation.export_year, timezone.localdate().year)
self.assertIn('"artifacts_count": 25', command_output.getvalue())
def test_previous_json_generation_requires_rebuild(self):
build_source_record_export_artifacts()
manifest_path = Path(self.export_directory.name) / "current.json"
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
self.assertEqual(manifest["version"], 3)
manifest["version"] = 2
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
with self.assertRaises(SourceRecordExportArtifactsUnavailable):
load_current_source_record_export_generation()
def test_generation_contains_only_records_from_its_calendar_year(self):
export_year = 2026
generated_at = datetime(export_year, 8, 4, 6, 0, tzinfo=UTC)
@@ -354,10 +301,7 @@ class SourceRecordExportApiTest(APITestCase):
if artifact.source_group == "government_procurements"
and artifact.file_format == "json"
)
procurement_rows = _source_records(
json.loads(procurements_path.read_text(encoding="utf-8")),
"government_procurements",
)
procurement_rows = json.loads(procurements_path.read_text(encoding="utf-8"))
self.assertEqual(
[row["uid"] for row in procurement_rows],
[str(current_procurement.pk)],
@@ -369,10 +313,7 @@ class SourceRecordExportApiTest(APITestCase):
if artifact.source_group == "industrial_production"
and artifact.file_format == "json"
)
industrial_rows = _source_records(
json.loads(industrial_path.read_text(encoding="utf-8")),
"industrial_production",
)
industrial_rows = json.loads(industrial_path.read_text(encoding="utf-8"))
self.assertEqual(
[row["uid"] for row in industrial_rows],
[str(current_product.pk)],
@@ -383,10 +324,7 @@ class SourceRecordExportApiTest(APITestCase):
for artifact in generation.artifacts
if artifact.source_group == "financial_indicators"
)
financial_rows = _source_records(
json.loads(financial_path.read_text(encoding="utf-8")),
"financial_indicators",
)
financial_rows = json.loads(financial_path.read_text(encoding="utf-8"))
self.assertEqual(
[row["uid"] for row in financial_rows],
[str(current_report.pk)],
@@ -396,115 +334,6 @@ class SourceRecordExportApiTest(APITestCase):
{export_year},
)
def test_all_years_generation_is_separate_and_keeps_historical_financial_lines(
self,
):
organization = OrganizationFactory.create()
for year in (2020, 2026):
PublicProcurementFactory.create(
organization=organization,
contract_date=datetime(year, 1, 1, tzinfo=UTC).date(),
)
report = FinancialReportFactory.create(organization=organization)
for year in (2020, 2026):
FinancialReportLineFactory.create(
report=report, year=year, line_code=str(year)
)
source = "government_procurements"
annual = build_source_record_export_artifacts(
now=datetime(2026, 8, 4, tzinfo=UTC)
)
annual_manifest = Path(self.export_directory.name) / "current.json"
before = annual_manifest.read_bytes()
full = build_source_record_export_artifacts(
now=datetime(2026, 8, 4, tzinfo=UTC),
all_years=True,
)
self.assertIsNone(full.export_year)
self.assertEqual(annual_manifest.read_bytes(), before)
full_root = Path(self.export_directory.name) / "all-years"
loaded = load_current_source_record_export_generation(
export_directory=full_root
)
self.assertEqual(loaded.generation_id, full.generation_id)
self.assertIsNone(loaded.export_year)
def rows(generation, group):
artifact = next(
a
for a in generation.artifacts
if a.source_group == group and a.file_format == "json"
)
return _source_records(json.loads(artifact.path.read_text()), group)
self.assertEqual(len(rows(annual, source)), 1)
self.assertEqual(len(rows(full, source)), 2)
self.assertEqual(
{
line["year"]
for line in rows(full, "financial_indicators")[0]["financial_lines"]
},
{2020, 2026},
)
self.assertEqual(
{
line["year"]
for line in rows(annual, "financial_indicators")[0]["financial_lines"]
},
{2026},
)
# Retention in either scope must not delete the other's files.
for _ in range(3):
build_source_record_export_artifacts(all_years=True)
self.assertTrue(all(a.path.is_file() for a in annual.artifacts))
def test_all_years_command_does_not_publish_an_annual_manifest(self):
call_command("build_source_record_exports", all_years=True, stdout=StringIO())
self.assertFalse((Path(self.export_directory.name) / "current.json").exists())
full = load_current_source_record_export_generation(
export_directory=Path(self.export_directory.name) / "all-years",
)
self.assertIsNone(full.export_year)
def test_full_export_task_publishes_separate_manifest_and_waits_for_lock(self):
from apps.external_data.tasks import (
refresh_all_years_source_record_export_artifacts,
)
from celery.exceptions import Retry
from django.core.cache import cache
lock = "test-full-export-lock"
with self.settings(SOURCE_RECORD_EXPORT_LOCK_KEY=lock):
cache.delete(lock)
cache.add(lock, "held", timeout=30)
try:
with self.assertRaises(Retry):
refresh_all_years_source_record_export_artifacts.run()
self.assertFalse(
(
Path(self.export_directory.name) / "all-years/current.json"
).exists()
)
finally:
cache.delete(lock)
result = refresh_all_years_source_record_export_artifacts.run()
self.assertEqual(result["status"], "success")
self.assertIsNone(result["export_year"])
self.assertIsNone(cache.get(lock))
self.assertFalse(
(Path(self.export_directory.name) / "current.json").exists()
)
def test_manifest_rejects_ambiguous_all_years_scope(self):
build_source_record_export_artifacts(all_years=True)
directory = Path(self.export_directory.name) / "all-years"
manifest_path = directory / "current.json"
payload = json.loads(manifest_path.read_text())
payload["export_year"] = 2026
manifest_path.write_text(json.dumps(payload))
with self.assertRaises(SourceRecordExportArtifactsUnavailable):
load_current_source_record_export_generation(export_directory=directory)
def test_new_calendar_year_requires_a_new_prepared_generation(self):
build_source_record_export_artifacts(
now=datetime(2026, 12, 31, 23, 59, tzinfo=UTC)

View File

@@ -39,26 +39,6 @@ class SsoStartViewTest(SimpleTestCase):
{"target": ["fkc"], "path": ["/open-data?scope=rosatom"]},
)
def test_callback_alias_does_not_duplicate_openapi_operations(self):
from core.api_v1_urls import urlpatterns
from drf_yasg import openapi
from drf_yasg.generators import OpenAPISchemaGenerator
schema = OpenAPISchemaGenerator(
info=openapi.Info(title="SSO", default_version="v1"),
patterns=[
item for item in urlpatterns if str(item.pattern).startswith("auth/sso")
],
).get_schema(request=None, public=True)
operations = [
operation.operation_id
for item in schema.paths.values()
for _, operation in item.operations
]
self.assertEqual(len(operations), len(set(operations)))
self.assertIn("/sso/", schema.paths)
self.assertNotIn("/sso", schema.paths)
def test_rejects_absolute_redirect_path(self):
response = self.client.get(
"/api/v1/auth/sso/start/",
@@ -138,53 +118,6 @@ class SsoCallbackViewTest(APITestCase):
content_type="application/x-www-form-urlencoded",
)
@override_settings(DEBUG=False)
def test_callback_without_slash_preserves_form_and_creates_session(self):
response = self.client.post(
self.callback_url.rstrip("/"),
urlencode({"sso_token": self._token(), "redirect_path": "/open-data"}),
content_type="application/x-www-form-urlencoded",
)
self.assertEqual(response.status_code, 303)
self.assertEqual(response["Location"], "/open-data")
self.assertIn("sessionid", response.cookies)
self.assertIn("csrftoken", response.cookies)
self.assertTrue(response.cookies["sessionid"]["secure"])
self.assertTrue(response.cookies["sessionid"]["httponly"])
self.assertEqual(self.client.get("/api/v1/users/me/").status_code, 200)
@override_settings(DEBUG=False)
def test_both_callback_urls_reject_invalid_forms_and_get(self):
for url in (self.callback_url, self.callback_url.rstrip("/")):
with self.subTest(url=url):
self.assertEqual(self.client.get(url).status_code, 405)
missing = self.client.post(
url, "", content_type="application/x-www-form-urlencoded"
)
self.assertEqual(missing.status_code, 400)
unsafe = self.client.post(
url,
urlencode(
{
"sso_token": self._token(),
"redirect_path": "https://attacker.example/",
}
),
content_type="application/x-www-form-urlencoded",
)
self.assertEqual(unsafe.status_code, 400)
@override_settings(DEBUG=False)
def test_callback_alias_cannot_replay_token_used_on_canonical_url(self):
token = self._token()
self.assertEqual(self._post_callback(token).status_code, 303)
response = self.client.post(
self.callback_url.rstrip("/"),
urlencode({"sso_token": token}),
content_type="application/x-www-form-urlencoded",
)
self.assertEqual(response.status_code, 403)
def test_valid_token_creates_regular_user_identity_and_session(self):
response = self._post_callback(self._token())