fix(security): close MEDIUM ASVS findings — JWT pinning, SSE tickets, SSRF, mTLS pin, rate limits + correctness bugs
Auth (V2.1.1/V3.1.2, V2.1.3, V3.1.1): - Pin JWT iss/aud/typ at mint and require+verify them at decode; revocation (jti denylist + tokens_valid_from) still enforced. - Change-password now requires min_length=12. - SSE auth moves off JWT-in-URL to a single-use 60s opaque ticket (POST /auth/sse-ticket); raw JWT in query no longer authenticates a stream. Removed dead fail-open get_stream_user helper. Egress (V5.1.1, V9.1.1/V14.1.3): - Webhook delivery + CRUD reject SSRF destinations (private/loopback/link-local/ metadata, IPv4-mapped, multi-A-record) via resolved-IP validation, pin to the vetted IP, and never auto-follow redirects. Opt-out via DECNET_WEBHOOK_ALLOW_PRIVATE. - UpdaterClient pins the worker leaf cert SHA-256 against the stored per-host fingerprint (fail closed on missing/mismatch); DECNET_VERIFY_HOSTNAME now defaults True. Hardening (V13.1.3, V4.1.4, V13.1.2): - Rate-limit change-password (5/min), enroll-bundle (10/min), webhook-create (20/min), host-delete (20/min) via the existing slowapi limiter. - Correct false 'global auth middleware' comment; document enroll-bundle proxy trust. Correctness (BUG-7..11): - BUG-7 unbound bus in finally; BUG-8 apply_ceiling clamps to min(base,ceiling); BUG-9 commit before emit; BUG-10 multi-actor rearm for sub-threshold identities; BUG-11 normalize naive timestamps to UTC. Already-closed (no change): V14.1.1, V2.1.2/V3.1.3, V5.1.2. Tests added for every fix; unanimous adversarial review.
This commit is contained in:
@@ -223,3 +223,62 @@ async def test_independent_dedup_per_identity(
|
||||
seen = {c["payload"]["identity_uuid"] for c in captured}
|
||||
assert seen == {iuid_a, iuid_b}
|
||||
await bus.close()
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_rearms_for_sub_threshold_identity_in_candidates(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""BUG-10 regression: seen_now.add() must run AFTER the threshold guard.
|
||||
|
||||
If an identity is returned by the repo with < MULTI_ACTOR_MIN_PRIMITIVES
|
||||
(defensive path) it must NOT be added to seen_now. That means it stays
|
||||
absent from seen_now → gets removed from last_fired on the stale-rearm
|
||||
sweep → re-fires when primitives climb back above threshold.
|
||||
|
||||
Before fix: seen_now.add() ran before the continue, so the identity
|
||||
was treated as present-and-seen even though it was below threshold,
|
||||
and last_fired was never cleared → no rearm.
|
||||
"""
|
||||
bus = FakeBus()
|
||||
await bus.connect()
|
||||
captured: list[dict[str, Any]] = []
|
||||
|
||||
async def cap(_b, t, p, *, event_type=""):
|
||||
captured.append({"topic": t, "payload": p})
|
||||
|
||||
monkeypatch.setattr(_aw, "publish_safely", cap)
|
||||
|
||||
iuid = "test-rearm-uuid"
|
||||
|
||||
class _StubRepo:
|
||||
def __init__(self, entries: list[dict]) -> None:
|
||||
self._entries = entries
|
||||
|
||||
async def list_multi_actor_identities(self) -> list[dict]:
|
||||
return list(self._entries)
|
||||
|
||||
# First tick: identity fires with 2 primitives.
|
||||
repo_above = _StubRepo([
|
||||
{"identity_uuid": iuid, "primitives": ["prim.a", "prim.b"]},
|
||||
])
|
||||
last_fired: dict[str, Any] = {}
|
||||
await _aw.tick_multi_actor(bus, repo_above, last_fired) # type: ignore[arg-type]
|
||||
assert len(captured) == 1
|
||||
assert iuid in last_fired
|
||||
|
||||
# Second tick: identity returned by repo but with only 1 primitive
|
||||
# (sub-threshold defensive path). last_fired[iuid] must be cleared.
|
||||
repo_below = _StubRepo([
|
||||
{"identity_uuid": iuid, "primitives": ["prim.a"]},
|
||||
])
|
||||
await _aw.tick_multi_actor(bus, repo_below, last_fired) # type: ignore[arg-type]
|
||||
assert iuid not in last_fired, (
|
||||
"sub-threshold identity must be removed from last_fired so it re-arms"
|
||||
)
|
||||
|
||||
# Third tick: identity climbs back above threshold — must re-fire.
|
||||
await _aw.tick_multi_actor(bus, repo_above, last_fired) # type: ignore[arg-type]
|
||||
assert len(captured) == 2, "identity must re-fire after rearm"
|
||||
|
||||
await bus.close()
|
||||
|
||||
@@ -235,3 +235,69 @@ def test_multiple_rotations_increment_counter(engine, now):
|
||||
row = session.exec(select(AttackerFingerprintState)).one()
|
||||
assert row.rotation_count == 2
|
||||
assert row.last_hash == "h3"
|
||||
|
||||
|
||||
def test_emit_after_commit_raising_publish_does_not_lose_row(engine, now) -> None:
|
||||
"""BUG-9 regression: publish_fn is called AFTER session.commit().
|
||||
|
||||
A raising publish_fn must not roll back / lose the committed rotation
|
||||
row. Before fix, publish was called before commit so a raise in
|
||||
publish_fn left the session without a commit and the state row was lost.
|
||||
"""
|
||||
later = now + timedelta(hours=1)
|
||||
|
||||
call_order: list[str] = []
|
||||
|
||||
class _OrderRecorder:
|
||||
def __call__(self, event_type: str, payload: dict) -> None:
|
||||
call_order.append("emit")
|
||||
raise RuntimeError("downstream unavailable")
|
||||
|
||||
publish = _OrderRecorder()
|
||||
|
||||
with Session(engine) as session:
|
||||
# Patch session.commit to record ordering.
|
||||
original_commit = session.commit
|
||||
|
||||
def _recording_commit() -> None:
|
||||
call_order.append("commit")
|
||||
original_commit()
|
||||
|
||||
session.commit = _recording_commit # type: ignore[method-assign]
|
||||
|
||||
_seed_attacker(session)
|
||||
|
||||
with Session(engine) as session:
|
||||
original_commit2 = session.commit
|
||||
|
||||
def _recording_commit2() -> None:
|
||||
call_order.append("commit")
|
||||
original_commit2()
|
||||
|
||||
session.commit = _recording_commit2 # type: ignore[method-assign]
|
||||
|
||||
# first_sighting — no publish yet
|
||||
record_fingerprint(
|
||||
session,
|
||||
attacker_ip="1.2.3.4", port=22, probe_type="hassh",
|
||||
new_hash="h1", ts=now,
|
||||
)
|
||||
call_order.clear()
|
||||
|
||||
# rotation — publish_fn raises after commit
|
||||
outcome = record_fingerprint(
|
||||
session,
|
||||
attacker_ip="1.2.3.4", port=22, probe_type="hassh",
|
||||
new_hash="h2", ts=later,
|
||||
publish_fn=publish,
|
||||
)
|
||||
|
||||
assert outcome.kind == "rotated"
|
||||
# commit must come before emit
|
||||
assert call_order.index("commit") < call_order.index("emit")
|
||||
|
||||
# The rotation row must be persisted despite publish raising
|
||||
with Session(engine) as session:
|
||||
row = session.exec(select(AttackerFingerprintState)).one()
|
||||
assert row.last_hash == "h2"
|
||||
assert row.rotation_count == 1
|
||||
|
||||
@@ -9,6 +9,8 @@ must agree with the collector's ``parse_rfc5424`` so that
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timezone
|
||||
|
||||
from decnet.correlation.parser import parse_line
|
||||
|
||||
|
||||
@@ -71,3 +73,41 @@ def test_outer_msgid_set_does_not_recurse() -> None:
|
||||
assert e.event_type == "auth_attempt"
|
||||
assert e.decky == "omega-decky"
|
||||
assert e.service == "auth-helper"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# BUG-11 regression: naive datetime normalization
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_NAIVE_TS_LINE = (
|
||||
"<14>1 2026-05-02T06:22:48.089309 omega-decky smtp - disconnect "
|
||||
"[relay@55555 src_ip=\"10.0.0.1\"]"
|
||||
)
|
||||
|
||||
_AWARE_TS_LINE = (
|
||||
"<14>1 2026-05-02T06:22:48.089309+00:00 omega-decky smtp - disconnect "
|
||||
"[relay@55555 src_ip=\"10.0.0.2\"]"
|
||||
)
|
||||
|
||||
|
||||
def test_naive_timestamp_normalized_to_utc() -> None:
|
||||
"""BUG-11 regression: a log line with a naïve ISO timestamp (no tz offset)
|
||||
must parse to a tz-aware UTC datetime so it sorts alongside aware ones
|
||||
without TypeError. Before fix, fromisoformat returned a naïve datetime
|
||||
which crashed min/max/sort with aware datetimes downstream."""
|
||||
e = parse_line(_NAIVE_TS_LINE)
|
||||
assert e is not None
|
||||
assert e.timestamp.tzinfo is not None
|
||||
assert e.timestamp.tzinfo == timezone.utc
|
||||
|
||||
|
||||
def test_naive_and_aware_timestamps_sortable_together() -> None:
|
||||
"""A naïve-source entry and an aware-source entry must compare
|
||||
without raising TypeError."""
|
||||
naive_entry = parse_line(_NAIVE_TS_LINE)
|
||||
aware_entry = parse_line(_AWARE_TS_LINE)
|
||||
assert naive_entry is not None
|
||||
assert aware_entry is not None
|
||||
# min/max would raise TypeError pre-fix
|
||||
earliest = min(naive_entry.timestamp, aware_entry.timestamp)
|
||||
assert earliest is not None
|
||||
|
||||
Reference in New Issue
Block a user