feat: define shared event and IPC contracts
This commit is contained in:
1 parent
e0a7e35674
commit
0745c5e767
15 files changed
+1214
-14
No files matched your search
@@ -0,0 +1,116 @@
|
||||
# LabStand Contracts 1
|
||||
|
||||
Общий пакет `labstand-contracts==0.1.0`, Python ≥3.10, только стандартная библиотека. Один исходный код и одни примеры используются производителями RPi и потребителями Windows. На этапе 2 пакет ещё не подключён к GPIO/UART и действующим обработчикам стенда. Совместимость с установленным Python на RPi проверим при включении стенда; аппаратные импорты для этого пакета не нужны.
|
||||
|
||||
## API
|
||||
|
||||
```python
|
||||
from labstand_contracts import Event, ContractError
|
||||
|
||||
event = Event.from_json(raw_bytes)
|
||||
payload = event.to_dict()
|
||||
identity = event.identity
|
||||
position = event.position
|
||||
encoded_bytes = event.to_json()
|
||||
```
|
||||
|
||||
`Event`, `DetectionResult`, `ErrorMessage`, `IPCRequest`, `IPCResponse` принимают словарь в конструкторе либо один JSON-объект UTF-8 в `from_json(bytes | str)`. Проверка выполняется при создании. Модель хранит неизменяемый снимок; `to_dict()` возвращает независимую копию. `to_json()` возвращает байты без перевода строки. Писатель JSONL добавит `b'\n'` на этапе 6. BOM, несколько объектов в одном входе, повторы ключей на любой глубине и нечисловые NaN/Infinity запрещены.
|
||||
|
||||
`ContractError` содержит машинный `code` и `path`, например `missing_field: $.event_id`; исходные значения и секреты в ошибку не вставляются. Ошибки валидации: `invalid_type`, `invalid_value`, `missing_field`, `unknown_field`, `unsupported_version`, `invalid_encoding`, `invalid_json`, `duplicate_key`, `duplicate_value`, `limit_exceeded`, `invalid_response`, `system_tag_requires_system_event`.
|
||||
|
||||
Это **структурная проверка**, не аутентификация и не детекция. Поле origin/source не удостоверяет отправителя. MAC, ключи, канонизация для подписи и проверка контрольных точек относятся к этапу 5; обычную JSON-сериализацию этого пакета пока нельзя считать криптографическим контрактом. Подлинность IPC-отправителя и разрешения операций обеспечит этап 3/4. Проверку наличия доказательств, последовательности между записями и конфликтов идентификаторов выполнит хранилище.
|
||||
|
||||
## Общие ограничения
|
||||
|
||||
- `schema_version` — целое число 1; bool не принимается за число. Неизвестная версия, поле или enum отклоняются. Новая несовместимая структура потребует новой версии схемы и явной поддержки потребителем.
|
||||
- Событие и ErrorMessage — не более 8192 байт; результат и IPC — не более 65536 байт. При `from_json` считаются все входные UTF-8 байты, включая пробелы/перевод строки; при создании из dict — компактная сериализация. Вложенное событие также проверяется на свой предел. Лимит будущего MAC-конверта задаётся отдельно на этапе 5.
|
||||
- Не более 8 уровней вложенности (корень — 0), 2048 значений, 2048 символов в строке. Конечные float разрешены общим JSON-декодером, но текущие числовые поля схем принимают только int. Целые в пределах ±(2^63−1), большинство полей неотрицательные. Управляющие символы и одиночные Unicode-суррогаты в текстовых полях запрещены.
|
||||
- Идентификатор: ASCII `[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}`. UUID: каноническая нижнерегистровая запись с дефисами; пакет не генерирует UUID и не доказывает уникальность.
|
||||
- Время: `YYYY-MM-DDTHH:MM:SS[.ffffff]Z` или явное смещение; системное — UTC (`Z`/`+00:00`), симулированное — МСК (`+03:00`). Проверяется календарная дата, точность до микросекунд; naive datetime и отрицательное неизвестное смещение `-00:00` не принимаются. Сравнение календаря и рабочих часов — этап 12.
|
||||
- Ограничения должны применяться и транспортом до накопления полного входа. Декодер принимает уже полученные байты, не заменяет ограниченную очередь/потоковый фрейминг.
|
||||
|
||||
## Event: обязательные поля
|
||||
|
||||
| Поля | Тип / назначение |
|
||||
| --- | --- |
|
||||
| schema_version, stand_id | Версия 1 и идентификатор стенда |
|
||||
| event_id | UUID записи; дедупликация по `(stand_id, event_id)` |
|
||||
| journal_generation, session_id | UUID поколения журнала и процесса-производителя; Windows использует собственные значения |
|
||||
| sequence | Положительное int, порядок внутри сессии; `.position` = `(stand_id, origin, journal_generation, session_id, sequence)` |
|
||||
| monotonic_ms | Неотрицательное время от старта производителя для технических интервалов; между сессиями не сравнивается |
|
||||
| timestamp_sys, timestamp_sim | UTC источника и sim_clock МСК. У локальной диагностики Windows sim может отсутствовать (`null`) |
|
||||
| sim_epoch | Неотрицательное int; `null` тогда и только тогда, когда timestamp_sim = null; у RPi обе метки обязательны |
|
||||
| stand_mode | RUNNING, FREEZING, FROZEN, RESUMING, STOPPED, UNKNOWN |
|
||||
| origin, source | rpi/windows и источник из каталога ниже. Windows допускает только system/logger/collector |
|
||||
| event_type | Тип из закрытого каталога; source должен соответствовать типу |
|
||||
| correlation_id | UUID связанной операции либо null |
|
||||
| policy_version | Идентификатор версии политики производителя (не версия правила детектора) |
|
||||
| details | Строгая структура конкретного типа; не произвольный объект |
|
||||
|
||||
`identity` не меняется от времени, sequence или повторной доставки. Две записи с одним identity, но разным содержимым — конфликт хранилища, а не автоматически одна и та же запись. Схема сама не хранит историю и не проверяет рост sequence. Переходы epoch/generation и полномочия их изменения проверяются соответствующим доменом.
|
||||
|
||||
## Каталог details
|
||||
|
||||
Все перечисленные поля обязательны, кроме явно отмеченных. Текст — непустая строка, код/действие/причина типа identifier — короткий идентификатор. `pc_id` = 1..3, `channel` = 1..2. Полный исполняемый контракт — `src/labstand_contracts/models.py`, общий набор JSON — `examples/`.
|
||||
|
||||
| Тип / source | Поля details |
|
||||
| --- | --- |
|
||||
| RFID_SCAN / rfid | channel, device (turnstile для 1, director_lock для 2), uid (8/14/20 заглавных hex-символов), role (employee/director/guard/unknown), result (granted/denied), reason (identifier) |
|
||||
| SYSTEM_STOP_REQUEST / system | reason = system_tag, uid = A1CE8B0D, channel. Этот UID запрещён в RFID_SCAN, чтобы он не попадал в обычные счётчики |
|
||||
| IR_COMMAND / ir | code (uint32), action (identifier), result (executed/ignored/failed) |
|
||||
| RADIO_COMMAND / radio | code (uint32), burst_id (UUID), count (1..65535), recognized (bool), action (identifier), result (executed/debounced/ignored/failed). power/RSSI отсутствуют |
|
||||
| LIGHTING_CHANGED / lighting | action (identifier), enabled_before/after (bool); необязательный mode (identifier) |
|
||||
| ACCESS_POINT / access | device (turnstile/barrier/gate/director_lock), action (identifier), result (requested/executed/failed/observed); необязательные hall_a0/hall_a1 (0/1) |
|
||||
| PC_POWER/BOOT/SHUTDOWN/REBOOT / pc | pc_id, reason (identifier) |
|
||||
| OS_BSOD / os | pc_id, reason (identifier) |
|
||||
| USB_CONNECTED/DISCONNECTED / usb | pc_id, usb_session_id (UUID), device_type = keyboard; необязательные vendor_id/product_id (uint16) |
|
||||
| OS_COMMAND / os | pc_id, usb_session_id (UUID/null), command (текст) |
|
||||
| OS_APP_OPEN/CLOSE / os | pc_id, usb_session_id (UUID/null), app (identifier) |
|
||||
| SIM_TIME_CHANGED / clock | before/after (МСК), reason (identifier) |
|
||||
| FREEZE_BEGIN/READY/END/FAILED / clock | freeze_id (UUID), reason (identifier), participants (до 16 уникальных идентификаторов) |
|
||||
| LOG_GAP / logger | reason (identifier), lost_count (неотрицательное int/null, если неизвестно) |
|
||||
| MANUAL_RESET / logger | actor (identifier), reason (текст), old_generation/new_generation (UUID) |
|
||||
| RETENTION_PRUNE / logger | reason = age, removed_records (неотрицательное int); очистка по capacity не разрешена |
|
||||
| POLICY_CHANGED / system | actor, before, after (identifier) |
|
||||
| SYSTEM_START/STOP/ERROR, WATCHDOG_TRIGGERED, I2C_RECOVERY / system | component/code (identifier), message (текст), state (ok/degraded/unavailable/unknown) |
|
||||
| ESP_CONNECTED/DISCONNECTED, UART_ERROR / esp | Те же component/code/message/state |
|
||||
| LOGGER_HEALTH / logger; COLLECTOR_HEALTH / collector | Те же component/code/message/state; STORAGE_FULL и CLOCK_UNTRUSTED передаются как code |
|
||||
|
||||
Схема не вычисляет авторизацию по UID и не доверяет заявленной роли: её назначает D3. Метка системной остановки разрешена во всех stand_mode. Обычные события вне RUNNING схема может представить для диагностики несогласованности источника, но D2/D3/D9 обязаны запрещать исполнение/учебную детекцию; валидность JSON не означает разрешение действия. Разделение статусов confirmed/ложное срабатывание оператора будет отдельным контрактом аннотаций, исходное событие не редактируется.
|
||||
|
||||
## DetectionResult
|
||||
|
||||
Обязательны schema_version, stand_id, result_id (UUID), rule_id/rule_version (identifier), classification (suspicious/fault/system/normal), severity (info/low/medium/high/critical), timestamp_sys (UTC), timestamp_sim (МСК/null), event_ids (1..64 уникальных UUID того же стенда), reason (текст), data_complete (bool), fault.
|
||||
|
||||
`fault` обязателен как объект только для classification=fault, иначе строго null. Поля объекта: component/code (identifier), state (active/resolved/unknown), first_seen_sys/last_seen_sys (UTC, последнее не раньше первого), occurrences (положительное int). Синий цвет назначает UI по classification, не источник. severity независим от класса. Начало и последнее наблюдение — физическое время для диагностики; timestamp_sim остаётся справочным контекстом такого сбоя.
|
||||
|
||||
Источник не присылает attack_detected/classification внутри Event: такие лишние поля отклоняются. Результат создаётся детектором. Существование event_ids, отсутствие запрещённых доказательств вроде системной метки и воспроизводимость результата проверит движок/хранилище; этап 2 не реализует эти компоненты.
|
||||
|
||||
## ErrorMessage и IPC v1
|
||||
|
||||
ErrorMessage: schema_version, code (invalid_request/unsupported_version/unauthorized/conflict/unavailable/internal_error), message (текст без исходных чувствительных данных), retryable (bool). Это ошибка запроса, а не автоматически fault-инцидент IDS. Исключение ContractError можно преобразовать в ErrorMessage на границе сервиса; автоматического преобразования с передачей сырого payload нет.
|
||||
|
||||
IPCRequest: schema_version, request_id (UUID), operation, payload. IPCResponse: schema_version, request_id, operation, status (ok/error), result, error. При ok error=null и result соответствует операции; при error result=null и error — ErrorMessage. `.matches(request)` проверяет пару request_id/operation; отправителя и разрешения он не проверяет.
|
||||
|
||||
| Операция | payload запроса | result успешного ответа |
|
||||
| --- | --- | --- |
|
||||
| events.append | events: 1..32 валидных Event | accepted: int 0..32 |
|
||||
| results.append | results: 1..32 валидных DetectionResult | accepted: int 0..32 |
|
||||
| events.query | limit: 1..100, cursor: identifier/null, event_type: известный тип/null | items: 0..100 Event, next_cursor: identifier/null |
|
||||
| results.query | limit: 1..100, cursor: identifier/null, classification: класс/null | items: 0..100 DetectionResult, next_cursor: identifier/null |
|
||||
| health.get | пустой объект | component: identifier, state: ok/degraded/unavailable/unknown |
|
||||
|
||||
Общий лимит 64 КиБ действует даже если количество записей допустимо; большие выборки разбиваются на страницы. accepted не может превышать размер реального запроса — это проверка сервиса вместе с атомарностью записи, не автономной схемы ответа. Сырые SQL, команды оболочки, GPIO, заявленные sender/role, неизвестные операции и произвольные поля отклоняются. Правила, ручной сброс и freeze-протокол будут добавляться явно на своих этапах, сейчас их нет в IPC API. UART ESP32 остаётся отдельным протоколом этапа 7; этот пакет не заменяет ArduinoJson-пакеты готовой прошивки.
|
||||
|
||||
## Установка и проверка
|
||||
|
||||
Из корня проекта с уже подготовленным окружением этапа 1:
|
||||
|
||||
```powershell
|
||||
office-ids-windows\.venv\Scripts\python.exe -m pip install --no-build-isolation --no-deps -e shared/contracts
|
||||
office-ids-windows\.venv\Scripts\python.exe -m pip install --no-build-isolation --no-deps -e office-ids-windows
|
||||
cd office-ids-windows
|
||||
.venv\Scripts\python.exe -m pytest
|
||||
```
|
||||
|
||||
На RPi устанавливается **только** shared/contracts, не Windows-проект. Общие тесты расположены в `shared/contracts/tests`, примеры в `shared/contracts/examples`. В дальнейшем один и тот же набор запускается на RPi без изменений; отсутствие аппаратной проверки сейчас не означает проверенную совместимость развёрнутого стенда.
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"code": "unavailable",
|
||||
"message": "Хранилище временно недоступно",
|
||||
"retryable": true
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
[
|
||||
{
|
||||
"schema_version": 1,
|
||||
"stand_id": "labstand-01",
|
||||
"session_id": "10000000-0000-4000-8000-000000000001",
|
||||
"journal_generation": "20000000-0000-4000-8000-000000000001",
|
||||
"event_id": "40000000-0000-4000-8000-000000000001",
|
||||
"sequence": 1,
|
||||
"monotonic_ms": 1000,
|
||||
"timestamp_sys": "2026-12-03T09:30:00Z",
|
||||
"timestamp_sim": "2026-12-03T12:30:00+03:00",
|
||||
"sim_epoch": 0,
|
||||
"stand_mode": "RUNNING",
|
||||
"origin": "rpi",
|
||||
"source": "rfid",
|
||||
"event_type": "RFID_SCAN",
|
||||
"correlation_id": "30000000-0000-4000-8000-000000000001",
|
||||
"policy_version": "access-1",
|
||||
"details": {
|
||||
"channel": 2,
|
||||
"device": "director_lock",
|
||||
"uid": "2EF588F2",
|
||||
"role": "employee",
|
||||
"result": "denied",
|
||||
"reason": "uid_not_authorized_for_channel"
|
||||
}
|
||||
},
|
||||
{
|
||||
"schema_version": 1,
|
||||
"stand_id": "labstand-01",
|
||||
"session_id": "10000000-0000-4000-8000-000000000001",
|
||||
"journal_generation": "20000000-0000-4000-8000-000000000001",
|
||||
"event_id": "40000000-0000-4000-8000-000000000002",
|
||||
"sequence": 2,
|
||||
"monotonic_ms": 1000,
|
||||
"timestamp_sys": "2026-12-03T09:30:00Z",
|
||||
"timestamp_sim": "2026-12-03T12:30:00+03:00",
|
||||
"sim_epoch": 0,
|
||||
"stand_mode": "RUNNING",
|
||||
"origin": "rpi",
|
||||
"source": "ir",
|
||||
"event_type": "IR_COMMAND",
|
||||
"correlation_id": "30000000-0000-4000-8000-000000000001",
|
||||
"policy_version": "access-1",
|
||||
"details": {
|
||||
"code": 3108437760,
|
||||
"action": "toggle_enabled",
|
||||
"result": "executed"
|
||||
}
|
||||
},
|
||||
{
|
||||
"schema_version": 1,
|
||||
"stand_id": "labstand-01",
|
||||
"session_id": "10000000-0000-4000-8000-000000000001",
|
||||
"journal_generation": "20000000-0000-4000-8000-000000000001",
|
||||
"event_id": "40000000-0000-4000-8000-000000000003",
|
||||
"sequence": 3,
|
||||
"monotonic_ms": 1000,
|
||||
"timestamp_sys": "2026-12-03T09:30:00Z",
|
||||
"timestamp_sim": "2026-12-03T12:30:00+03:00",
|
||||
"sim_epoch": 0,
|
||||
"stand_mode": "RUNNING",
|
||||
"origin": "rpi",
|
||||
"source": "radio",
|
||||
"event_type": "RADIO_COMMAND",
|
||||
"correlation_id": "30000000-0000-4000-8000-000000000001",
|
||||
"policy_version": "access-1",
|
||||
"details": {
|
||||
"code": 460769,
|
||||
"burst_id": "30000000-0000-4000-8000-000000000001",
|
||||
"count": 4,
|
||||
"recognized": true,
|
||||
"action": "toggle_barrier",
|
||||
"result": "executed"
|
||||
}
|
||||
},
|
||||
{
|
||||
"schema_version": 1,
|
||||
"stand_id": "labstand-01",
|
||||
"session_id": "10000000-0000-4000-8000-000000000001",
|
||||
"journal_generation": "20000000-0000-4000-8000-000000000001",
|
||||
"event_id": "40000000-0000-4000-8000-000000000004",
|
||||
"sequence": 4,
|
||||
"monotonic_ms": 1000,
|
||||
"timestamp_sys": "2026-12-03T09:30:00Z",
|
||||
"timestamp_sim": "2026-12-03T12:30:00+03:00",
|
||||
"sim_epoch": 0,
|
||||
"stand_mode": "RUNNING",
|
||||
"origin": "rpi",
|
||||
"source": "usb",
|
||||
"event_type": "USB_CONNECTED",
|
||||
"correlation_id": "30000000-0000-4000-8000-000000000001",
|
||||
"policy_version": "access-1",
|
||||
"details": {
|
||||
"pc_id": 1,
|
||||
"usb_session_id": "30000000-0000-4000-8000-000000000001",
|
||||
"device_type": "keyboard"
|
||||
}
|
||||
},
|
||||
{
|
||||
"schema_version": 1,
|
||||
"stand_id": "labstand-01",
|
||||
"session_id": "10000000-0000-4000-8000-000000000001",
|
||||
"journal_generation": "20000000-0000-4000-8000-000000000001",
|
||||
"event_id": "40000000-0000-4000-8000-000000000005",
|
||||
"sequence": 5,
|
||||
"monotonic_ms": 1000,
|
||||
"timestamp_sys": "2026-12-03T09:30:00Z",
|
||||
"timestamp_sim": "2026-12-03T12:30:00+03:00",
|
||||
"sim_epoch": 0,
|
||||
"stand_mode": "FROZEN",
|
||||
"origin": "rpi",
|
||||
"source": "system",
|
||||
"event_type": "SYSTEM_STOP_REQUEST",
|
||||
"correlation_id": "30000000-0000-4000-8000-000000000001",
|
||||
"policy_version": "access-1",
|
||||
"details": {
|
||||
"reason": "system_tag",
|
||||
"uid": "A1CE8B0D",
|
||||
"channel": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"schema_version": 1,
|
||||
"stand_id": "labstand-01",
|
||||
"session_id": "10000000-0000-4000-8000-000000000001",
|
||||
"journal_generation": "20000000-0000-4000-8000-000000000001",
|
||||
"event_id": "40000000-0000-4000-8000-000000000006",
|
||||
"sequence": 6,
|
||||
"monotonic_ms": 1000,
|
||||
"timestamp_sys": "2026-12-03T09:30:00Z",
|
||||
"timestamp_sim": "2026-12-03T12:30:00+03:00",
|
||||
"sim_epoch": 0,
|
||||
"stand_mode": "RUNNING",
|
||||
"origin": "rpi",
|
||||
"source": "esp",
|
||||
"event_type": "ESP_DISCONNECTED",
|
||||
"correlation_id": "30000000-0000-4000-8000-000000000001",
|
||||
"policy_version": "access-1",
|
||||
"details": {
|
||||
"component": "esp32",
|
||||
"code": "heartbeat_timeout",
|
||||
"message": "Нет heartbeat от ESP32",
|
||||
"state": "unavailable"
|
||||
}
|
||||
},
|
||||
{
|
||||
"schema_version": 1,
|
||||
"stand_id": "labstand-01",
|
||||
"session_id": "10000000-0000-4000-8000-000000000002",
|
||||
"journal_generation": "20000000-0000-4000-8000-000000000002",
|
||||
"event_id": "40000000-0000-4000-8000-000000000007",
|
||||
"sequence": 1,
|
||||
"monotonic_ms": 1000,
|
||||
"timestamp_sys": "2026-12-03T09:30:00Z",
|
||||
"timestamp_sim": null,
|
||||
"sim_epoch": null,
|
||||
"stand_mode": "UNKNOWN",
|
||||
"origin": "windows",
|
||||
"source": "collector",
|
||||
"event_type": "COLLECTOR_HEALTH",
|
||||
"correlation_id": "30000000-0000-4000-8000-000000000001",
|
||||
"policy_version": "access-1",
|
||||
"details": {
|
||||
"component": "sftp",
|
||||
"code": "connection_lost",
|
||||
"message": "Соединение недоступно",
|
||||
"state": "unavailable"
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"request_id": "30000000-0000-4000-8000-000000000001",
|
||||
"operation": "events.append",
|
||||
"payload": {
|
||||
"events": [
|
||||
{
|
||||
"schema_version": 1,
|
||||
"stand_id": "labstand-01",
|
||||
"session_id": "10000000-0000-4000-8000-000000000001",
|
||||
"journal_generation": "20000000-0000-4000-8000-000000000001",
|
||||
"event_id": "40000000-0000-4000-8000-000000000001",
|
||||
"sequence": 1,
|
||||
"monotonic_ms": 1000,
|
||||
"timestamp_sys": "2026-12-03T09:30:00Z",
|
||||
"timestamp_sim": "2026-12-03T12:30:00+03:00",
|
||||
"sim_epoch": 0,
|
||||
"stand_mode": "RUNNING",
|
||||
"origin": "rpi",
|
||||
"source": "rfid",
|
||||
"event_type": "RFID_SCAN",
|
||||
"correlation_id": "30000000-0000-4000-8000-000000000001",
|
||||
"policy_version": "access-1",
|
||||
"details": {
|
||||
"channel": 2,
|
||||
"device": "director_lock",
|
||||
"uid": "2EF588F2",
|
||||
"role": "employee",
|
||||
"result": "denied",
|
||||
"reason": "uid_not_authorized_for_channel"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"request_id": "30000000-0000-4000-8000-000000000001",
|
||||
"operation": "events.append",
|
||||
"status": "ok",
|
||||
"result": {
|
||||
"accepted": 1
|
||||
},
|
||||
"error": null
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"stand_id": "labstand-01",
|
||||
"result_id": "50000000-0000-4000-8000-000000000001",
|
||||
"rule_id": "HEALTH-01",
|
||||
"rule_version": "1",
|
||||
"classification": "fault",
|
||||
"severity": "high",
|
||||
"timestamp_sys": "2026-12-03T09:30:00Z",
|
||||
"timestamp_sim": "2026-12-03T12:30:00+03:00",
|
||||
"event_ids": [
|
||||
"40000000-0000-4000-8000-000000000006"
|
||||
],
|
||||
"reason": "Потеря связи с ESP32",
|
||||
"data_complete": true,
|
||||
"fault": {
|
||||
"component": "esp32",
|
||||
"code": "heartbeat_timeout",
|
||||
"state": "active",
|
||||
"first_seen_sys": "2026-12-03T09:30:00Z",
|
||||
"last_seen_sys": "2026-12-03T09:30:00Z",
|
||||
"occurrences": 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[build-system]
|
||||
requires = ["setuptools==80.9.0", "wheel==0.45.1"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "labstand-contracts"
|
||||
version = "0.1.0"
|
||||
description = "Shared LabStand event and IPC contracts for Raspberry Pi and Windows"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
dependencies = []
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["src"]
|
||||
@@ -0,0 +1,9 @@
|
||||
"""Platform-independent, validated LabStand payloads; no transport or authentication."""
|
||||
|
||||
from .models import DetectionResult, ErrorMessage, Event, IPCRequest, IPCResponse
|
||||
from .validation import ContractError, MAX_EVENT_BYTES, MAX_MESSAGE_BYTES, SCHEMA_VERSION
|
||||
|
||||
__all__ = [
|
||||
"ContractError", "DetectionResult", "ErrorMessage", "Event", "IPCRequest",
|
||||
"IPCResponse", "MAX_EVENT_BYTES", "MAX_MESSAGE_BYTES", "SCHEMA_VERSION",
|
||||
]
|
||||
@@ -0,0 +1,280 @@
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
import json
|
||||
|
||||
from .validation import (
|
||||
MAX_EVENT_BYTES, MAX_MESSAGE_BYTES, array, boolean, bounded_integer,
|
||||
choice, decode, encode, fail, fields, identifier, integer, nullable,
|
||||
sim_time, text, utc_time, uuid, version,
|
||||
)
|
||||
|
||||
|
||||
CLASSIFICATIONS = ("suspicious", "fault", "system", "normal")
|
||||
STAND_MODES = ("RUNNING", "FREEZING", "FROZEN", "RESUMING", "STOPPED", "UNKNOWN")
|
||||
SYSTEM_UID = "A1CE8B0D"
|
||||
PC_ID = bounded_integer(1, 3)
|
||||
CHANNEL = bounded_integer(1, 2)
|
||||
|
||||
|
||||
def uid(value, path):
|
||||
text(value, path)
|
||||
if len(value) not in (8, 14, 20) or any(character not in "0123456789ABCDEF" for character in value):
|
||||
fail(path)
|
||||
|
||||
|
||||
def object_fields(required, optional=None):
|
||||
def validate(value, path):
|
||||
fields(value, required, optional, path)
|
||||
return validate
|
||||
|
||||
|
||||
EVENT_SPECS = {
|
||||
"RFID_SCAN": ("rfid", {
|
||||
"channel": CHANNEL, "device": choice("turnstile", "director_lock"),
|
||||
"uid": uid, "role": choice("employee", "director", "guard", "unknown"),
|
||||
"result": choice("granted", "denied"), "reason": identifier,
|
||||
}, {}),
|
||||
"SYSTEM_STOP_REQUEST": ("system", {
|
||||
"reason": choice("system_tag"), "uid": choice(SYSTEM_UID), "channel": CHANNEL,
|
||||
}, {}),
|
||||
"IR_COMMAND": ("ir", {
|
||||
"code": bounded_integer(0, 2**32 - 1), "action": identifier,
|
||||
"result": choice("executed", "ignored", "failed"),
|
||||
}, {}),
|
||||
"RADIO_COMMAND": ("radio", {
|
||||
"code": bounded_integer(0, 2**32 - 1), "burst_id": uuid, "count": bounded_integer(1, 65535),
|
||||
"recognized": boolean, "action": identifier,
|
||||
"result": choice("executed", "debounced", "ignored", "failed"),
|
||||
}, {}),
|
||||
"LIGHTING_CHANGED": ("lighting", {
|
||||
"action": identifier, "enabled_before": boolean, "enabled_after": boolean,
|
||||
}, {"mode": identifier}),
|
||||
"ACCESS_POINT": ("access", {
|
||||
"device": choice("turnstile", "barrier", "gate", "director_lock"),
|
||||
"action": identifier, "result": choice("requested", "executed", "failed", "observed"),
|
||||
}, {"hall_a0": bounded_integer(0, 1), "hall_a1": bounded_integer(0, 1)}),
|
||||
"OS_COMMAND": ("os", {"pc_id": PC_ID, "usb_session_id": nullable(uuid), "command": text}, {}),
|
||||
"SIM_TIME_CHANGED": ("clock", {
|
||||
"before": sim_time, "after": sim_time, "reason": identifier,
|
||||
}, {}),
|
||||
"LOG_GAP": ("logger", {
|
||||
"reason": identifier, "lost_count": nullable(integer),
|
||||
}, {}),
|
||||
"MANUAL_RESET": ("logger", {
|
||||
"actor": identifier, "reason": text, "old_generation": uuid, "new_generation": uuid,
|
||||
}, {}),
|
||||
"RETENTION_PRUNE": ("logger", {
|
||||
"reason": choice("age"), "removed_records": integer,
|
||||
}, {}),
|
||||
"POLICY_CHANGED": ("system", {"actor": identifier, "before": identifier, "after": identifier}, {}),
|
||||
}
|
||||
|
||||
for event_name in ("PC_POWER", "PC_BOOT", "PC_SHUTDOWN", "PC_REBOOT", "OS_BSOD"):
|
||||
EVENT_SPECS[event_name] = ("pc" if event_name != "OS_BSOD" else "os", {
|
||||
"pc_id": PC_ID, "reason": identifier,
|
||||
}, {})
|
||||
|
||||
for event_name in ("USB_CONNECTED", "USB_DISCONNECTED"):
|
||||
EVENT_SPECS[event_name] = ("usb", {
|
||||
"pc_id": PC_ID, "usb_session_id": uuid, "device_type": choice("keyboard"),
|
||||
}, {"vendor_id": bounded_integer(0, 65535), "product_id": bounded_integer(0, 65535)})
|
||||
|
||||
for event_name in ("OS_APP_OPEN", "OS_APP_CLOSE"):
|
||||
EVENT_SPECS[event_name] = ("os", {
|
||||
"pc_id": PC_ID, "usb_session_id": nullable(uuid), "app": identifier,
|
||||
}, {})
|
||||
|
||||
for event_name in ("FREEZE_BEGIN", "FREEZE_READY", "FREEZE_END", "FREEZE_FAILED"):
|
||||
EVENT_SPECS[event_name] = ("clock", {
|
||||
"freeze_id": uuid, "reason": identifier,
|
||||
"participants": array(identifier, maximum=16, unique=True),
|
||||
}, {})
|
||||
|
||||
for event_name, source in (
|
||||
("SYSTEM_START", "system"), ("SYSTEM_STOP", "system"), ("SYSTEM_ERROR", "system"),
|
||||
("ESP_CONNECTED", "esp"), ("ESP_DISCONNECTED", "esp"), ("UART_ERROR", "esp"),
|
||||
("WATCHDOG_TRIGGERED", "system"), ("I2C_RECOVERY", "system"),
|
||||
("LOGGER_HEALTH", "logger"), ("COLLECTOR_HEALTH", "collector"),
|
||||
):
|
||||
EVENT_SPECS[event_name] = (source, {
|
||||
"component": identifier, "code": identifier, "message": text,
|
||||
"state": choice("ok", "degraded", "unavailable", "unknown"),
|
||||
}, {})
|
||||
|
||||
|
||||
def event_payload(payload, path="$"):
|
||||
fields(payload, {
|
||||
"schema_version": version, "stand_id": identifier,
|
||||
"session_id": uuid, "journal_generation": uuid, "event_id": uuid,
|
||||
"sequence": bounded_integer(1, 2**63 - 1), "monotonic_ms": integer,
|
||||
"timestamp_sys": utc_time, "timestamp_sim": nullable(sim_time),
|
||||
"sim_epoch": nullable(integer), "stand_mode": choice(*STAND_MODES),
|
||||
"origin": choice("rpi", "windows"), "source": identifier,
|
||||
"event_type": choice(*EVENT_SPECS), "correlation_id": nullable(uuid),
|
||||
"policy_version": identifier, "details": lambda value, location: None,
|
||||
}, path=path)
|
||||
source, required, optional = EVENT_SPECS[payload["event_type"]]
|
||||
if payload["source"] != source:
|
||||
fail(f"{path}.source")
|
||||
fields(payload["details"], required, optional, f"{path}.details")
|
||||
if payload["origin"] == "rpi" and payload["timestamp_sim"] is None:
|
||||
fail(f"{path}.timestamp_sim")
|
||||
if (payload["timestamp_sim"] is None) != (payload["sim_epoch"] is None):
|
||||
fail(f"{path}.sim_epoch")
|
||||
if payload["origin"] == "windows" and source not in ("system", "collector", "logger"):
|
||||
fail(f"{path}.origin")
|
||||
details = payload["details"]
|
||||
if payload["event_type"] == "RFID_SCAN":
|
||||
if details["uid"] == SYSTEM_UID:
|
||||
fail(f"{path}.details.uid", "system_tag_requires_system_event")
|
||||
expected_device = "turnstile" if details["channel"] == 1 else "director_lock"
|
||||
if details["device"] != expected_device:
|
||||
fail(f"{path}.details.device")
|
||||
if payload["event_type"] == "SYSTEM_STOP_REQUEST" and payload["origin"] != "rpi":
|
||||
fail(f"{path}.origin")
|
||||
if payload["event_type"] == "RADIO_COMMAND":
|
||||
if not details["recognized"] and details["result"] != "ignored":
|
||||
fail(f"{path}.details.result")
|
||||
encode(payload, MAX_EVENT_BYTES)
|
||||
|
||||
|
||||
FAULT_FIELDS = {
|
||||
"component": identifier, "code": identifier,
|
||||
"state": choice("active", "resolved", "unknown"),
|
||||
"first_seen_sys": utc_time, "last_seen_sys": utc_time,
|
||||
"occurrences": bounded_integer(1, 2**63 - 1),
|
||||
}
|
||||
|
||||
|
||||
def result_payload(payload, path="$"):
|
||||
fields(payload, {
|
||||
"schema_version": version, "stand_id": identifier, "result_id": uuid,
|
||||
"rule_id": identifier, "rule_version": identifier,
|
||||
"classification": choice(*CLASSIFICATIONS),
|
||||
"severity": choice("info", "low", "medium", "high", "critical"),
|
||||
"timestamp_sys": utc_time, "timestamp_sim": nullable(sim_time),
|
||||
"event_ids": array(uuid, minimum=1, maximum=64, unique=True),
|
||||
"reason": text, "data_complete": boolean,
|
||||
"fault": nullable(object_fields(FAULT_FIELDS)),
|
||||
}, path=path)
|
||||
if (payload["classification"] == "fault") != (payload["fault"] is not None):
|
||||
fail(f"{path}.fault")
|
||||
if payload["fault"] is not None:
|
||||
fault = payload["fault"]
|
||||
first = datetime.fromisoformat(fault["first_seen_sys"].replace("Z", "+00:00"))
|
||||
last = datetime.fromisoformat(fault["last_seen_sys"].replace("Z", "+00:00"))
|
||||
if first > last:
|
||||
fail(f"{path}.fault.last_seen_sys")
|
||||
|
||||
|
||||
def error_payload(payload, path="$"):
|
||||
fields(payload, {
|
||||
"schema_version": version,
|
||||
"code": choice("invalid_request", "unsupported_version", "unauthorized", "conflict", "unavailable", "internal_error"),
|
||||
"message": text, "retryable": boolean,
|
||||
}, path=path)
|
||||
|
||||
|
||||
OPERATIONS = ("events.append", "events.query", "results.append", "results.query", "health.get")
|
||||
QUERY_FIELDS = {"limit": bounded_integer(1, 100), "cursor": nullable(identifier)}
|
||||
|
||||
|
||||
def request_payload(payload, path="$"):
|
||||
fields(payload, {
|
||||
"schema_version": version, "request_id": uuid, "operation": choice(*OPERATIONS),
|
||||
"payload": lambda value, location: None,
|
||||
}, path=path)
|
||||
operation = payload["operation"]
|
||||
required = {}
|
||||
if operation == "events.append":
|
||||
required = {"events": array(event_payload, minimum=1)}
|
||||
elif operation == "results.append":
|
||||
required = {"results": array(result_payload, minimum=1)}
|
||||
elif operation == "events.query":
|
||||
required = {**QUERY_FIELDS, "event_type": nullable(choice(*EVENT_SPECS))}
|
||||
elif operation == "results.query":
|
||||
required = {**QUERY_FIELDS, "classification": nullable(choice(*CLASSIFICATIONS))}
|
||||
fields(payload["payload"], required, path=f"{path}.payload")
|
||||
|
||||
|
||||
def response_payload(payload, path="$"):
|
||||
fields(payload, {
|
||||
"schema_version": version, "request_id": uuid, "operation": choice(*OPERATIONS),
|
||||
"status": choice("ok", "error"), "result": lambda value, location: None,
|
||||
"error": nullable(error_payload),
|
||||
}, path=path)
|
||||
if payload["status"] == "error":
|
||||
if payload["result"] is not None or payload["error"] is None:
|
||||
fail(path, "invalid_response")
|
||||
return
|
||||
if payload["error"] is not None:
|
||||
fail(f"{path}.error", "invalid_response")
|
||||
operation = payload["operation"]
|
||||
if operation.endswith(".append"):
|
||||
required = {"accepted": bounded_integer(0, 32)}
|
||||
elif operation.endswith(".query"):
|
||||
validator = event_payload if operation == "events.query" else result_payload
|
||||
required = {"items": array(validator, maximum=100), "next_cursor": nullable(identifier)}
|
||||
else:
|
||||
required = {"component": identifier, "state": choice("ok", "degraded", "unavailable", "unknown")}
|
||||
fields(payload["result"], required, path=f"{path}.result")
|
||||
|
||||
|
||||
@dataclass(frozen=True, init=False)
|
||||
class Message:
|
||||
_encoded: bytes
|
||||
|
||||
def __init__(self, payload):
|
||||
encoded = encode(payload, self.maximum_bytes)
|
||||
self.validate(json.loads(encoded))
|
||||
object.__setattr__(self, "_encoded", encoded)
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, raw):
|
||||
return cls(decode(raw, cls.maximum_bytes))
|
||||
|
||||
def to_dict(self):
|
||||
return json.loads(self._encoded)
|
||||
|
||||
def to_json(self):
|
||||
return self._encoded
|
||||
|
||||
|
||||
class Event(Message):
|
||||
maximum_bytes = MAX_EVENT_BYTES
|
||||
validate = staticmethod(event_payload)
|
||||
|
||||
@property
|
||||
def identity(self):
|
||||
payload = self.to_dict()
|
||||
return payload["stand_id"], payload["event_id"]
|
||||
|
||||
@property
|
||||
def position(self):
|
||||
payload = self.to_dict()
|
||||
return tuple(payload[name] for name in ("stand_id", "origin", "journal_generation", "session_id", "sequence"))
|
||||
|
||||
|
||||
class DetectionResult(Message):
|
||||
maximum_bytes = MAX_MESSAGE_BYTES
|
||||
validate = staticmethod(result_payload)
|
||||
|
||||
|
||||
class ErrorMessage(Message):
|
||||
maximum_bytes = MAX_EVENT_BYTES
|
||||
validate = staticmethod(error_payload)
|
||||
|
||||
|
||||
class IPCRequest(Message):
|
||||
maximum_bytes = MAX_MESSAGE_BYTES
|
||||
validate = staticmethod(request_payload)
|
||||
|
||||
|
||||
class IPCResponse(Message):
|
||||
maximum_bytes = MAX_MESSAGE_BYTES
|
||||
validate = staticmethod(response_payload)
|
||||
|
||||
def matches(self, request):
|
||||
response_payload = self.to_dict()
|
||||
request_payload = request.to_dict()
|
||||
return all(response_payload[key] == request_payload[key] for key in ("request_id", "operation"))
|
||||
@@ -0,0 +1,208 @@
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
from uuid import UUID
|
||||
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
MAX_EVENT_BYTES = 8192
|
||||
MAX_MESSAGE_BYTES = 65536
|
||||
MAX_DEPTH = 8
|
||||
MAX_NODES = 2048
|
||||
MAX_STRING_LENGTH = 2048
|
||||
MAX_INTEGER = 2**63 - 1
|
||||
|
||||
|
||||
class ContractError(ValueError):
|
||||
def __init__(self, code: str, path: str):
|
||||
self.code = code
|
||||
self.path = path
|
||||
super().__init__(f"{code}: {path}")
|
||||
|
||||
|
||||
def fail(path, code="invalid_value"):
|
||||
raise ContractError(code, path)
|
||||
|
||||
|
||||
def text(value, path):
|
||||
if type(value) is not str or not value or len(value) > MAX_STRING_LENGTH:
|
||||
fail(path)
|
||||
if any(ord(character) < 32 or 0xD800 <= ord(character) <= 0xDFFF for character in value):
|
||||
fail(path)
|
||||
|
||||
|
||||
def identifier(value, path):
|
||||
text(value, path)
|
||||
if re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}", value) is None:
|
||||
fail(path)
|
||||
|
||||
|
||||
def uuid(value, path):
|
||||
text(value, path)
|
||||
try:
|
||||
parsed = UUID(value)
|
||||
except ValueError:
|
||||
fail(path)
|
||||
if str(parsed) != value:
|
||||
fail(path)
|
||||
|
||||
|
||||
def integer(value, path, minimum=0, maximum=MAX_INTEGER):
|
||||
if type(value) is not int or not minimum <= value <= maximum:
|
||||
fail(path)
|
||||
|
||||
|
||||
def boolean(value, path):
|
||||
if type(value) is not bool:
|
||||
fail(path)
|
||||
|
||||
|
||||
def choice(*values):
|
||||
def validate(value, path):
|
||||
if type(value) is not str or value not in values:
|
||||
fail(path)
|
||||
return validate
|
||||
|
||||
|
||||
def nullable(validator):
|
||||
def validate(value, path):
|
||||
if value is not None:
|
||||
validator(value, path)
|
||||
return validate
|
||||
|
||||
|
||||
def bounded_integer(minimum, maximum):
|
||||
def validate(value, path):
|
||||
integer(value, path, minimum, maximum)
|
||||
return validate
|
||||
|
||||
|
||||
def timestamp(offset):
|
||||
def validate(value, path):
|
||||
text(value, path)
|
||||
if re.fullmatch(
|
||||
r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})",
|
||||
value,
|
||||
) is None:
|
||||
fail(path)
|
||||
try:
|
||||
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
fail(path)
|
||||
suffixes = ("Z", "+00:00") if offset == 0 else ("+03:00",)
|
||||
if parsed.utcoffset() != timedelta(hours=offset) or not value.endswith(suffixes):
|
||||
fail(path)
|
||||
return validate
|
||||
|
||||
|
||||
utc_time = timestamp(0)
|
||||
sim_time = timestamp(3)
|
||||
|
||||
|
||||
def fields(value, required, optional=None, path="$"):
|
||||
if type(value) is not dict:
|
||||
fail(path, "invalid_type")
|
||||
optional = optional or {}
|
||||
if set(value) - set(required) - set(optional):
|
||||
fail(path, "unknown_field")
|
||||
for name, validator in required.items():
|
||||
field_path = f"{path}.{name}"
|
||||
if name not in value:
|
||||
fail(field_path, "missing_field")
|
||||
validator(value[name], field_path)
|
||||
for name, validator in optional.items():
|
||||
if name in value:
|
||||
validator(value[name], f"{path}.{name}")
|
||||
|
||||
|
||||
def version(value, path):
|
||||
if type(value) is not int:
|
||||
fail(path, "invalid_type")
|
||||
if value != SCHEMA_VERSION:
|
||||
fail(path, "unsupported_version")
|
||||
|
||||
|
||||
def array(validator, minimum=0, maximum=32, unique=False):
|
||||
def validate(value, path):
|
||||
if type(value) is not list or not minimum <= len(value) <= maximum:
|
||||
fail(path)
|
||||
for index, item in enumerate(value):
|
||||
validator(item, f"{path}[{index}]")
|
||||
if unique and len(set(value)) != len(value):
|
||||
fail(path, "duplicate_value")
|
||||
return validate
|
||||
|
||||
|
||||
def check_tree(value):
|
||||
nodes = 0
|
||||
|
||||
def visit(item, depth):
|
||||
nonlocal nodes
|
||||
nodes += 1
|
||||
if depth > MAX_DEPTH or nodes > MAX_NODES:
|
||||
fail("$", "limit_exceeded")
|
||||
if type(item) is dict:
|
||||
for key, child in item.items():
|
||||
text(key, "$")
|
||||
visit(child, depth + 1)
|
||||
elif type(item) is list:
|
||||
for child in item:
|
||||
visit(child, depth + 1)
|
||||
elif type(item) is str:
|
||||
if len(item) > MAX_STRING_LENGTH:
|
||||
fail("$", "limit_exceeded")
|
||||
if any(0xD800 <= ord(character) <= 0xDFFF for character in item):
|
||||
fail("$", "invalid_value")
|
||||
elif type(item) is float:
|
||||
if not math.isfinite(item):
|
||||
fail("$", "invalid_value")
|
||||
elif type(item) is int:
|
||||
if not -MAX_INTEGER <= item <= MAX_INTEGER:
|
||||
fail("$", "limit_exceeded")
|
||||
elif item is not None and type(item) is not bool:
|
||||
fail("$", "invalid_type")
|
||||
|
||||
visit(value, 0)
|
||||
|
||||
|
||||
def encode(value, maximum):
|
||||
check_tree(value)
|
||||
encoded = json.dumps(
|
||||
value, ensure_ascii=False, allow_nan=False, separators=(",", ":"), sort_keys=True
|
||||
).encode("utf-8")
|
||||
if len(encoded) > maximum:
|
||||
fail("$", "limit_exceeded")
|
||||
return encoded
|
||||
|
||||
|
||||
def decode(raw, maximum):
|
||||
if type(raw) not in (bytes, str):
|
||||
fail("$", "invalid_type")
|
||||
try:
|
||||
encoded = raw.encode("utf-8") if type(raw) is str else raw
|
||||
if len(encoded) > maximum:
|
||||
fail("$", "limit_exceeded")
|
||||
decoded = encoded.decode("utf-8")
|
||||
except UnicodeError:
|
||||
fail("$", "invalid_encoding")
|
||||
|
||||
def pairs(items):
|
||||
result = {}
|
||||
for key, value in items:
|
||||
if key in result:
|
||||
fail("$", "duplicate_key")
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
def reject_constant(value):
|
||||
fail("$", "invalid_json")
|
||||
|
||||
try:
|
||||
result = json.loads(decoded, object_pairs_hook=pairs, parse_constant=reject_constant)
|
||||
except (ValueError, RecursionError) as error:
|
||||
if isinstance(error, ContractError):
|
||||
raise
|
||||
fail("$", "invalid_json")
|
||||
check_tree(result)
|
||||
return result
|
||||
@@ -0,0 +1,285 @@
|
||||
from copy import deepcopy
|
||||
from dataclasses import FrozenInstanceError
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from labstand_contracts import (
|
||||
ContractError, DetectionResult, ErrorMessage, Event, IPCRequest, IPCResponse,
|
||||
MAX_EVENT_BYTES, MAX_MESSAGE_BYTES,
|
||||
)
|
||||
from labstand_contracts.validation import MAX_DEPTH
|
||||
|
||||
|
||||
EXAMPLES = Path(__file__).resolve().parents[1] / "examples"
|
||||
|
||||
|
||||
def example(name):
|
||||
return json.loads((EXAMPLES / name).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def event():
|
||||
return example("events.json")[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", example("events.json"))
|
||||
def test_shared_events_round_trip(payload):
|
||||
model = Event(payload)
|
||||
assert Event.from_json(model.to_json()).to_dict() == payload
|
||||
assert Event.from_json(json.dumps(payload)).identity == model.identity
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("model", "filename"),
|
||||
[(DetectionResult, "result.json"), (ErrorMessage, "error.json"),
|
||||
(IPCRequest, "request.json"), (IPCResponse, "response.json")],
|
||||
)
|
||||
def test_shared_messages_round_trip(model, filename):
|
||||
payload = example(filename)
|
||||
assert model.from_json(model(payload).to_json()).to_dict() == payload
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("field", "value"),
|
||||
[
|
||||
("schema_version", 2), ("schema_version", True),
|
||||
("sequence", True), ("sequence", 0), ("sequence", 1.0),
|
||||
("monotonic_ms", -1), ("sim_epoch", -1), ("event_id", "not-a-uuid"),
|
||||
("journal_generation", None), ("timestamp_sys", "2026-12-03T12:00:00+03:00"),
|
||||
("timestamp_sys", "2026-12-03T12:00:00"),
|
||||
("timestamp_sys", "2026-02-30T12:00:00Z"),
|
||||
("timestamp_sys", "2026-12-03T12:00:00-00:00"),
|
||||
("timestamp_sim", "2026-12-03T12:00:00+02:60"),
|
||||
("timestamp_sim", "2026-12-03T12:00:00Z"), ("timestamp_sim", None),
|
||||
("source", "radio"), ("event_type", "INVENTED"), ("origin", "windows"),
|
||||
("stand_mode", "executing"), ("sim_epoch", None),
|
||||
],
|
||||
)
|
||||
def test_invalid_event_fields(event, field, value):
|
||||
event[field] = value
|
||||
with pytest.raises(ContractError):
|
||||
Event(event)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", list(example("events.json")[0]))
|
||||
def test_every_envelope_field_is_required(event, field):
|
||||
del event[field]
|
||||
with pytest.raises(ContractError) as error:
|
||||
Event(event)
|
||||
assert error.value.code == "missing_field"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("field", "value"),
|
||||
[("channel", True), ("channel", 3), ("uid", "2ef588f2"),
|
||||
("uid", "A1CE8B0D"), ("role", "admin"), ("device", "turnstile"),
|
||||
("result", "success"), ("attack_detected", True)],
|
||||
)
|
||||
def test_invalid_rfid_details(event, field, value):
|
||||
event["details"][field] = value
|
||||
with pytest.raises(ContractError):
|
||||
Event(event)
|
||||
|
||||
|
||||
def test_unexpected_envelope_and_missing_details(event):
|
||||
event["classification"] = "normal"
|
||||
with pytest.raises(ContractError, match="unknown_field"):
|
||||
Event(event)
|
||||
del event["classification"]
|
||||
del event["details"]["uid"]
|
||||
with pytest.raises(ContractError, match="missing_field"):
|
||||
Event(event)
|
||||
|
||||
|
||||
def test_event_snapshot_is_immutable(event):
|
||||
model = Event(event)
|
||||
event["details"]["uid"] = "CE0385F2"
|
||||
exported = model.to_dict()
|
||||
exported["details"]["uid"] = "CE0385F2"
|
||||
assert model.to_dict()["details"]["uid"] == "2EF588F2"
|
||||
with pytest.raises(FrozenInstanceError):
|
||||
model._encoded = b"{}"
|
||||
|
||||
|
||||
def test_identity_does_not_depend_on_time_or_sequence(event):
|
||||
first = Event(event)
|
||||
event["sequence"] += 1
|
||||
event["timestamp_sim"] = "2026-12-02T01:00:00+03:00"
|
||||
second = Event(event)
|
||||
assert first.identity == second.identity
|
||||
assert first.position != second.position
|
||||
event["journal_generation"] = "20000000-0000-4000-8000-000000000002"
|
||||
assert Event(event).position != second.position
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", [
|
||||
b"\xff", '{"schema_version":1,"schema_version":1}',
|
||||
'{"details":{"uid":"one","uid":"two"}}', '{"number":NaN}',
|
||||
'{"number":Infinity}', '{"number":1e999}', '{', '{}{}',
|
||||
'\ufeff{}', '"\\ud800"', '[' * 1500 + '0' + ']' * 1500,
|
||||
])
|
||||
def test_untrusted_json_is_rejected(raw):
|
||||
with pytest.raises(ContractError):
|
||||
Event.from_json(raw)
|
||||
|
||||
|
||||
def test_utf8_byte_limit_and_jsonl_framing(event):
|
||||
raw = Event(event).to_json()
|
||||
assert Event.from_json(raw + b"\n").identity == Event(event).identity
|
||||
assert Event.from_json(raw + b" " * (MAX_EVENT_BYTES - len(raw)))
|
||||
with pytest.raises(ContractError, match="limit_exceeded"):
|
||||
Event.from_json(raw + b" " * (MAX_EVENT_BYTES - len(raw) + 1))
|
||||
with pytest.raises(ContractError, match="limit_exceeded"):
|
||||
Event.from_json('я' * (MAX_EVENT_BYTES // 2 + 1))
|
||||
|
||||
|
||||
def test_object_limits_before_schema_validation(event):
|
||||
nested = {}
|
||||
for index in range(MAX_DEPTH + 1):
|
||||
nested = {"child": nested}
|
||||
for value in (nested, {"children": [0] * 2049}, {"text": "x" * 2049}):
|
||||
with pytest.raises(ContractError, match="limit_exceeded"):
|
||||
Event(value)
|
||||
event["details"]["reason"] = "secret\nvalue"
|
||||
with pytest.raises(ContractError) as error:
|
||||
Event(event)
|
||||
assert "secret" not in str(error.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("classification", ["suspicious", "fault", "system", "normal"])
|
||||
def test_result_classes(classification):
|
||||
payload = example("result.json")
|
||||
payload["classification"] = classification
|
||||
if classification != "fault":
|
||||
payload["fault"] = None
|
||||
assert DetectionResult(payload)
|
||||
|
||||
|
||||
def test_result_requires_consistent_fault_and_evidence():
|
||||
payload = example("result.json")
|
||||
variants = []
|
||||
for field, value in [("fault", None), ("event_ids", []), ("classification", "attack")]:
|
||||
candidate = deepcopy(payload)
|
||||
candidate[field] = value
|
||||
variants.append(candidate)
|
||||
duplicate = deepcopy(payload)
|
||||
duplicate["event_ids"] *= 2
|
||||
variants.append(duplicate)
|
||||
inverted = deepcopy(payload)
|
||||
inverted["fault"]["last_seen_sys"] = "2026-12-02T09:30:00Z"
|
||||
variants.append(inverted)
|
||||
for candidate in variants:
|
||||
with pytest.raises(ContractError):
|
||||
DetectionResult(candidate)
|
||||
|
||||
|
||||
def test_windows_diagnostics_may_lack_simulated_time():
|
||||
payload = example("events.json")[-1]
|
||||
assert Event(payload)
|
||||
payload["sim_epoch"] = 0
|
||||
with pytest.raises(ContractError):
|
||||
Event(payload)
|
||||
|
||||
|
||||
def test_system_tag_and_unknown_radio_semantics():
|
||||
payload = example("events.json")[4]
|
||||
assert Event(payload).to_dict()["stand_mode"] == "FROZEN"
|
||||
payload["origin"] = "windows"
|
||||
with pytest.raises(ContractError):
|
||||
Event(payload)
|
||||
payload = example("events.json")[2]
|
||||
payload["details"]["recognized"] = False
|
||||
with pytest.raises(ContractError):
|
||||
Event(payload)
|
||||
payload["details"]["result"] = "ignored"
|
||||
assert Event(payload)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("source,event_type,details", [
|
||||
("lighting", "LIGHTING_CHANGED", {"action": "toggle", "enabled_before": False, "enabled_after": True}),
|
||||
("access", "ACCESS_POINT", {"device": "gate", "action": "stop", "result": "executed", "hall_a0": 0}),
|
||||
("pc", "PC_POWER", {"pc_id": 1, "reason": "button"}),
|
||||
("pc", "PC_BOOT", {"pc_id": 2, "reason": "power_on"}),
|
||||
("pc", "PC_SHUTDOWN", {"pc_id": 3, "reason": "user_request"}),
|
||||
("pc", "PC_REBOOT", {"pc_id": 1, "reason": "button_long"}),
|
||||
("os", "OS_BSOD", {"pc_id": 1, "reason": "killall"}),
|
||||
("os", "OS_COMMAND", {"pc_id": 1, "usb_session_id": None, "command": "killallnet"}),
|
||||
("os", "OS_APP_OPEN", {"pc_id": 1, "usb_session_id": None, "app": "terminal"}),
|
||||
("os", "OS_APP_CLOSE", {"pc_id": 1, "usb_session_id": None, "app": "terminal"}),
|
||||
("clock", "SIM_TIME_CHANGED", {"before": "2026-12-03T12:00:00+03:00", "after": "2026-12-02T12:00:00+03:00", "reason": "rewind"}),
|
||||
("logger", "LOG_GAP", {"reason": "queue_overflow", "lost_count": None}),
|
||||
("logger", "RETENTION_PRUNE", {"reason": "age", "removed_records": 10}),
|
||||
("logger", "MANUAL_RESET", {"actor": "admin", "reason": "Учебный сброс", "old_generation": "20000000-0000-4000-8000-000000000001", "new_generation": "20000000-0000-4000-8000-000000000002"}),
|
||||
("system", "POLICY_CHANGED", {"actor": "admin", "before": "access-1", "after": "access-2"}),
|
||||
])
|
||||
def test_other_event_families(event, source, event_type, details):
|
||||
event.update(source=source, event_type=event_type, details=details)
|
||||
assert Event.from_json(Event(event).to_json()).to_dict() == event
|
||||
|
||||
|
||||
@pytest.mark.parametrize("event_type", ["FREEZE_BEGIN", "FREEZE_READY", "FREEZE_END", "FREEZE_FAILED"])
|
||||
def test_freeze_events(event, event_type):
|
||||
event.update(source="clock", event_type=event_type, details={
|
||||
"freeze_id": event["correlation_id"], "reason": "encoder", "participants": ["esp32", "okna96"],
|
||||
})
|
||||
assert Event(event)
|
||||
event["details"]["participants"].append("esp32")
|
||||
with pytest.raises(ContractError, match="duplicate_value"):
|
||||
Event(event)
|
||||
|
||||
|
||||
def test_ipc_pair_and_error_response():
|
||||
request = IPCRequest(example("request.json"))
|
||||
payload = example("response.json")
|
||||
assert IPCResponse(payload).matches(request)
|
||||
payload["request_id"] = "30000000-0000-4000-8000-000000000002"
|
||||
assert not IPCResponse(payload).matches(request)
|
||||
payload.update(status="error", result=None, error=example("error.json"))
|
||||
assert IPCResponse(payload)
|
||||
payload["result"] = {"accepted": 1}
|
||||
with pytest.raises(ContractError, match="invalid_response"):
|
||||
IPCResponse(payload)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operation", ["shell.execute", "gpio.write", "sql.execute", "rules.apply"])
|
||||
def test_unsupported_operations_are_rejected(operation):
|
||||
payload = example("request.json")
|
||||
payload["operation"] = operation
|
||||
with pytest.raises(ContractError):
|
||||
IPCRequest(payload)
|
||||
|
||||
|
||||
def test_ipc_queries_and_nested_validation():
|
||||
payload = example("request.json")
|
||||
payload.update(operation="events.query", payload={"limit": 100, "cursor": None, "event_type": None})
|
||||
assert IPCRequest(payload)
|
||||
payload["payload"]["limit"] = 101
|
||||
with pytest.raises(ContractError):
|
||||
IPCRequest(payload)
|
||||
nested = example("request.json")
|
||||
nested["payload"]["events"][0]["details"]["channel"] = 3
|
||||
with pytest.raises(ContractError):
|
||||
IPCRequest(nested)
|
||||
nested = example("request.json")
|
||||
nested["payload"]["events"] *= 33
|
||||
with pytest.raises(ContractError):
|
||||
IPCRequest(nested)
|
||||
with pytest.raises(ContractError, match="limit_exceeded"):
|
||||
IPCRequest.from_json(b" " * (MAX_MESSAGE_BYTES + 1))
|
||||
|
||||
|
||||
def test_results_query_reply_and_health():
|
||||
payload = example("response.json")
|
||||
payload.update(operation="results.query", result={"items": [example("result.json")], "next_cursor": None})
|
||||
assert IPCResponse(payload)
|
||||
payload["result"]["items"][0]["fault"] = None
|
||||
with pytest.raises(ContractError):
|
||||
IPCResponse(payload)
|
||||
request = example("request.json")
|
||||
request.update(operation="health.get", payload={})
|
||||
assert IPCRequest(request)
|
||||
request["payload"]["sql"] = "DROP TABLE events"
|
||||
with pytest.raises(ContractError, match="unknown_field"):
|
||||
IPCRequest(request)
|
||||
Reference in new issue
Block a user