Archive the reject NUL text inputs change

This commit is contained in:
Artyom
2026-11-06 02:07:29 +03:00
parent e66e2d7d68
commit d60e29221a
18 changed files with 511 additions and 3 deletions
+5
View File
@@ -2,6 +2,11 @@ date: 2026-11-05T22:28:57.204523+00:00 commit: f591fa64e525679a31c9db7f942d36c78
# Доказательства
NUL во входных строках после повторного ревью — [review-nul-inputs/README.md](review-nul-inputs/README.md),
код `e66e2d7d685ef8cdef74b3104bd6b5550b01c0af`: 136 unit-тестов и 18 архитектурных проверок
offline, 17 HTTP-регрессий только собраны. Там же обязательные проверки финального агента;
динамические свойства и нагрузка на исправленном SHA здесь не подтверждаются.
Исправления после независимого ревью — [review-fixes/README.md](review-fixes/README.md),
код `2af24d7762a87173aa2d34c3464c64184b3ee8bf`. Здесь выполнены только offline-проверки;
ниже сохранены измерения прежнего кода. Обязательные динамические проверки нового SHA
+68
View File
@@ -0,0 +1,68 @@
date: 2026-11-06 commit: e66e2d7d685ef8cdef74b3104bd6b5550b01c0af
# NUL во входных строках — исправление повторного ревью
Исходный snapshot: `82641cbd3d03718e49701a86198bdffb35c0310e`.
Код исправлений и регрессионных тестов: `e66e2d7d685ef8cdef74b3104bd6b5550b01c0af`.
Проверки выполнялись в существующем окружении основного репозитория. Docker, серверы,
нагрузка, установка окружений и публикация на этом этапе не выполнялись.
## Исправление и доказательства
Basic username с NUL теперь отклоняется парсером до VerifyCredentials; guard возвращает
стандартный `401 unauthorized` с Basic challenge. DisplayName, ChatTitle и MessageText
отклоняют NUL своими доменными ошибками, отображаемыми в `400 invalid_request`.
При неверном тексте PostMessageHandler сохраняет проверку членства: чужой/несуществующий
чат даёт `404`, MessageLog.post не вызывается. Допустимый Unicode и пробелы сохраняются.
Пароли, SQL, схема, миграции, инфраструктура и зависимости не изменены.
Ограничение NUL в текстовых типах сверено через Context7 с
[документацией PostgreSQL 17](https://www.postgresql.org/docs/17/datatype-character.html).
- [Регрессия на старом коде](baseline-regression-corrected.txt): 19 ожидаемых падений,
3 проверки допустимого текста проходят. SHA `5c561ea` содержит только proposal поверх
snapshot ревью; исходники приложения ещё без исправления, новые тесты — working tree.
- [Первоначальная попытка](baseline-regression.txt) сохранена: те же 19 падений и 3 успеха,
но два сценария обработчика остановились на неполной заглушке Clock. После назначения
реального datetime повтор выше подтвердил отсутствие нужного пути валидации.
- [Проверки исправленного SHA](offline-checks.txt): `make check`, `make validate`,
`make lint`, `make student-test PYTEST_ARGS='-q student-tests/unit'` — 136 passed,
включая все 22 новые проверки; 18 архитектурных проверок вызваны напрямую без
database-фикстуры. OpenSpec strict — 15/15 до архивации.
- [Финализация](finalization-checks.txt): OpenSpec strict — 14/14 после синхронизации
и архивации, активных changes нет; lint успешен, diff нормативных файлов, runner/state,
зависимостей, миграций и инфраструктуры относительно исходного snapshot пуст.
- Там же: 17 HTTP-тестов `student-tests/api/test_nul_validation.py` собраны через
`--collect-only`, **не исполнены**. SQL, транзакции и ответы работающего HTTP-сервера
этим этапом не проверены. Unit-тесты guard/MessageLog используют подставные порты.
Первый `make lint` после добавления тестов нашёл строку 102 символа при лимите 100;
строка разбита, итоговые Ruff/format/ty успешны. Нормативные файлы не менялись.
## Обязательный финальный прогон
Команды ниже здесь **не выполнялись**. Runner передаёт их агенту нагрузки в чистом clone
финального SHA. Нужен разрешённый собственный compose project, свободный HTTP-порт 18083,
прочие host-порты 23000–23999 и NO_PROXY/no_proxy для localhost,127.0.0.1,::1.
1. `make student-test PYTEST_ARGS='-v student-tests/api/test_nul_validation.py'` — 17 сценариев
с реальным PostgreSQL: NUL в начале/середине/конце/единственным символом, одинаковый `401`
с неверным паролем, контрактное тело и оба X-заголовка, отсутствие созданного пользователя
или чата после `400`, пустая история после NUL, исправленное сообщение с прежним ключом
получает `201` и корректно повторяется; чужой и несуществующий чат одинаково дают `404`.
2. `make student-test` — полная регрессия, особенно сессии, negative, access, idempotency и
ранее добавленные проверки кэша. Проверить сохранение Unicode/переносов строк/табуляции.
3. На работающем стенде через LB повторить те же NUL-запросы и исправленный повтор сообщения
с тем же ключом через другую реплику; зафиксировать `X-Instance-Id`, `X-Request-Id`, статусы,
историю без дублей и отсутствие `500`. NUL в JSON передавать как `\u0000`, в Basic —
внутри Base64 синтетических credentials. Секреты и сессионные токены в evidence не писать.
4. `make test`, `make test-persistence ACTION_SCRIPT=scripts/restart.sh`,
`make test-failover ACTION_SCRIPT=scripts/stop-one.sh`, `make lb-check`, `make retry-check`
и `make test-faults` — обязательные общие сценарии финальной версии по заданию runner.
5. Сохраняются все обязательства [предыдущего исправления](../review-fixes/README.md),
включая реальные PostgreSQL/Valkey, HAProxy, rolling/failover и измерения трека «5».
Старые RPS/p95 относятся к прежнему коду; этот этап новых измерений не добавляет.
После Docker-этапа остановить только свои стенды без удаления постоянных volumes.
Финальный отчёт оформляет отдельный агент. Этот change закрывает замечание о валидации
минимума уровня «3»; выполнение динамических критериев «3»/«4»/«5» заново не заявляется.
@@ -0,0 +1,125 @@
date: 2026-11-05T23:03:20.666957+00:00 commit: 5c561eac26be15d9dca3d9f282294a351f6043e5; tests: working tree
$ .venv/bin/pytest -q --tb=short student-tests/unit/test_nul_inputs.py
FFFFFFFFFFFFFFFFF...FF [100%]
=================================== FAILURES ===================================
____________________ test_basic_rejects_nul_username[\x00] _____________________
student-tests/unit/test_nul_inputs.py:34: in test_basic_rejects_nul_username
assert basic_credentials(f"Basic {raw}") is None
E AssertionError: assert ('\x00', 'synthetic-password') is None
E + where ('\x00', 'synthetic-password') = basic_credentials('Basic ADpzeW50aGV0aWMtcGFzc3dvcmQ=')
___________________ test_basic_rejects_nul_username[\x00abc] ___________________
student-tests/unit/test_nul_inputs.py:34: in test_basic_rejects_nul_username
assert basic_credentials(f"Basic {raw}") is None
E AssertionError: assert ('\x00abc', 'synthetic-password') is None
E + where ('\x00abc', 'synthetic-password') = basic_credentials('Basic AGFiYzpzeW50aGV0aWMtcGFzc3dvcmQ=')
_________________ test_basic_rejects_nul_username[abc\x00def] __________________
student-tests/unit/test_nul_inputs.py:34: in test_basic_rejects_nul_username
assert basic_credentials(f"Basic {raw}") is None
E AssertionError: assert ('abc\x00def', 'synthetic-password') is None
E + where ('abc\x00def', 'synthetic-password') = basic_credentials('Basic YWJjAGRlZjpzeW50aGV0aWMtcGFzc3dvcmQ=')
___________________ test_basic_rejects_nul_username[abc\x00] ___________________
student-tests/unit/test_nul_inputs.py:34: in test_basic_rejects_nul_username
assert basic_credentials(f"Basic {raw}") is None
E AssertionError: assert ('abc\x00', 'synthetic-password') is None
E + where ('abc\x00', 'synthetic-password') = basic_credentials('Basic YWJjADpzeW50aGV0aWMtcGFzc3dvcmQ=')
____________ test_nul_username_is_rejected_before_credential_lookup ____________
student-tests/unit/test_nul_inputs.py:50: in test_nul_username_is_rejected_before_credential_lookup
verify.assert_not_awaited()
../../../../../.local/share/uv/python/cpython-3.14.5-macos-aarch64-none/lib/python3.14/unittest/mock.py:2471: in assert_not_awaited
raise AssertionError(msg)
E AssertionError: Expected mock to not have been awaited. Awaited 1 times.
________ test_text_values_reject_nul[DisplayName-InvalidUserData-\x00] _________
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidUserData
_______ test_text_values_reject_nul[DisplayName-InvalidUserData-\x00abc] _______
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidUserData
_____ test_text_values_reject_nul[DisplayName-InvalidUserData-abc\x00def] ______
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidUserData
_______ test_text_values_reject_nul[DisplayName-InvalidUserData-abc\x00] _______
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidUserData
_________ test_text_values_reject_nul[ChatTitle-InvalidChatData-\x00] __________
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidChatData
________ test_text_values_reject_nul[ChatTitle-InvalidChatData-\x00abc] ________
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidChatData
______ test_text_values_reject_nul[ChatTitle-InvalidChatData-abc\x00def] _______
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidChatData
________ test_text_values_reject_nul[ChatTitle-InvalidChatData-abc\x00] ________
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidChatData
_______ test_text_values_reject_nul[MessageText-InvalidMessageText-\x00] _______
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidMessageText
_____ test_text_values_reject_nul[MessageText-InvalidMessageText-\x00abc] ______
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidMessageText
____ test_text_values_reject_nul[MessageText-InvalidMessageText-abc\x00def] ____
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidMessageText
_____ test_text_values_reject_nul[MessageText-InvalidMessageText-abc\x00] ______
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidMessageText
____________ test_nul_message_checks_access_without_writing[False] _____________
student-tests/unit/test_nul_inputs.py:89: in test_nul_message_checks_access_without_writing
chats.chat_for_member.assert_awaited_once_with(command.chat_id, command.sender_id)
../../../../../.local/share/uv/python/cpython-3.14.5-macos-aarch64-none/lib/python3.14/unittest/mock.py:2404: in assert_awaited_once_with
raise AssertionError(msg)
E AssertionError: Expected chat_for_member to have been awaited once. Awaited 0 times.
_____________ test_nul_message_checks_access_without_writing[True] _____________
student-tests/unit/test_nul_inputs.py:88: in test_nul_message_checks_access_without_writing
await handler(command)
src/messenger/messaging/application/handlers.py:64: in __call__
raise ChatNotFound("чат не найден")
E messenger.messaging.domain.errors.ChatNotFound: чат не найден
=========================== short test summary info ============================
FAILED student-tests/unit/test_nul_inputs.py::test_basic_rejects_nul_username[\x00]
FAILED student-tests/unit/test_nul_inputs.py::test_basic_rejects_nul_username[\x00abc]
FAILED student-tests/unit/test_nul_inputs.py::test_basic_rejects_nul_username[abc\x00def]
FAILED student-tests/unit/test_nul_inputs.py::test_basic_rejects_nul_username[abc\x00]
FAILED student-tests/unit/test_nul_inputs.py::test_nul_username_is_rejected_before_credential_lookup
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[DisplayName-InvalidUserData-\x00]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[DisplayName-InvalidUserData-\x00abc]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[DisplayName-InvalidUserData-abc\x00def]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[DisplayName-InvalidUserData-abc\x00]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[ChatTitle-InvalidChatData-\x00]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[ChatTitle-InvalidChatData-\x00abc]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[ChatTitle-InvalidChatData-abc\x00def]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[ChatTitle-InvalidChatData-abc\x00]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[MessageText-InvalidMessageText-\x00]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[MessageText-InvalidMessageText-\x00abc]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[MessageText-InvalidMessageText-abc\x00def]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[MessageText-InvalidMessageText-abc\x00]
FAILED student-tests/unit/test_nul_inputs.py::test_nul_message_checks_access_without_writing[False]
FAILED student-tests/unit/test_nul_inputs.py::test_nul_message_checks_access_without_writing[True]
19 failed, 3 passed in 0.09s
exit: 1
@@ -0,0 +1,127 @@
date: 2026-11-05T23:03:07.667186+00:00 commit: 5c561eac26be15d9dca3d9f282294a351f6043e5; tests: working tree
$ .venv/bin/pytest -q --tb=short student-tests/unit/test_nul_inputs.py
FFFFFFFFFFFFFFFFF...FF [100%]
=================================== FAILURES ===================================
____________________ test_basic_rejects_nul_username[\x00] _____________________
student-tests/unit/test_nul_inputs.py:34: in test_basic_rejects_nul_username
assert basic_credentials(f"Basic {raw}") is None
E AssertionError: assert ('\x00', 'synthetic-password') is None
E + where ('\x00', 'synthetic-password') = basic_credentials('Basic ADpzeW50aGV0aWMtcGFzc3dvcmQ=')
___________________ test_basic_rejects_nul_username[\x00abc] ___________________
student-tests/unit/test_nul_inputs.py:34: in test_basic_rejects_nul_username
assert basic_credentials(f"Basic {raw}") is None
E AssertionError: assert ('\x00abc', 'synthetic-password') is None
E + where ('\x00abc', 'synthetic-password') = basic_credentials('Basic AGFiYzpzeW50aGV0aWMtcGFzc3dvcmQ=')
_________________ test_basic_rejects_nul_username[abc\x00def] __________________
student-tests/unit/test_nul_inputs.py:34: in test_basic_rejects_nul_username
assert basic_credentials(f"Basic {raw}") is None
E AssertionError: assert ('abc\x00def', 'synthetic-password') is None
E + where ('abc\x00def', 'synthetic-password') = basic_credentials('Basic YWJjAGRlZjpzeW50aGV0aWMtcGFzc3dvcmQ=')
___________________ test_basic_rejects_nul_username[abc\x00] ___________________
student-tests/unit/test_nul_inputs.py:34: in test_basic_rejects_nul_username
assert basic_credentials(f"Basic {raw}") is None
E AssertionError: assert ('abc\x00', 'synthetic-password') is None
E + where ('abc\x00', 'synthetic-password') = basic_credentials('Basic YWJjADpzeW50aGV0aWMtcGFzc3dvcmQ=')
____________ test_nul_username_is_rejected_before_credential_lookup ____________
student-tests/unit/test_nul_inputs.py:50: in test_nul_username_is_rejected_before_credential_lookup
verify.assert_not_awaited()
../../../../../.local/share/uv/python/cpython-3.14.5-macos-aarch64-none/lib/python3.14/unittest/mock.py:2471: in assert_not_awaited
raise AssertionError(msg)
E AssertionError: Expected mock to not have been awaited. Awaited 1 times.
________ test_text_values_reject_nul[DisplayName-InvalidUserData-\x00] _________
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidUserData
_______ test_text_values_reject_nul[DisplayName-InvalidUserData-\x00abc] _______
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidUserData
_____ test_text_values_reject_nul[DisplayName-InvalidUserData-abc\x00def] ______
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidUserData
_______ test_text_values_reject_nul[DisplayName-InvalidUserData-abc\x00] _______
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidUserData
_________ test_text_values_reject_nul[ChatTitle-InvalidChatData-\x00] __________
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidChatData
________ test_text_values_reject_nul[ChatTitle-InvalidChatData-\x00abc] ________
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidChatData
______ test_text_values_reject_nul[ChatTitle-InvalidChatData-abc\x00def] _______
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidChatData
________ test_text_values_reject_nul[ChatTitle-InvalidChatData-abc\x00] ________
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidChatData
_______ test_text_values_reject_nul[MessageText-InvalidMessageText-\x00] _______
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidMessageText
_____ test_text_values_reject_nul[MessageText-InvalidMessageText-\x00abc] ______
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidMessageText
____ test_text_values_reject_nul[MessageText-InvalidMessageText-abc\x00def] ____
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidMessageText
_____ test_text_values_reject_nul[MessageText-InvalidMessageText-abc\x00] ______
student-tests/unit/test_nul_inputs.py:62: in test_text_values_reject_nul
with pytest.raises(error):
^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE InvalidMessageText
____________ test_nul_message_checks_access_without_writing[False] _____________
student-tests/unit/test_nul_inputs.py:86: in test_nul_message_checks_access_without_writing
await handler(command)
src/messenger/messaging/application/handlers.py:62: in __call__
receipt = await self._log.post(draft, command.key, command.fingerprint, now - self._ttl)
^^^^^^^^^^^^^^^
E TypeError: unsupported operand type(s) for -: 'Mock' and 'datetime.timedelta'
_____________ test_nul_message_checks_access_without_writing[True] _____________
student-tests/unit/test_nul_inputs.py:86: in test_nul_message_checks_access_without_writing
await handler(command)
src/messenger/messaging/application/handlers.py:62: in __call__
receipt = await self._log.post(draft, command.key, command.fingerprint, now - self._ttl)
^^^^^^^^^^^^^^^
E TypeError: unsupported operand type(s) for -: 'Mock' and 'datetime.timedelta'
=========================== short test summary info ============================
FAILED student-tests/unit/test_nul_inputs.py::test_basic_rejects_nul_username[\x00]
FAILED student-tests/unit/test_nul_inputs.py::test_basic_rejects_nul_username[\x00abc]
FAILED student-tests/unit/test_nul_inputs.py::test_basic_rejects_nul_username[abc\x00def]
FAILED student-tests/unit/test_nul_inputs.py::test_basic_rejects_nul_username[abc\x00]
FAILED student-tests/unit/test_nul_inputs.py::test_nul_username_is_rejected_before_credential_lookup
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[DisplayName-InvalidUserData-\x00]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[DisplayName-InvalidUserData-\x00abc]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[DisplayName-InvalidUserData-abc\x00def]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[DisplayName-InvalidUserData-abc\x00]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[ChatTitle-InvalidChatData-\x00]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[ChatTitle-InvalidChatData-\x00abc]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[ChatTitle-InvalidChatData-abc\x00def]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[ChatTitle-InvalidChatData-abc\x00]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[MessageText-InvalidMessageText-\x00]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[MessageText-InvalidMessageText-\x00abc]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[MessageText-InvalidMessageText-abc\x00def]
FAILED student-tests/unit/test_nul_inputs.py::test_text_values_reject_nul[MessageText-InvalidMessageText-abc\x00]
FAILED student-tests/unit/test_nul_inputs.py::test_nul_message_checks_access_without_writing[False]
FAILED student-tests/unit/test_nul_inputs.py::test_nul_message_checks_access_without_writing[True]
19 failed, 3 passed in 0.08s
exit: 1
@@ -0,0 +1,47 @@
date: 2026-11-05T23:07:18.897766+00:00 commit: e66e2d7d685ef8cdef74b3104bd6b5550b01c0af; OpenSpec/evidence documentation worktree
$ openspec validate --all --strict
✓ spec/lab1-event-publication
✓ spec/lab1-messenger-chats
✓ spec/lab1-messenger-history
✓ spec/lab1-messenger-identity
✓ spec/lab1-service-operability
✓ spec/lab2-auth-sessions
✓ spec/lab2-dependency-failures
✓ spec/lab2-history-index
✓ spec/lab2-persistent-storage
✓ spec/lab2-session-cache
✓ spec/lab3-failover-operations
✓ spec/lab3-idempotent-messages
✓ spec/lab3-load-balancing
✓ spec/lab3-scaling-cost
Totals: 14 passed, 0 failed (14 items)
- Validating...
exit: 0
$ openspec list --json
{
"changes": [],
"root": {
"path": "<repo>",
"source": "nearest"
}
}
exit: 0
$ git diff --check
exit: 0
$ git diff 82641cbd3d03718e49701a86198bdffb35c0310e --exit-code -- contracts tests README.md COURSE.md .pipeline pyproject.toml uv.lock alembic infra compose.yaml
exit: 0
$ make lint
.venv/bin/ruff check src student-tests alembic scripts/probe.py scripts/limits.py scripts/scaling.py tools
All checks passed!
.venv/bin/ruff format --check src student-tests alembic scripts/probe.py scripts/limits.py scripts/scaling.py tools
113 files already formatted
.venv/bin/ty check src student-tests alembic
All checks passed!
exit: 0
@@ -0,0 +1,97 @@
date: 2026-11-05T23:05:24.813684+00:00 commit: e66e2d7d685ef8cdef74b3104bd6b5550b01c0af
$ make check
python3 scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
exit: 0
$ make validate
.venv/bin/python scripts/validate_openapi.py
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
exit: 0
$ make lint
.venv/bin/ruff check src student-tests alembic scripts/probe.py scripts/limits.py scripts/scaling.py tools
All checks passed!
.venv/bin/ruff format --check src student-tests alembic scripts/probe.py scripts/limits.py scripts/scaling.py tools
113 files already formatted
.venv/bin/ty check src student-tests alembic
All checks passed!
exit: 0
$ make student-test 'PYTEST_ARGS=-q student-tests/unit'
.venv/bin/pytest -q student-tests/unit
........................................................................ [ 52%]
................................................................ [100%]
136 passed in 0.11s
exit: 0
$ .venv/bin/python -c 'import runpy
scope = runpy.run_path('"'"'student-tests/api/test_bounded_contexts.py'"'"')
tests = [(name, fn) for name, fn in scope.items() if name.startswith('"'"'test_'"'"')]
for name, fn in tests:
fn()
print('"'"'PASS'"'"', name)
print(len(tests), '"'"'architecture checks passed without database fixtures'"'"')'
PASS test_identity_does_not_know_about_messaging
PASS test_domains_do_not_import_infrastructure
PASS test_core_layers_do_not_import_pydantic
PASS test_shared_knows_nothing_about_zones
PASS test_shared_core_is_free_of_transport
PASS test_shared_core_holds_only_platform
PASS test_shared_entrypoints_hold_only_transport
PASS test_every_zone_owns_its_errors_events_and_commands
PASS test_every_zone_owns_its_http_layer
PASS test_only_main_knows_both_zones
PASS test_application_has_no_separate_entrypoints_root
PASS test_shared_source_mentions_no_domain_vocabulary
PASS test_shared_declares_no_concrete_commands_or_events
PASS test_shared_has_no_test_doubles
PASS test_zone_errors_do_not_leak_transport_codes
PASS test_sql_of_each_zone_reads_only_its_tables
PASS test_messaging_does_not_import_identity_at_all
PASS test_sqlalchemy_stays_in_infrastructure_and_asyncpg_is_only_a_driver
18 architecture checks passed without database fixtures
exit: 0
$ .venv/bin/pytest --collect-only -q student-tests/api/test_nul_validation.py
student-tests/api/test_nul_validation.py::test_nul_basic_matches_wrong_password[\x00]
student-tests/api/test_nul_validation.py::test_nul_basic_matches_wrong_password[\x00abc]
student-tests/api/test_nul_validation.py::test_nul_basic_matches_wrong_password[abc\x00def]
student-tests/api/test_nul_validation.py::test_nul_basic_matches_wrong_password[abc\x00]
student-tests/api/test_nul_validation.py::test_nul_display_name_does_not_create_user[\x00]
student-tests/api/test_nul_validation.py::test_nul_display_name_does_not_create_user[\x00abc]
student-tests/api/test_nul_validation.py::test_nul_display_name_does_not_create_user[abc\x00def]
student-tests/api/test_nul_validation.py::test_nul_display_name_does_not_create_user[abc\x00]
student-tests/api/test_nul_validation.py::test_nul_title_does_not_create_chat[\x00]
student-tests/api/test_nul_validation.py::test_nul_title_does_not_create_chat[\x00abc]
student-tests/api/test_nul_validation.py::test_nul_title_does_not_create_chat[abc\x00def]
student-tests/api/test_nul_validation.py::test_nul_title_does_not_create_chat[abc\x00]
student-tests/api/test_nul_validation.py::test_nul_message_does_not_take_key[\x00]
student-tests/api/test_nul_validation.py::test_nul_message_does_not_take_key[\x00abc]
student-tests/api/test_nul_validation.py::test_nul_message_does_not_take_key[abc\x00def]
student-tests/api/test_nul_validation.py::test_nul_message_does_not_take_key[abc\x00]
student-tests/api/test_nul_validation.py::test_nul_message_does_not_disclose_chat
17 tests collected in 0.01s
exit: 0
$ openspec validate --all --strict
✓ spec/lab1-event-publication
✓ spec/lab1-messenger-chats
✓ spec/lab1-messenger-history
✓ spec/lab1-messenger-identity
✓ spec/lab1-service-operability
✓ spec/lab2-auth-sessions
✓ spec/lab2-dependency-failures
✓ spec/lab2-history-index
✓ spec/lab2-persistent-storage
✓ spec/lab2-session-cache
✓ spec/lab3-failover-operations
✓ spec/lab3-idempotent-messages
✓ spec/lab3-load-balancing
✓ spec/lab3-scaling-cost
✓ change/reject-nul-text-inputs
Totals: 15 passed, 0 failed (15 items)
- Validating...
exit: 0
@@ -1,2 +1,4 @@
schema: spec-driven
created: 2026-11-06
archived: 2026-11-06
lab: 3
@@ -4,7 +4,7 @@
Сервис SHALL принимать `POST /api/v1/auth/sessions` только с заголовком `Authorization: Basic <base64(username:password)>` и без тела. Декодирование base64 SHALL быть строгим, разделителем SHALL служить первое двоеточие, пароль SHALL декодироваться как UTF-8. При верных учётных данных ответ SHALL быть `201` с телом `{"token","token_type":"Bearer","expires_at","user"}`, где `token` — непрозрачная случайная строка не короче 32 символов с энтропией не менее 256 бит, `expires_at` — RFC 3339 UTC с `Z`, а `user` совпадает с ответом регистрации. Неверный пароль, неизвестный `username`, отсутствующий и испорченный заголовок SHALL давать одинаковый `401` с кодом `unauthorized` и заголовком `WWW-Authenticate: Basic realm="messenger", charset="UTF-8"`.
В соответствии с разделом «Идентификация и аутентификация» `contracts/README.md`, NUL в Basic username SHALL приводить к тому же `401 unauthorized`.
В соответствии с разделом «Идентификация и сессии» `contracts/README.md`, NUL в Basic username SHALL приводить к тому же `401 unauthorized`.
#### Scenario: Успешный вход
@@ -11,5 +11,5 @@
## 3. Проверки и передача финальному агенту
- [x] 3.1 Добавить HTTP-тесты NUL: одинаковый 401, отсутствие побочных записей, исправленный повтор с прежним ключом и 404 для постороннего; собрать их через pytest --collect-only без Docker.
- [ ] 3.2 Выполнить unit-тесты и архитектурные проверки, make check, make validate, make lint и OpenSpec strict; сохранить команды, SHA и ограничения в новом evidence.
- [ ] 3.3 Передать обязательные динамические проверки финальному агенту через evidence, синхронизировать спецификации и архивировать change.
- [x] 3.2 Выполнить unit-тесты и архитектурные проверки, make check, make validate, make lint и OpenSpec strict; сохранить команды, SHA и ограничения в новом evidence.
- [x] 3.3 Передать обязательные динамические проверки финальному агенту через evidence, синхронизировать спецификации и архивировать change.
@@ -7,6 +7,8 @@
Сервис SHALL принимать `POST /api/v1/chats` от аутентифицированного пользователя с телом `{"title":..., "member_ids":[...]}` и возвращать `201` с объектом `Chat`. `title` SHALL содержать от 1 до 100 code points и не состоять только из пробельных символов. `member_ids` SHALL содержать от 1 до 100 уникальных идентификаторов существующих пользователей и SHALL включать вызывающего. Чат SHALL создаваться атомарно: при любой ошибке валидации он не создаётся вовсе.
По правилам неверных полей и атомарного создания из `contracts/README.md`, `title` SHALL NOT содержать NUL.
#### Scenario: Чат создан
- **WHEN** участник отправляет `POST /api/v1/chats` с корректным `title` и списком из своего и чужого идентификаторов
@@ -34,6 +36,12 @@
- **WHEN** `POST /api/v1/chats` приходит без `Authorization: Bearer` или с недействительным токеном
- **THEN** ответ `401` с кодом `unauthorized` и `WWW-Authenticate: Bearer realm="messenger"`
#### Scenario: NUL в названии чата
- **WHEN** аутентифицированный пользователь отправляет `POST /api/v1/chats` с NUL в `title` и корректными участниками
- **THEN** ответ `400` с телом `{"error":{"code":"invalid_request","message":...,"request_id":...}}`; чат не появляется в списке
- **AND** ответ содержит непустые `X-Instance-Id` и `X-Request-Id`, совпадающий с `error.request_id`
### Requirement: Членство как граница доступа
Чат SHALL быть доступен только своим участникам. Посторонний пользователь SHALL получать `404` с кодом `not_found` — тот же ответ, что и для несуществующего чата. Сервис SHALL NOT использовать `403` и SHALL NOT раскрывать факт существования чужого чата ни кодом ответа, ни текстом сообщения.
@@ -7,6 +7,8 @@
Сервис SHALL принимать `POST /api/v1/chats/{chat_id}/messages` от участника чата с телом `{"text":...}` и обязательным заголовком `Idempotency-Key` и возвращать `201` с объектом `Message`. Отправитель SHALL выводиться из предъявленной идентификации; поле `sender_id` в теле запроса SHALL NOT приниматься. `text` SHALL содержать от 1 до 4000 Unicode code points и SHALL NOT состоять только из пробельных символов. `id` и `created_at` SHALL назначаться сервером. Правила ключа описаны в `lab3-idempotent-messages`.
По правилам неверных полей, доступа и идемпотентности из `contracts/README.md`, `text` SHALL NOT содержать NUL; отклонённая запись SHALL NOT занимать `Idempotency-Key`.
#### Scenario: Сообщение отправлено
- **WHEN** участник отправляет `{"text":"Привет, мир 👋"}` в свой чат с новым `Idempotency-Key`
@@ -45,6 +47,17 @@
- **WHEN** посторонний отправляет в чужой чат с ключом тело с пустым `text`
- **THEN** ответ `404`, а не `400`
#### Scenario: NUL в тексте сообщения
- **WHEN** участник отправляет `POST /api/v1/chats/{chat_id}/messages` с NUL в `text` и новым корректным `Idempotency-Key`
- **THEN** ответ `400` с телом `{"error":{"code":"invalid_request","message":...,"request_id":...}}`; история не меняется, исправленное сообщение с тем же ключом получает `201`, повтор возвращает тот же объект
- **AND** ответ содержит непустые `X-Instance-Id` и `X-Request-Id`, совпадающий с `error.request_id`
#### Scenario: NUL не раскрывает чужой чат
- **WHEN** посторонний отправляет сообщение с NUL в чужой или несуществующий чат с корректным ключом
- **THEN** ответ `404 not_found` в стандартном теле ошибки с `X-Instance-Id` и `X-Request-Id`; записи нет
### Requirement: Порядок истории
История чата SHALL быть упорядочена по паре `(created_at, id)` по возрастанию. Время SHALL назначаться сервером в формате RFC 3339 UTC с суффиксом `Z`. Сервис SHALL гарантировать, что `created_at` внутри одного чата строго возрастает в порядке фиксации сообщений, в том числе при конкурентных вставках через разные процессы API, — иначе обход истории keyset-курсором теряет запись, зафиксированную позже с меньшей отметкой.
@@ -7,6 +7,8 @@
Сервис SHALL принимать `POST /api/v1/users` без аутентификации и возвращать `201` с объектом `User`, содержащим назначенные сервером `id` и `created_at`. Тело запроса SHALL содержать ровно поля `username`, `display_name` и `password`. `username` SHALL соответствовать `^[a-z0-9_]{3,32}$` и быть уникальным, `display_name` SHALL содержать от 1 до 100 Unicode code points и не состоять только из пробельных символов, требования к `password` задаёт `lab2-auth-sessions`. Ответ SHALL NOT содержать полей, отсутствующих в схеме `User`. Уникальность SHALL соблюдаться и при конкурентной регистрации одного `username`: успешной будет ровно одна, остальные получат `409`.
По правилам неверных полей и ошибок из `contracts/README.md`, `display_name` SHALL NOT содержать NUL.
#### Scenario: Пользователь создан
- **WHEN** приходит `POST /api/v1/users` с телом `{"username":"alice_01","display_name":"Алиса","password":"<12+ символов>"}`
@@ -39,6 +41,12 @@
- **WHEN** `POST /api/v1/users` приходит без заголовка `Authorization`
- **THEN** запрос обрабатывается на общих основаниях, ответ не равен `401`
#### Scenario: NUL в отображаемом имени
- **WHEN** `POST /api/v1/users` содержит NUL в `display_name`
- **THEN** ответ `400` с телом `{"error":{"code":"invalid_request","message":...,"request_id":...}}`; пользователь не создаётся, повтор с корректным именем и тем же username может дать `201`
- **AND** ответ содержит непустые `X-Instance-Id` и `X-Request-Id`, совпадающий с `error.request_id`
### Requirement: Чтение текущего пользователя
Сервис SHALL отдавать по `GET /api/v1/users/me` объект `User` владельца предъявленной `Bearer`-сессии в том же виде, в каком он был возвращён при регистрации.
@@ -31,6 +31,8 @@
Сервис SHALL принимать `POST /api/v1/auth/sessions` только с заголовком `Authorization: Basic <base64(username:password)>` и без тела. Декодирование base64 SHALL быть строгим, разделителем SHALL служить первое двоеточие, пароль SHALL декодироваться как UTF-8. При верных учётных данных ответ SHALL быть `201` с телом `{"token","token_type":"Bearer","expires_at","user"}`, где `token` — непрозрачная случайная строка не короче 32 символов с энтропией не менее 256 бит, `expires_at` — RFC 3339 UTC с `Z`, а `user` совпадает с ответом регистрации. Неверный пароль, неизвестный `username`, отсутствующий и испорченный заголовок SHALL давать одинаковый `401` с кодом `unauthorized` и заголовком `WWW-Authenticate: Basic realm="messenger", charset="UTF-8"`.
В соответствии с разделом «Идентификация и сессии» `contracts/README.md`, NUL в Basic username SHALL приводить к тому же `401 unauthorized`.
#### Scenario: Успешный вход
- **WHEN** зарегистрированный пользователь отправляет верные `username:password` в `Basic`
@@ -58,6 +60,12 @@
- **WHEN** запрос с верным `Basic` содержит тело
- **THEN** ответ `400` с кодом `invalid_request`, сессия не создаётся
#### Scenario: Username с NUL
- **WHEN** в `POST /api/v1/auth/sessions` передан корректный Base64 от username с NUL и пароля
- **THEN** ответ `401` с `WWW-Authenticate: Basic realm="messenger", charset="UTF-8"`; тело `{"error":{"code":"unauthorized","message":...,"request_id":...}}` совпадает с ошибкой неверного пароля, кроме `request_id`
- **AND** ответ содержит непустые `X-Instance-Id` и `X-Request-Id`, совпадающий с `error.request_id`
### Requirement: Защищённые endpoint принимают только Bearer
Все `/api/v1/*`, кроме `POST /api/v1/users` и `POST /api/v1/auth/sessions`, SHALL требовать `Authorization: Bearer <token>`; схема сравнивается без учёта регистра. Отсутствующий, неизвестный, истёкший и отозванный токен, а также `Basic` на этих endpoint SHALL давать `401` с кодом `unauthorized` и `WWW-Authenticate: Bearer realm="messenger"`. Заголовок `X-User-Id` SHALL игнорироваться: он не даёт доступа и не меняет владельца сессии. Аутентификация SHALL выполняться раньше проверки доступа к ресурсу и раньше валидации пути, параметров и тела.