Compare commits

...

4 Commits

Author SHA1 Message Date
Aleksandr Meshchryakov
d40d2c1abc fix(auth): keep SSO compatibility route out of OpenAPI 2026-09-28 11:28:11 +02:00
Aleksandr Meshchryakov
c068022705 fix(auth): accept SSO callback without trailing slash 2026-09-28 11:25:43 +02:00
avm
b37f521cd8 Merge pull request 'fix: group JSON source exports by organization (main)' (#21) from hotfix/json-source-export-20260927 into main
Some checks failed
Deploy Customer Main / Build, Push, Deploy (push) Failing after 51s
CI/CD Pipeline / Code Quality Checks (push) Successful in 1m34s
CI/CD Pipeline / Run Tests (push) Successful in 3m33s
CI/CD Pipeline / Build and Push Dev Images (push) Has been skipped
CI/CD Pipeline / Deploy Dev via Compose (push) Has been skipped
2026-09-27 11:43:48 +03:00
Aleksandr Meshchryakov
10d6a47000 fix: group JSON source exports by organization
All checks were successful
CI/CD Pipeline / Code Quality Checks (pull_request) Successful in 1m53s
CI/CD Pipeline / Run Tests (pull_request) Successful in 3m45s
CI/CD Pipeline / Build and Push Dev Images (pull_request) Has been skipped
CI/CD Pipeline / Deploy Dev via Compose (pull_request) Has been skipped
2026-09-27 10:27:06 +02:00
7 changed files with 268 additions and 23 deletions

View File

@@ -254,3 +254,11 @@ make pre-commit
Дополнительный SSO-вход включается переменной `SSO_ENABLED=true`. Публичный P-256 PEM-ключ провайдера должен быть смонтирован вне репозитория и webroot, а путь к нему передан в `SSO_PUBLIC_KEY_PATH`. Дополнительный 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-вход продолжит работать. Используются настройки `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

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

View File

@@ -8,6 +8,7 @@ import os
import re import re
import secrets import secrets
import shutil import shutil
import sqlite3
import zipfile import zipfile
from collections.abc import Iterable, Iterator, Sequence from collections.abc import Iterable, Iterator, Sequence
from dataclasses import dataclass from dataclasses import dataclass
@@ -44,7 +45,7 @@ EXPORT_FORMAT_XLSX = "xlsx"
EXPORT_FORMAT_JSON = "json" EXPORT_FORMAT_JSON = "json"
EXPORT_FORMATS = (EXPORT_FORMAT_CSV, EXPORT_FORMAT_XLSX, EXPORT_FORMAT_JSON) EXPORT_FORMATS = (EXPORT_FORMAT_CSV, EXPORT_FORMAT_XLSX, EXPORT_FORMAT_JSON)
FINANCIAL_SOURCE_GROUP = "financial_indicators" FINANCIAL_SOURCE_GROUP = "financial_indicators"
EXPORT_MANIFEST_VERSION = 2 EXPORT_MANIFEST_VERSION = 3
CURRENT_EXPORT_MANIFEST_FILE_NAME = "current.json" CURRENT_EXPORT_MANIFEST_FILE_NAME = "current.json"
GENERATION_MANIFEST_FILE_NAME = "manifest.json" GENERATION_MANIFEST_FILE_NAME = "manifest.json"
GENERATION_DIRECTORY_NAME = "generations" GENERATION_DIRECTORY_NAME = "generations"
@@ -548,6 +549,7 @@ def build_source_record_export_artifacts(
file_format=file_format, file_format=file_format,
) )
artifact_paths = _render_source_group_artifact( artifact_paths = _render_source_group_artifact(
source_group=source_group,
row_spool_path=row_spool_path, row_spool_path=row_spool_path,
output_path=staging_directory / file_name, output_path=staging_directory / file_name,
headers=headers, headers=headers,
@@ -964,6 +966,7 @@ def _spool_source_group_rows(
def _render_source_group_artifact( def _render_source_group_artifact(
*, *,
source_group: str,
row_spool_path: Path, row_spool_path: Path,
output_path: Path, output_path: Path,
headers: Sequence[str], headers: Sequence[str],
@@ -984,10 +987,87 @@ def _render_source_group_artifact(
headers=headers, headers=headers,
records_count=records_count, records_count=records_count,
) )
os.link(row_spool_path, output_path) _render_json_file(
source_group=source_group,
row_spool_path=row_spool_path,
output_path=output_path,
)
return (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]]: def _iter_spooled_rows(row_spool_path: Path) -> Iterator[dict[str, Any]]:
with row_spool_path.open("r", encoding="utf-8") as rows_file: with row_spool_path.open("r", encoding="utf-8") as rows_file:
for line in rows_file: for line in rows_file:

View File

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

View File

@@ -11,7 +11,11 @@ from apps.core.views import (
BackgroundJobStatusView, BackgroundJobStatusView,
BackgroundJobStreamView, BackgroundJobStreamView,
) )
from apps.user.sso_views import SsoCallbackView, SsoStartView from apps.user.sso_views import (
SsoCallbackView,
SsoCallbackWithoutSlashView,
SsoStartView,
)
from django.urls import include, path from django.urls import include, path
app_name = "api_v1" app_name = "api_v1"
@@ -23,6 +27,8 @@ jobs_urlpatterns = [
] ]
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/", SsoCallbackView.as_view(), name="sso-callback"),
path("auth/sso/start/", SsoStartView.as_view(), name="sso-start"), path("auth/sso/start/", SsoStartView.as_view(), name="sso-start"),
path("analytics/", include("apps.organization.analytics_root_urls")), path("analytics/", include("apps.organization.analytics_root_urls")),

View File

@@ -4,6 +4,7 @@ import json
import zipfile import zipfile
from datetime import UTC, datetime from datetime import UTC, datetime
from io import BytesIO, StringIO from io import BytesIO, StringIO
from pathlib import Path
from tempfile import TemporaryDirectory from tempfile import TemporaryDirectory
from unittest.mock import patch from unittest.mock import patch
@@ -12,6 +13,7 @@ from apps.external_data.source_record_export import (
SOURCE_GROUP_EXPORT_SPECS, SOURCE_GROUP_EXPORT_SPECS,
SOURCE_RECORD_EXPORT_FIELDS, SOURCE_RECORD_EXPORT_FIELDS,
SourceRecordExportArtifactsUnavailable, SourceRecordExportArtifactsUnavailable,
_render_json_file,
_source_group_headers, _source_group_headers,
build_source_record_export_artifacts, build_source_record_export_artifacts,
build_source_records_export_archive, build_source_records_export_archive,
@@ -39,6 +41,40 @@ from tests.apps.organization.factories import OrganizationFactory
from tests.apps.user.factories import UserFactory 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): class SourceRecordExportApiTest(APITestCase):
"""Check admin access and zero-query delivery of prepared files.""" """Check admin access and zero-query delivery of prepared files."""
@@ -121,7 +157,8 @@ class SourceRecordExportApiTest(APITestCase):
if artifact.source_group == "industrial_production" if artifact.source_group == "industrial_production"
and artifact.file_format == "json" and artifact.file_format == "json"
) )
industrial_rows = json.loads(industrial_path.read_text(encoding="utf-8")) industrial_groups = json.loads(industrial_path.read_text(encoding="utf-8"))
industrial_rows = _source_records(industrial_groups, "industrial_production")
self.assertEqual( self.assertEqual(
{row["record_type"] for row in industrial_rows}, {row["record_type"] for row in industrial_rows},
{ {
@@ -130,11 +167,8 @@ class SourceRecordExportApiTest(APITestCase):
"manufacturer_registry_entry", "manufacturer_registry_entry",
}, },
) )
self.assertEqual({row["ОКПО"] for row in industrial_rows}, {"12345678"}) self.assertEqual([group["okpo"] for group in industrial_groups], ["12345678"])
self.assertEqual( self.assertNotIn("ОКПО", industrial_rows[0])
list(industrial_rows[0])[: len(expected_prefix)],
expected_prefix,
)
self.assertNotIn("organization", industrial_rows[0]) self.assertNotIn("organization", industrial_rows[0])
self.assertIn("payload.product_name", industrial_rows[0]) self.assertIn("payload.product_name", industrial_rows[0])
@@ -143,7 +177,10 @@ class SourceRecordExportApiTest(APITestCase):
for artifact in generation.artifacts for artifact in generation.artifacts
if artifact.source_group == "financial_indicators" if artifact.source_group == "financial_indicators"
) )
financial_rows = json.loads(financial_path.read_text(encoding="utf-8")) financial_rows = _source_records(
json.loads(financial_path.read_text(encoding="utf-8")),
"financial_indicators",
)
self.assertEqual(financial_rows[0]["financial_lines"][0]["line_code"], "1600") self.assertEqual(financial_rows[0]["financial_lines"][0]["line_code"], "1600")
arbitration_path = next( arbitration_path = next(
@@ -151,7 +188,9 @@ class SourceRecordExportApiTest(APITestCase):
for artifact in generation.artifacts for artifact in generation.artifacts
if artifact.source_group == "arbitration" and artifact.file_format == "json" if artifact.source_group == "arbitration" and artifact.file_format == "json"
) )
arbitration_row = json.loads(arbitration_path.read_text(encoding="utf-8"))[0] arbitration_row = _source_records(
json.loads(arbitration_path.read_text(encoding="utf-8")), "arbitration"
)[0]
self.assertEqual(arbitration_row["source"], "arbitration") self.assertEqual(arbitration_row["source"], "arbitration")
self.assertEqual( self.assertEqual(
arbitration_row["external_id"], arbitration_row["payload.case_number"] arbitration_row["external_id"], arbitration_row["payload.case_number"]
@@ -219,7 +258,9 @@ class SourceRecordExportApiTest(APITestCase):
) )
for artifact in artifacts: for artifact in artifacts:
if artifact.file_format == "json": if artifact.file_format == "json":
exported_values = json.loads(artifact.path.read_text(encoding="utf-8")) 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")
self.assertEqual( self.assertEqual(
[key for key in exported_values[0] if key.startswith("payload.")], [key for key in exported_values[0] if key.startswith("payload.")],
[ [
@@ -244,7 +285,8 @@ class SourceRecordExportApiTest(APITestCase):
serialized_values = str(exported_values) serialized_values = str(exported_values)
self.assertIn(str(excluded_record.id), serialized_values) self.assertIn(str(excluded_record.id), serialized_values)
self.assertIn(str(included_record.id), str(exported_values)) self.assertIn(str(included_record.id), str(exported_values))
self.assertIn("11223344", str(exported_values)) if artifact.file_format != "json":
self.assertIn("11223344", str(exported_values))
self.assertNotRegex( self.assertNotRegex(
serialized_values, serialized_values,
r"(?i)(?<![a-zа-яё0-9])(?:checko(?:\.ru)?|чеко|чекало|чекко)" r"(?i)(?<![a-zа-яё0-9])(?:checko(?:\.ru)?|чеко|чекало|чекко)"
@@ -261,6 +303,17 @@ class SourceRecordExportApiTest(APITestCase):
self.assertEqual(generation.export_year, timezone.localdate().year) self.assertEqual(generation.export_year, timezone.localdate().year)
self.assertIn('"artifacts_count": 25', command_output.getvalue()) 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): def test_generation_contains_only_records_from_its_calendar_year(self):
export_year = 2026 export_year = 2026
generated_at = datetime(export_year, 8, 4, 6, 0, tzinfo=UTC) generated_at = datetime(export_year, 8, 4, 6, 0, tzinfo=UTC)
@@ -301,7 +354,10 @@ class SourceRecordExportApiTest(APITestCase):
if artifact.source_group == "government_procurements" if artifact.source_group == "government_procurements"
and artifact.file_format == "json" and artifact.file_format == "json"
) )
procurement_rows = json.loads(procurements_path.read_text(encoding="utf-8")) procurement_rows = _source_records(
json.loads(procurements_path.read_text(encoding="utf-8")),
"government_procurements",
)
self.assertEqual( self.assertEqual(
[row["uid"] for row in procurement_rows], [row["uid"] for row in procurement_rows],
[str(current_procurement.pk)], [str(current_procurement.pk)],
@@ -313,7 +369,10 @@ class SourceRecordExportApiTest(APITestCase):
if artifact.source_group == "industrial_production" if artifact.source_group == "industrial_production"
and artifact.file_format == "json" and artifact.file_format == "json"
) )
industrial_rows = json.loads(industrial_path.read_text(encoding="utf-8")) industrial_rows = _source_records(
json.loads(industrial_path.read_text(encoding="utf-8")),
"industrial_production",
)
self.assertEqual( self.assertEqual(
[row["uid"] for row in industrial_rows], [row["uid"] for row in industrial_rows],
[str(current_product.pk)], [str(current_product.pk)],
@@ -324,7 +383,10 @@ class SourceRecordExportApiTest(APITestCase):
for artifact in generation.artifacts for artifact in generation.artifacts
if artifact.source_group == "financial_indicators" if artifact.source_group == "financial_indicators"
) )
financial_rows = json.loads(financial_path.read_text(encoding="utf-8")) financial_rows = _source_records(
json.loads(financial_path.read_text(encoding="utf-8")),
"financial_indicators",
)
self.assertEqual( self.assertEqual(
[row["uid"] for row in financial_rows], [row["uid"] for row in financial_rows],
[str(current_report.pk)], [str(current_report.pk)],

View File

@@ -39,6 +39,26 @@ class SsoStartViewTest(SimpleTestCase):
{"target": ["fkc"], "path": ["/open-data?scope=rosatom"]}, {"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): def test_rejects_absolute_redirect_path(self):
response = self.client.get( response = self.client.get(
"/api/v1/auth/sso/start/", "/api/v1/auth/sso/start/",
@@ -118,6 +138,53 @@ class SsoCallbackViewTest(APITestCase):
content_type="application/x-www-form-urlencoded", 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): def test_valid_token_creates_regular_user_identity_and_session(self):
response = self._post_callback(self._token()) response = self._post_callback(self._token())