feat: prefilter journal reads from acl process allowlist
This commit is contained in:
parent
6e515bfbc6
commit
d140d7db94
Binary file not shown.
|
|
@ -3,7 +3,7 @@ from __future__ import annotations
|
|||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from collections.abc import Callable, Mapping
|
||||
from collections.abc import Callable, Iterable, Mapping
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
|
|
@ -152,6 +152,37 @@ def _metadata_mapping(
|
|||
return value if isinstance(value, Mapping) else None
|
||||
|
||||
|
||||
def _metadata_names(record: SourceRegistryRecord, key: str) -> tuple[str, ...]:
|
||||
value = record.metadata.get(key)
|
||||
if value is None:
|
||||
return ()
|
||||
if isinstance(value, str):
|
||||
values: Iterable[Any] = (value,)
|
||||
elif isinstance(value, Mapping):
|
||||
values = value.keys()
|
||||
elif isinstance(value, Iterable):
|
||||
values = value
|
||||
else:
|
||||
normalized = str(value).strip()
|
||||
return () if not normalized else (normalized,)
|
||||
names: list[str] = []
|
||||
for candidate in values:
|
||||
normalized = str(candidate).strip()
|
||||
if normalized and normalized not in names:
|
||||
names.append(normalized)
|
||||
return tuple(names)
|
||||
|
||||
|
||||
def _merge_names(*groups: tuple[str, ...]) -> tuple[str, ...]:
|
||||
merged: list[str] = []
|
||||
for group in groups:
|
||||
for candidate in group:
|
||||
normalized = candidate.strip()
|
||||
if normalized and normalized not in merged:
|
||||
merged.append(normalized)
|
||||
return tuple(merged)
|
||||
|
||||
|
||||
def _source_kind_has_cache_rules(
|
||||
acl_policy: SourceAclConfig | None, source_kind: str
|
||||
) -> bool:
|
||||
|
|
@ -178,8 +209,11 @@ def _build_journal_adapter(
|
|||
),
|
||||
dispatcher=dispatcher,
|
||||
filter_template=JournalFilter(
|
||||
source_names=_metadata_mapping(record, "source_names"),
|
||||
process_names=_metadata_mapping(record, "process_names"),
|
||||
source_names=_metadata_names(record, "source_names"),
|
||||
process_names=_merge_names(
|
||||
_metadata_names(record, "process_names"),
|
||||
acl_policy.journal_process_names,
|
||||
),
|
||||
field_matches=_metadata_mapping(record, "field_matches"),
|
||||
),
|
||||
clock=clock,
|
||||
|
|
|
|||
|
|
@ -28,6 +28,20 @@ def _strip(value: Any, label: str) -> str:
|
|||
return normalized
|
||||
|
||||
|
||||
def _normalize_process_names(values: Any | None) -> tuple[str, ...]:
|
||||
if values is None:
|
||||
return ()
|
||||
if isinstance(values, str):
|
||||
values = (values,)
|
||||
normalized: list[str] = []
|
||||
for value in values:
|
||||
name = _strip(value, "journal_process_names")
|
||||
if name == "*" or name in normalized:
|
||||
continue
|
||||
normalized.append(name)
|
||||
return tuple(normalized)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AclRule:
|
||||
selector_name: str
|
||||
|
|
@ -114,6 +128,14 @@ class AclDecision:
|
|||
class SourceAclConfig:
|
||||
journal: tuple[AclRule, ...] = ()
|
||||
dbus: tuple[AclRule, ...] = ()
|
||||
journal_process_names: tuple[str, ...] = ()
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(
|
||||
self,
|
||||
"journal_process_names",
|
||||
_normalize_process_names(self.journal_process_names),
|
||||
)
|
||||
|
||||
def decision_for_journal(
|
||||
self, *, process_name: str | None, message: str | None
|
||||
|
|
@ -283,15 +305,24 @@ def _parse_acl_rules(raw_rules: Any, source_kind: str) -> tuple[AclRule, ...]:
|
|||
)
|
||||
|
||||
|
||||
def _journal_process_names_from_rules(rules: tuple[AclRule, ...]) -> tuple[str, ...]:
|
||||
return _normalize_process_names(
|
||||
rule.selector_name for rule in rules if rule.selector_name != "*"
|
||||
)
|
||||
|
||||
|
||||
def load_acl_config_from_mapping(raw: Mapping[str, Any]) -> SourceAclConfig:
|
||||
acl_section = raw.get("acl")
|
||||
if acl_section is None:
|
||||
return SourceAclConfig()
|
||||
if not isinstance(acl_section, Mapping):
|
||||
raise AclConfigError("acl section must be a mapping")
|
||||
journal_rules = _parse_acl_rules(acl_section.get("journal"), "journal")
|
||||
dbus_rules = _parse_acl_rules(acl_section.get("dbus"), "dbus")
|
||||
return SourceAclConfig(
|
||||
journal=_parse_acl_rules(acl_section.get("journal"), "journal"),
|
||||
dbus=_parse_acl_rules(acl_section.get("dbus"), "dbus"),
|
||||
journal=journal_rules,
|
||||
dbus=dbus_rules,
|
||||
journal_process_names=_journal_process_names_from_rules(journal_rules),
|
||||
)
|
||||
|
||||
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -10,7 +10,7 @@ import pytest
|
|||
|
||||
from app.adapters.dbus_wpa import DbusSignalEvent, DbusWpaAdapter
|
||||
from tests.support.fake_dbus_client import FakeDbusClient
|
||||
from app.adapters.journal.adapter import JournalAdapter
|
||||
from app.adapters import JournalAdapter, JournalFilter
|
||||
from app.core.acl import (
|
||||
AclConfigError,
|
||||
AclRuleParseError,
|
||||
|
|
@ -48,6 +48,19 @@ class FakeJournalReader:
|
|||
def __init__(self, entries: list[dict[str, object]]) -> None:
|
||||
self.entries = list(entries)
|
||||
self.calls: list[tuple[object, int | None]] = []
|
||||
self.returned_entries: list[dict[str, object]] = []
|
||||
|
||||
@staticmethod
|
||||
def _matches_process_names(
|
||||
entry: dict[str, object], names: tuple[str, ...]
|
||||
) -> bool:
|
||||
if not names:
|
||||
return True
|
||||
for key in ("_COMM", "SYSLOG_IDENTIFIER"):
|
||||
value = entry.get(key)
|
||||
if isinstance(value, str) and value.strip() in names:
|
||||
return True
|
||||
return False
|
||||
|
||||
async def read(
|
||||
self, journal_filter, *, limit: int | None = None
|
||||
|
|
@ -60,7 +73,13 @@ class FakeJournalReader:
|
|||
)
|
||||
batch = self.entries[:batch_size]
|
||||
self.entries = self.entries[batch_size:]
|
||||
return list(batch)
|
||||
filtered = [
|
||||
dict(entry)
|
||||
for entry in batch
|
||||
if self._matches_process_names(entry, journal_filter.process_names)
|
||||
]
|
||||
self.returned_entries.extend(filtered)
|
||||
return filtered
|
||||
|
||||
|
||||
async def _run_acl_config_scenario(tmp_path: Path) -> None:
|
||||
|
|
@ -157,17 +176,33 @@ async def _run_journal_acl_ingress_scenario() -> None:
|
|||
{
|
||||
"__CURSOR": "s=1",
|
||||
"__REALTIME_TIMESTAMP": BASE_TIME,
|
||||
"_COMM": "uvicorn",
|
||||
"MESSAGE": "application log line",
|
||||
},
|
||||
{
|
||||
"__CURSOR": "s=2",
|
||||
"__REALTIME_TIMESTAMP": BASE_TIME,
|
||||
"_COMM": "sshd",
|
||||
"MESSAGE": "Accepted publickey for alice",
|
||||
},
|
||||
{
|
||||
"__CURSOR": "s=2",
|
||||
"__CURSOR": "s=3",
|
||||
"__REALTIME_TIMESTAMP": BASE_TIME,
|
||||
"_COMM": "cron",
|
||||
"MESSAGE": "periodic job completed",
|
||||
},
|
||||
]
|
||||
)
|
||||
acl_policy = load_acl_config_from_mapping(
|
||||
{
|
||||
"acl": {
|
||||
"journal": [
|
||||
'cache process sshd regexp "^Accepted" send urgent scope scan123 transport alerts',
|
||||
'drop process cron regexp ".*"',
|
||||
]
|
||||
}
|
||||
}
|
||||
)
|
||||
adapter = JournalAdapter(
|
||||
source_key="journal-main",
|
||||
source_id=SOURCE_ID,
|
||||
|
|
@ -176,19 +211,8 @@ async def _run_journal_acl_ingress_scenario() -> None:
|
|||
dispatcher=dispatcher,
|
||||
clock=FrozenClock(BASE_TIME),
|
||||
poll_interval_seconds=0.0,
|
||||
acl_policy=SourceAclConfig(
|
||||
journal=(
|
||||
AclRule(
|
||||
selector_name="sshd",
|
||||
message_regex="^Accepted",
|
||||
cache_policy="cache",
|
||||
send_policy="urgent",
|
||||
scope="scan123",
|
||||
transport_name="alerts",
|
||||
),
|
||||
AclRule(selector_name="cron", message_regex=".*", cache_policy="drop"),
|
||||
)
|
||||
),
|
||||
filter_template=JournalFilter(process_names=acl_policy.journal_process_names),
|
||||
acl_policy=acl_policy,
|
||||
)
|
||||
|
||||
manager.register(adapter)
|
||||
|
|
@ -205,6 +229,8 @@ async def _run_journal_acl_ingress_scenario() -> None:
|
|||
assert envelope.body["_COMM"] == "sshd"
|
||||
assert queue.empty()
|
||||
assert reader.calls
|
||||
assert reader.calls[0][0].process_names == ("sshd", "cron")
|
||||
assert all(entry["_COMM"] != "uvicorn" for entry in reader.returned_entries)
|
||||
|
||||
stopped = await manager.stop("journal-main")
|
||||
assert stopped.running is False
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ def test_acl_rules_parse_cache_drop_and_metadata() -> None:
|
|||
"journal": [
|
||||
'cache process sshd regexp "^Accepted" send urgent scope scan123 transport alerts',
|
||||
'drop process cron regexp ".*"',
|
||||
'cache process sshd regexp ".*"',
|
||||
],
|
||||
"dbus": ['cache process wpa_supplicant regexp ".*"'],
|
||||
}
|
||||
|
|
@ -44,6 +45,7 @@ def test_acl_rules_parse_cache_drop_and_metadata() -> None:
|
|||
assert journal_allow.rule.to_dict()["transport"] == "alerts"
|
||||
assert "mark" not in journal_allow.rule.to_dict()
|
||||
assert journal_drop.allowed is False
|
||||
assert config.journal_process_names == ("sshd", "cron")
|
||||
assert dbus_allow.allowed is True
|
||||
assert dbus_allow.rule is not None
|
||||
assert dbus_allow.rule.cache_policy == "cache"
|
||||
|
|
@ -69,6 +71,7 @@ def test_acl_defaults_to_drop_when_source_rules_are_missing_or_empty() -> None:
|
|||
).allowed
|
||||
is False
|
||||
)
|
||||
assert config.journal_process_names == ()
|
||||
|
||||
|
||||
def test_acl_rule_validation_and_file_loading(tmp_path: Path) -> None:
|
||||
|
|
|
|||
|
|
@ -0,0 +1,59 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.bootstrap import _build_journal_adapter
|
||||
from app.core.acl import load_acl_config_from_mapping
|
||||
from app.core.clock import FrozenClock
|
||||
from app.core.config import Settings
|
||||
from app.storage.repositories import SourceRegistryRecord
|
||||
|
||||
|
||||
def test_build_journal_adapter_merges_acl_process_allowlist() -> None:
|
||||
settings = Settings.model_validate(
|
||||
{
|
||||
"config_path": "wf-agent.toml",
|
||||
"env_path": ".env",
|
||||
"database_dsn": "sqlite+aiosqlite:///tmp/test-db.sqlite",
|
||||
"wifi_interface_name": "wlan0",
|
||||
"cache_ttl_seconds": 60,
|
||||
"history_ttl_seconds": 120,
|
||||
}
|
||||
)
|
||||
record = SourceRegistryRecord(
|
||||
id="11111111-1111-1111-1111-111111111111",
|
||||
source_key="journal-main",
|
||||
source_kind="journal",
|
||||
display_name="Journal Main",
|
||||
metadata={
|
||||
"source_names": ["journal-main"],
|
||||
"process_names": ["daemon", "sshd"],
|
||||
},
|
||||
created_at=datetime(2026, 4, 13, 12, 0, tzinfo=timezone.utc),
|
||||
updated_at=datetime(2026, 4, 13, 12, 0, tzinfo=timezone.utc),
|
||||
)
|
||||
acl_policy = load_acl_config_from_mapping(
|
||||
{
|
||||
"acl": {
|
||||
"journal": [
|
||||
'cache process sshd regexp ".*"',
|
||||
'drop process cron regexp ".*"',
|
||||
'cache process sshd regexp ".*"',
|
||||
]
|
||||
}
|
||||
}
|
||||
)
|
||||
bootstrap = SimpleNamespace(session_factory=object())
|
||||
|
||||
adapter = _build_journal_adapter(
|
||||
record,
|
||||
bootstrap,
|
||||
settings,
|
||||
acl_policy,
|
||||
dispatcher=object(),
|
||||
clock=FrozenClock(datetime(2026, 4, 13, 12, 0, tzinfo=timezone.utc)),
|
||||
)
|
||||
|
||||
assert adapter.filter_template.source_names == ("journal-main",)
|
||||
assert adapter.filter_template.process_names == ("daemon", "sshd", "cron")
|
||||
Loading…
Reference in New Issue