This commit is contained in:
DurkaHelper contributors committed 2026-10-10 07:29:48 +03:00
commit 303438d206
217 files changed
+66681

No files matched your search

+39
View File
@@ -0,0 +1,39 @@
<a id="synthetic-local-defense-lab"></a>
# Синтетическая локальная лаборатория защиты
[English](README.md) | Русский
Этот сервис использует только стандартную библиотеку, намеренно мал и доступен только через loopback. Он не подключается к инфраструктуре соревнования. Запускайте из корня репозитория с Python 3.10+.
Свидетельство: `REVIEWED`; эффект `SERVICE-CHANGE` (один локальный процесс). Ожидается: loopback listener без внешнего bind. Секреты: используйте только предоставленные синтетические fixtures. Rollback: Ctrl-C останавливает процесс.
```bash
python3 lab/health_service.py
```
Порт по умолчанию: 8080. Используйте --port 8081 для другого явно выбранного порта или --port 0 для временного порта, фактический URL которого будет напечатан. Соответственно обновите профиль probe. fixtures/service.json демонстрирует резервное копирование конфигурации; сервер его не загружает.
| Запрос | Ответ |
|---|---|
| GET /health or /health?check=1 | 200 и {"status": "ok"} |
| GET /version | 200 и {"version": "demo"} |
| HEAD /health | Заголовки GET без тела |
| GET /missing | 404 |
| POST /health | 405; Allow: GET, HEAD |
Сервис пишет в stderr JSONL-записи level/status без URL или содержимого запросов.
В другом терминале: свидетельство `REVIEWED`, эффект `READ-ONLY`, тот же рабочий каталог; ожидается код выхода probe 0 и сводка лога с двумя HTTP-ошибками в предоставленном fixture из четырёх записей:
```bash
python3 scripts/http_probe.py config/services.example.json
python3 scripts/log_summary.py lab/fixtures/events.jsonl
```
Unit tests создают и останавливают собственные временные loopback-серверы; отдельно запущенная лаборатория не нужна. Эффект: временный `WORKSPACE-WRITE`; ожидается успешное прохождение набора.
```bash
python3 -m unittest discover -s tests -p 'test_defense*.py' -v
```
DEMO_ONLY_DO_NOT_COPY в fixtures/service.json — безвредное тестовое значение, а не действующий пароль. Внешние контейнерные тесты — отдельный запускаемый по выбору [integration fixture](../integration/README-RU.md).
+38
View File
@@ -0,0 +1,38 @@
# Synthetic local defense lab
English | [Русский](README-RU.md)
This stdlib-only service is intentionally small and loopback-only. It does not connect to competition infrastructure. Run from the repository root with Python 3.10+.
Evidence: `REVIEWED`; effect `SERVICE-CHANGE` (one local process). Expected: a loopback listener, no external binding. Secrets: use only provided synthetic fixtures. Rollback: Ctrl-C stops the process.
```bash
python3 lab/health_service.py
```
Default port: 8080. Use --port 8081 for another explicit port, or --port 0 for an ephemeral port whose actual URL is printed. Update your probe profile accordingly. fixtures/service.json demonstrates configuration backup; the server does not load it.
| Request | Response |
|---|---|
| GET /health or /health?check=1 | 200 and {"status": "ok"} |
| GET /version | 200 and {"version": "demo"} |
| HEAD /health | GET headers without body |
| GET /missing | 404 |
| POST /health | 405; Allow: GET, HEAD |
The service writes JSONL level/status records to stderr without URLs or request contents.
In another terminal, evidence `REVIEWED`, effect `READ-ONLY`, same cwd; expected probe exit 0 and a log summary with two HTTP errors in the provided four-record fixture:
```bash
python3 scripts/http_probe.py config/services.example.json
python3 scripts/log_summary.py lab/fixtures/events.jsonl
```
Unit tests create/stop their own temporary loopback servers; no separately running lab is needed. Effect: temporary `WORKSPACE-WRITE`; expected suite pass.
```bash
python3 -m unittest discover -s tests -p 'test_defense*.py' -v
```
DEMO_ONLY_DO_NOT_COPY in fixtures/service.json is an inert test value, not a working password. External container tests are a separate opt-in [integration fixture](../integration/README.md).
@@ -0,0 +1,15 @@
{
"schema": "durkahelper.event.v1",
"id": "event-synthetic-redacted-0001",
"timestamp": "2026-01-01T00:01:00Z",
"source": "synthetic-triage",
"kind": "suspicious_activity",
"severity": "medium",
"summary": "Synthetic triage event exported with sensitive details removed.",
"attributes": {
"detail": "[REDACTED]",
"record_count": 2,
"redacted": true,
"source_address": "127.0.0.1"
}
}
+14
View File
@@ -0,0 +1,14 @@
{
"schema": "durkahelper.event.v1",
"id": "event-synthetic-health-0001",
"timestamp": "2026-01-01T00:00:00Z",
"source": "synthetic-health",
"kind": "service_health",
"severity": "info",
"summary": "Synthetic loopback health check passed.",
"attributes": {
"endpoint": "http://127.0.0.1:8080/health",
"healthy": true,
"status_code": 200
}
}
@@ -0,0 +1,16 @@
{
"schema": "durkahelper.validation-record.v1",
"id": "validation-redacted-0001",
"timestamp": "2026-01-01T00:03:00Z",
"check": "evidence_export",
"status": "partial",
"summary": "Synthetic validation retained only redacted evidence.",
"evidence": [
"lab/fixtures/defense_ops/event.redacted.json"
],
"attributes": {
"inspected_events": 1,
"redacted": true,
"retained_detail": "[REDACTED]"
}
}
@@ -0,0 +1,15 @@
{
"schema": "durkahelper.validation-record.v1",
"id": "validation-baseline-0001",
"timestamp": "2026-01-01T00:02:00Z",
"check": "baseline_compare",
"status": "pass",
"summary": "Synthetic baseline matched the current snapshot.",
"evidence": [
"lab/fixtures/defense_ops/event.valid.json"
],
"attributes": {
"comparable": true,
"drift_count": 0
}
}
+4
View File
@@ -0,0 +1,4 @@
{"level":"INFO","status":200,"message":"health check"}
{"level":"INFO","status":200,"message":"version check"}
{"level":"WARNING","status":404,"message":"unknown route"}
{"level":"ERROR","status":503,"message":"synthetic unavailable response"}
+7
View File
@@ -0,0 +1,7 @@
{
"service": {"name": "local-demo"},
"http": {"port": 8080},
"logging": {"level": "INFO"},
"credentials": {"password": "DEMO_ONLY_DO_NOT_COPY"},
"unselected": "THIS_FIELD_IS_NOT_INCLUDED"
}
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
"""Small health-check demo bound only to IPv4 loopback."""
import argparse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import sys
from urllib.parse import urlsplit
class Handler(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def respond(self, head=False, unsupported=False):
try:
path = urlsplit(self.path).path
except ValueError:
path = ""
if unsupported:
status, body = 405, {"error": "method not allowed"}
elif path == "/health":
status, body = 200, {"status": "ok"}
elif path == "/version":
status, body = 200, {"version": "demo"}
else:
status, body = 404, {"error": "not found"}
payload = json.dumps(body).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(payload)))
if status == 405:
self.send_header("Allow", "GET, HEAD")
self.end_headers()
if not head:
self.wfile.write(payload)
print(json.dumps({"level": "INFO", "status": status}), file=sys.stderr, flush=True)
def do_GET(self):
self.respond()
def do_HEAD(self):
self.respond(head=True)
def do_POST(self):
self.respond(unsupported=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--port", type=int, default=8080)
args = parser.parse_args()
if not 0 <= args.port <= 65535:
parser.error("port must be 0..65535 (0 chooses an available port)")
try:
with ThreadingHTTPServer(("127.0.0.1", args.port), Handler) as server:
print(f"http://127.0.0.1:{server.server_port}", flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
except OSError as exc:
print(f"local demo: {type(exc).__name__}", file=sys.stderr)
return 2
return 0
if __name__ == "__main__":
raise SystemExit(main())