добавлены ACL процессов и сообщений вместо просто перечня имён разрешённых процессов
This commit is contained in:
parent
c1a8bb29d7
commit
86c04c3712
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
## Summary
|
||||
|
||||
`journal-event-collector` is a Linux application that reads journal messages from configured process names, turns them into events, caches them with expiry, and exposes the shared core through a REST API and a CLI.
|
||||
`journal-event-collector` is a Linux application that reads journal messages through configured ACL rules, turns matching messages into events, caches them with expiry, and exposes the shared core through a REST API and a CLI.
|
||||
|
||||
The project is built around one core layer with thin adapters for the daemon runtime, API, and CLI. Active events live in memory, while persisted snapshots are stored in SQLite so local and remote inspection can read the same state.
|
||||
|
||||
|
|
@ -52,12 +52,12 @@ Data flow:
|
|||
### `config.py`
|
||||
- Loads TOML configuration.
|
||||
- Validates required fields.
|
||||
- Normalizes monitored process names, cache timing, API settings, and SQLite state file path.
|
||||
- Validates ACL rules, cache timing, API settings, and SQLite state file path.
|
||||
|
||||
### `journal.py`
|
||||
- Launches `journalctl`.
|
||||
- Reads JSON journal records.
|
||||
- Filters entries by configured process names.
|
||||
- Filters entries by configured message ACL rules.
|
||||
- Builds domain events from journal entries.
|
||||
|
||||
### `models.py`
|
||||
|
|
|
|||
|
|
@ -36,13 +36,17 @@ python -m pip install -e .
|
|||
|
||||
1. Create the service config directory.
|
||||
2. Copy or adapt the example config from `journal-event-collector/example-config.toml`.
|
||||
3. Set monitored process names, REST binding, journal command, and the SQLite state file.
|
||||
3. Set the message ACL, REST binding, journal command, and the SQLite state file.
|
||||
|
||||
Example:
|
||||
|
||||
```toml
|
||||
message_acl = [
|
||||
'cache process sshd regexp "^Accepted" send urgent mark scan123',
|
||||
'drop process cron regexp ".*"',
|
||||
]
|
||||
|
||||
[application]
|
||||
monitored_process_names = ["sshd", "cron"]
|
||||
event_ttl_seconds = 300
|
||||
cleanup_interval_seconds = 30
|
||||
log_level = "info"
|
||||
|
|
|
|||
|
|
@ -79,7 +79,7 @@ or:
|
|||
GET /status
|
||||
```
|
||||
|
||||
Returns the live daemon state, configured process names, cache size, TTL, cleanup interval, and the last error if any.
|
||||
Returns the live daemon state, active message ACL, cache size, TTL, cleanup interval, and the last error if any.
|
||||
|
||||
### Cached events
|
||||
|
||||
|
|
@ -107,10 +107,14 @@ Returns the persisted SQLite snapshot directly:
|
|||
|
||||
## Configuration Notes
|
||||
|
||||
1. `monitored_process_names` controls which journal sources become events.
|
||||
2. `event_ttl_seconds` controls how long events remain in cache and in the persisted snapshot.
|
||||
3. `cleanup_interval_seconds` controls how often expired events are purged.
|
||||
4. `storage.state_file` should point to the SQLite database used for persisted state.
|
||||
1. `message_acl` controls which journal messages become events and how they are classified.
|
||||
2. The config uses a single `message_acl` array of one-line ACL strings.
|
||||
3. If `message_acl` is omitted or empty, the default policy is to drop all messages.
|
||||
4. `cache = "drop"` suppresses event creation for matching messages.
|
||||
5. `cache = "cache"` stores the event and records `send` and `mark` in the cached event metadata.
|
||||
6. `event_ttl_seconds` controls how long events remain in cache and in the persisted snapshot.
|
||||
7. `cleanup_interval_seconds` controls how often expired events are purged.
|
||||
8. `storage.state_file` should point to the SQLite database used for persisted state.
|
||||
|
||||
## Common Issues
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,9 @@
|
|||
message_acl = [
|
||||
'cache process sshd regexp "^Accepted" send urgent mark scan123',
|
||||
'drop process cron regexp ".*"',
|
||||
]
|
||||
|
||||
[application]
|
||||
monitored_process_names = ["sshd", "cron"]
|
||||
event_ttl_seconds = 300
|
||||
cleanup_interval_seconds = 30
|
||||
log_level = "info"
|
||||
|
|
|
|||
|
|
@ -2,19 +2,19 @@
|
|||
|
||||
## Introduction
|
||||
|
||||
This feature defines a Linux daemon that monitors configured journal sources by process name, turns matching journal messages into application events, caches those events for a configurable retention period, and exposes the shared functionality through both a REST API and a CLI. The application is intended to run under `systemd` and uses a common application core for all interfaces.
|
||||
This feature defines a Linux daemon that evaluates configured ACL rules against journal messages, turns matching messages into application events, caches those events for a configurable retention period, and exposes the shared functionality through both a REST API and a CLI. The application is intended to run under `systemd` and uses a common application core for all interfaces.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement 1: Configure monitored journal sources
|
||||
### Requirement 1: Configure journal message ACLs
|
||||
|
||||
**User Story:** As an operator, I want to configure which process names are monitored, so that the daemon collects only relevant journal messages.
|
||||
**User Story:** As an operator, I want to configure ACL rules for journal messages, so that the daemon collects only relevant journal messages.
|
||||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN the application starts with a valid configuration file or equivalent configuration source THEN the system SHALL load the configured process names and journal settings before starting event collection.
|
||||
1. WHEN the application starts with a valid configuration file or equivalent configuration source THEN the system SHALL load the configured ACL rules and journal settings before starting event collection.
|
||||
2. IF the configuration is missing required values or contains invalid values THEN the system SHALL fail startup with a clear error that identifies the invalid setting.
|
||||
3. WHEN the monitored process-name list is updated and the application is restarted THEN the system SHALL use the updated configuration for subsequent journal collection.
|
||||
3. WHEN the ACL rule list is updated and the application is restarted THEN the system SHALL use the updated configuration for subsequent journal collection.
|
||||
4. WHERE configuration values affect both the REST API and CLI THEN the system SHALL resolve them through the same shared application core.
|
||||
|
||||
### Requirement 2: Run as a Linux daemon under systemd
|
||||
|
|
@ -34,8 +34,8 @@ This feature defines a Linux daemon that monitors configured journal sources by
|
|||
|
||||
#### Acceptance Criteria
|
||||
|
||||
1. WHEN a journal message is received from a configured process name THEN the system SHALL create an event record from the message.
|
||||
2. WHEN a journal message does not match any configured process name THEN the system SHALL ignore the message for event creation.
|
||||
1. WHEN a journal message matches a configured ACL rule THEN the system SHALL create an event record from the message unless the rule is configured to drop it.
|
||||
2. WHEN a journal message does not match any configured ACL rule THEN the system SHALL ignore the message for event creation.
|
||||
3. WHEN an event is created THEN the system SHALL preserve at least the source process name, message payload, and capture timestamp.
|
||||
4. WHILE journal collection is running THEN the system SHALL continue processing new messages without requiring manual restart after each event.
|
||||
5. IF a journal entry cannot be parsed or read THEN the system SHALL log the failure and continue processing subsequent journal messages.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
"""Journal event collector application package."""
|
||||
|
||||
from .config import AppConfig, ConfigError
|
||||
from .models import JournalEvent, ServiceStatus
|
||||
from .models import JournalEvent, MessageAclRule, ServiceStatus
|
||||
|
||||
__all__ = ["AppConfig", "ConfigError", "JournalEvent", "ServiceStatus"]
|
||||
__all__ = ["AppConfig", "ConfigError", "JournalEvent", "MessageAclRule", "ServiceStatus"]
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ from datetime import datetime
|
|||
from typing import Any, Iterable
|
||||
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from .models import JournalEvent
|
||||
from .service import ApplicationCore
|
||||
|
|
@ -19,6 +19,17 @@ class EventResponse(BaseModel):
|
|||
message: str
|
||||
captured_at: datetime
|
||||
payload: dict[str, Any]
|
||||
acl: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class MessageAclRuleResponse(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
process_name: str
|
||||
message_regex: str
|
||||
cache: str
|
||||
send: str | None = None
|
||||
mark: str | None = None
|
||||
|
||||
|
||||
class StatusResponse(BaseModel):
|
||||
|
|
@ -26,11 +37,11 @@ class StatusResponse(BaseModel):
|
|||
|
||||
running: bool
|
||||
started_at: datetime | None
|
||||
monitored_process_names: list[str]
|
||||
cached_events: int
|
||||
event_ttl_seconds: int
|
||||
cleanup_interval_seconds: int
|
||||
last_error: str | None
|
||||
message_acl: list[MessageAclRuleResponse]
|
||||
|
||||
|
||||
class StateSnapshotResponse(BaseModel):
|
||||
|
|
|
|||
|
|
@ -2,34 +2,18 @@ from __future__ import annotations
|
|||
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
from typing import Any, Mapping
|
||||
import tomllib
|
||||
|
||||
from .models import MessageAclRule
|
||||
|
||||
|
||||
class ConfigError(ValueError):
|
||||
"""Raised when the application configuration is invalid."""
|
||||
|
||||
|
||||
def _require_str_list(value: Any, field_name: str) -> list[str]:
|
||||
if not isinstance(value, list) or not value:
|
||||
raise ConfigError(f"{field_name} must be a non-empty list of process names")
|
||||
|
||||
result: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for item in value:
|
||||
if not isinstance(item, str) or not item.strip():
|
||||
raise ConfigError(f"{field_name} must contain only non-empty strings")
|
||||
normalized = item.strip()
|
||||
key = normalized.casefold()
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
result.append(normalized)
|
||||
if not result:
|
||||
raise ConfigError(f"{field_name} must contain at least one process name")
|
||||
return result
|
||||
|
||||
|
||||
def _require_positive_int(value: Any, field_name: str) -> int:
|
||||
try:
|
||||
parsed = int(value)
|
||||
|
|
@ -40,9 +24,196 @@ def _require_positive_int(value: Any, field_name: str) -> int:
|
|||
return parsed
|
||||
|
||||
|
||||
def _default_message_acl() -> list[MessageAclRule]:
|
||||
return [MessageAclRule(process_name="*", message_regex=".*", cache_policy="drop")]
|
||||
|
||||
|
||||
def _require_message_acl(value: Any) -> list[MessageAclRule]:
|
||||
if value is None:
|
||||
return _default_message_acl()
|
||||
if isinstance(value, list):
|
||||
rules_value = value
|
||||
if not rules_value:
|
||||
return _default_message_acl()
|
||||
elif isinstance(value, Mapping):
|
||||
rules_value = value.get("rules")
|
||||
if rules_value is None:
|
||||
return _default_message_acl()
|
||||
if not isinstance(rules_value, list):
|
||||
raise ConfigError("message_acl must be a list of ACL rule strings")
|
||||
if not rules_value:
|
||||
return _default_message_acl()
|
||||
else:
|
||||
raise ConfigError("message_acl must be a list of ACL rule strings")
|
||||
|
||||
rules: list[MessageAclRule] = []
|
||||
for index, item in enumerate(rules_value):
|
||||
rules.append(_parse_message_acl_rule(item, index))
|
||||
|
||||
return rules
|
||||
|
||||
|
||||
def _parse_message_acl_rule(value: Any, index: int) -> MessageAclRule:
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise ConfigError(f"message_acl[{index}] must be a non-empty string")
|
||||
|
||||
raw_rule = value.strip()
|
||||
try:
|
||||
tokens = shlex.split(raw_rule)
|
||||
except ValueError as exc:
|
||||
raise ConfigError(f"message_acl[{index}] is invalid: {exc}") from exc
|
||||
if not tokens:
|
||||
raise ConfigError(f"message_acl[{index}] must not be empty")
|
||||
|
||||
if "=" in tokens[0]:
|
||||
return _parse_message_acl_key_value_rule(tokens, index)
|
||||
return _parse_message_acl_positional_rule(tokens, index)
|
||||
|
||||
|
||||
def _parse_message_acl_key_value_rule(tokens: list[str], index: int) -> MessageAclRule:
|
||||
fields: dict[str, str] = {}
|
||||
for token in tokens:
|
||||
if "=" not in token:
|
||||
raise ConfigError(
|
||||
f"message_acl[{index}] must use either key=value syntax or the compact DSL"
|
||||
)
|
||||
key, value = token.split("=", 1)
|
||||
key = key.strip().casefold()
|
||||
value = value.strip()
|
||||
if not key:
|
||||
raise ConfigError(f"message_acl[{index}] contains an empty field name")
|
||||
if not value:
|
||||
raise ConfigError(f"message_acl[{index}].{key} must be a non-empty string")
|
||||
if key in fields:
|
||||
raise ConfigError(f"message_acl[{index}] contains duplicate field {key}")
|
||||
fields[key] = value
|
||||
|
||||
process_name = fields.get("process_name") or fields.get("process")
|
||||
message_regex = fields.get("message_regex") or fields.get("regexp")
|
||||
cache_policy = fields.get("cache")
|
||||
send_policy = fields.get("send")
|
||||
mark = fields.get("mark")
|
||||
return _build_message_acl_rule(process_name, message_regex, cache_policy, send_policy, mark, index)
|
||||
|
||||
|
||||
def _parse_message_acl_positional_rule(tokens: list[str], index: int) -> MessageAclRule:
|
||||
if len(tokens) < 4:
|
||||
raise ConfigError(
|
||||
f"message_acl[{index}] must look like: cache process <name> regexp <pattern> [send <urgent|queue> mark <mark>]"
|
||||
)
|
||||
|
||||
cache_policy = tokens[0].strip().casefold()
|
||||
if cache_policy not in {"cache", "drop"}:
|
||||
raise ConfigError(f"message_acl[{index}] must start with 'cache' or 'drop'")
|
||||
|
||||
position = 1
|
||||
process_name: str | None = None
|
||||
message_regex: str | None = None
|
||||
send_policy: str | None = None
|
||||
mark: str | None = None
|
||||
|
||||
while position < len(tokens):
|
||||
key = tokens[position].strip().casefold()
|
||||
if key in {"process", "process_name"}:
|
||||
position += 1
|
||||
if position >= len(tokens):
|
||||
raise ConfigError(f"message_acl[{index}].process is missing a value")
|
||||
if process_name is not None:
|
||||
raise ConfigError(f"message_acl[{index}] contains duplicate process field")
|
||||
process_name = tokens[position]
|
||||
elif key in {"regexp", "message_regex"}:
|
||||
position += 1
|
||||
if position >= len(tokens):
|
||||
raise ConfigError(f"message_acl[{index}].regexp is missing a value")
|
||||
if message_regex is not None:
|
||||
raise ConfigError(f"message_acl[{index}] contains duplicate regexp field")
|
||||
message_regex = tokens[position]
|
||||
elif key == "send":
|
||||
position += 1
|
||||
if position >= len(tokens):
|
||||
raise ConfigError(f"message_acl[{index}].send is missing a value")
|
||||
if send_policy is not None:
|
||||
raise ConfigError(f"message_acl[{index}] contains duplicate send field")
|
||||
send_policy = tokens[position]
|
||||
elif key == "mark":
|
||||
position += 1
|
||||
if position >= len(tokens):
|
||||
raise ConfigError(f"message_acl[{index}].mark is missing a value")
|
||||
if mark is not None:
|
||||
raise ConfigError(f"message_acl[{index}] contains duplicate mark field")
|
||||
mark = tokens[position]
|
||||
else:
|
||||
raise ConfigError(f"message_acl[{index}] contains unsupported token: {tokens[position]}")
|
||||
position += 1
|
||||
|
||||
if cache_policy == "drop" and (send_policy is not None or mark is not None):
|
||||
raise ConfigError(f"message_acl[{index}] must not define send or mark when cache='drop'")
|
||||
|
||||
return _build_message_acl_rule(process_name, message_regex, cache_policy, send_policy, mark, index)
|
||||
|
||||
|
||||
def _build_message_acl_rule(
|
||||
process_name: str | None,
|
||||
message_regex: str | None,
|
||||
cache_policy: str | None,
|
||||
send_policy: str | None,
|
||||
mark: str | None,
|
||||
index: int,
|
||||
) -> MessageAclRule:
|
||||
if not isinstance(process_name, str) or not process_name.strip():
|
||||
raise ConfigError(f"message_acl[{index}].process_name must be a non-empty string")
|
||||
if not isinstance(message_regex, str) or not message_regex.strip():
|
||||
raise ConfigError(f"message_acl[{index}].message_regex must be a non-empty string")
|
||||
if not isinstance(cache_policy, str) or not cache_policy.strip():
|
||||
raise ConfigError(f"message_acl[{index}].cache must be a non-empty string")
|
||||
|
||||
cache_value = cache_policy.strip().casefold()
|
||||
if cache_value not in {"cache", "drop"}:
|
||||
raise ConfigError(f"message_acl[{index}].cache must be either 'cache' or 'drop'")
|
||||
|
||||
try:
|
||||
if cache_value == "drop":
|
||||
if send_policy is not None:
|
||||
raise ConfigError(f"message_acl[{index}].send is not allowed when cache='drop'")
|
||||
if mark is not None:
|
||||
raise ConfigError(f"message_acl[{index}].mark is not allowed when cache='drop'")
|
||||
return MessageAclRule(
|
||||
process_name=process_name.strip(),
|
||||
message_regex=message_regex.strip(),
|
||||
cache_policy=cache_value,
|
||||
)
|
||||
|
||||
if not isinstance(send_policy, str) or not send_policy.strip():
|
||||
raise ConfigError(
|
||||
f"message_acl[{index}].send must be a non-empty string when cache='cache'"
|
||||
)
|
||||
if not isinstance(mark, str) or not mark.strip():
|
||||
raise ConfigError(
|
||||
f"message_acl[{index}].mark must be a non-empty string when cache='cache'"
|
||||
)
|
||||
return MessageAclRule(
|
||||
process_name=process_name.strip(),
|
||||
message_regex=message_regex.strip(),
|
||||
cache_policy=cache_value,
|
||||
send_policy=send_policy.strip(),
|
||||
mark=mark.strip(),
|
||||
)
|
||||
except re.error as exc:
|
||||
raise ConfigError(
|
||||
f"message_acl[{index}].message_regex must be a valid regular expression"
|
||||
) from exc
|
||||
except ValueError as exc:
|
||||
message = str(exc)
|
||||
if "mark must contain only ASCII letters, digits, underscore, and hyphen" in message:
|
||||
raise ConfigError(f"message_acl[{index}].mark must match ^[A-Za-z0-9_-]+$") from exc
|
||||
if "send must be either 'urgent' or 'queue'" in message:
|
||||
raise ConfigError(f"message_acl[{index}].send must be either 'urgent' or 'queue'") from exc
|
||||
raise ConfigError(f"message_acl[{index}] is invalid: {exc}") from exc
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class AppConfig:
|
||||
monitored_process_names: list[str]
|
||||
message_acl: list[MessageAclRule] = field(default_factory=list)
|
||||
event_ttl_seconds: int = 300
|
||||
cleanup_interval_seconds: int = 60
|
||||
api_host: str = "127.0.0.1"
|
||||
|
|
@ -63,6 +234,7 @@ class AppConfig:
|
|||
api_section = raw.get("api", {})
|
||||
journal_section = raw.get("journal", {})
|
||||
storage_section = raw.get("storage", {})
|
||||
message_acl_raw = raw.get("message_acl")
|
||||
|
||||
if not isinstance(app_section, Mapping):
|
||||
raise ConfigError("application section must be a mapping")
|
||||
|
|
@ -72,10 +244,9 @@ class AppConfig:
|
|||
raise ConfigError("journal section must be a mapping")
|
||||
if storage_section and not isinstance(storage_section, Mapping):
|
||||
raise ConfigError("storage section must be a mapping")
|
||||
if "monitored_process_names" in app_section:
|
||||
raise ConfigError("monitored_process_names is no longer supported; use message_acl")
|
||||
|
||||
monitored_process_names = _require_str_list(
|
||||
app_section.get("monitored_process_names"), "monitored_process_names"
|
||||
)
|
||||
event_ttl_seconds = _require_positive_int(
|
||||
app_section.get("event_ttl_seconds", 300), "event_ttl_seconds"
|
||||
)
|
||||
|
|
@ -108,8 +279,10 @@ class AppConfig:
|
|||
if not state_file.is_absolute() and base_path is not None:
|
||||
state_file = (base_path / state_file).resolve()
|
||||
|
||||
message_acl = _require_message_acl(message_acl_raw)
|
||||
|
||||
return cls(
|
||||
monitored_process_names=monitored_process_names,
|
||||
message_acl=message_acl,
|
||||
event_ttl_seconds=event_ttl_seconds,
|
||||
cleanup_interval_seconds=cleanup_interval_seconds,
|
||||
api_host=api_host,
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ import sys
|
|||
import threading
|
||||
from typing import Any, Protocol
|
||||
|
||||
from .models import JournalEvent
|
||||
from .models import JournalEvent, MessageAclRule
|
||||
|
||||
|
||||
class JournalReader(Protocol):
|
||||
|
|
@ -128,21 +128,23 @@ def extract_timestamp(entry: Mapping[str, Any]) -> datetime:
|
|||
|
||||
def build_event(
|
||||
entry: Mapping[str, Any],
|
||||
monitored_process_names: Iterable[str],
|
||||
message_acl: Iterable[MessageAclRule],
|
||||
) -> JournalEvent | None:
|
||||
process_name = extract_process_name(entry)
|
||||
if process_name is None:
|
||||
return None
|
||||
|
||||
allowed_names = {name.casefold() for name in monitored_process_names}
|
||||
if process_name.casefold() not in allowed_names:
|
||||
return None
|
||||
|
||||
message = extract_message(entry)
|
||||
captured_at = extract_timestamp(entry)
|
||||
return JournalEvent.create(
|
||||
process_name=process_name,
|
||||
message=message,
|
||||
captured_at=captured_at,
|
||||
payload=entry,
|
||||
)
|
||||
for rule in message_acl:
|
||||
if not rule.matches(process_name, message):
|
||||
continue
|
||||
if rule.cache_policy == "drop":
|
||||
return None
|
||||
return JournalEvent.create(
|
||||
process_name=process_name,
|
||||
message=message,
|
||||
captured_at=extract_timestamp(entry),
|
||||
payload=entry,
|
||||
acl=rule.to_dict(),
|
||||
)
|
||||
return None
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ from __future__ import annotations
|
|||
from dataclasses import asdict, dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Mapping
|
||||
import re
|
||||
import uuid
|
||||
|
||||
|
||||
|
|
@ -10,6 +11,60 @@ def utc_now() -> datetime:
|
|||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
_MARK_PATTERN = re.compile(r"^[A-Za-z0-9_-]+$")
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class MessageAclRule:
|
||||
process_name: str
|
||||
message_regex: str
|
||||
cache_policy: str
|
||||
send_policy: str | None = None
|
||||
mark: str | None = None
|
||||
_pattern: re.Pattern[str] = field(init=False, repr=False, compare=False)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
self.process_name = self.process_name.strip()
|
||||
self.message_regex = self.message_regex.strip()
|
||||
self.cache_policy = self.cache_policy.strip().casefold()
|
||||
if self.send_policy is not None:
|
||||
self.send_policy = self.send_policy.strip().casefold()
|
||||
if self.mark is not None:
|
||||
self.mark = self.mark.strip()
|
||||
|
||||
if not self.process_name:
|
||||
raise ValueError("process_name must be a non-empty string")
|
||||
if not self.message_regex:
|
||||
raise ValueError("message_regex must be a non-empty string")
|
||||
if self.cache_policy not in {"cache", "drop"}:
|
||||
raise ValueError("cache must be either 'cache' or 'drop'")
|
||||
if self.send_policy is not None and self.send_policy not in {"urgent", "queue"}:
|
||||
raise ValueError("send must be either 'urgent' or 'queue'")
|
||||
if self.mark is not None and not _MARK_PATTERN.fullmatch(self.mark):
|
||||
raise ValueError("mark must contain only ASCII letters, digits, underscore, and hyphen")
|
||||
if self.cache_policy == "drop":
|
||||
if self.send_policy is not None or self.mark is not None:
|
||||
raise ValueError("drop rules must not define send or mark")
|
||||
else:
|
||||
if self.send_policy is None or self.mark is None:
|
||||
raise ValueError("cache rules must define send and mark")
|
||||
|
||||
self._pattern = re.compile(self.message_regex)
|
||||
|
||||
def matches(self, process_name: str, message: str) -> bool:
|
||||
process_matches = self.process_name == "*" or self.process_name.casefold() == process_name.casefold()
|
||||
return process_matches and self._pattern.search(message) is not None
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"process_name": self.process_name,
|
||||
"message_regex": self.message_regex,
|
||||
"cache": self.cache_policy,
|
||||
"send": self.send_policy,
|
||||
"mark": self.mark,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class JournalEvent:
|
||||
id: str
|
||||
|
|
@ -17,6 +72,7 @@ class JournalEvent:
|
|||
message: str
|
||||
captured_at: datetime
|
||||
payload: dict[str, Any] = field(default_factory=dict)
|
||||
acl: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
@classmethod
|
||||
def create(
|
||||
|
|
@ -25,6 +81,7 @@ class JournalEvent:
|
|||
message: str,
|
||||
captured_at: datetime | None = None,
|
||||
payload: Mapping[str, Any] | None = None,
|
||||
acl: Mapping[str, Any] | None = None,
|
||||
) -> "JournalEvent":
|
||||
return cls(
|
||||
id=str(uuid.uuid4()),
|
||||
|
|
@ -32,6 +89,7 @@ class JournalEvent:
|
|||
message=message,
|
||||
captured_at=captured_at or utc_now(),
|
||||
payload=dict(payload or {}),
|
||||
acl=dict(acl or {}),
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
|
|
@ -44,19 +102,19 @@ class JournalEvent:
|
|||
class ServiceStatus:
|
||||
running: bool
|
||||
started_at: datetime | None
|
||||
monitored_process_names: list[str]
|
||||
cached_events: int
|
||||
event_ttl_seconds: int
|
||||
cleanup_interval_seconds: int
|
||||
last_error: str | None = None
|
||||
message_acl: list[MessageAclRule] = field(default_factory=list)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"running": self.running,
|
||||
"started_at": self.started_at.isoformat() if self.started_at else None,
|
||||
"monitored_process_names": list(self.monitored_process_names),
|
||||
"cached_events": self.cached_events,
|
||||
"event_ttl_seconds": self.event_ttl_seconds,
|
||||
"cleanup_interval_seconds": self.cleanup_interval_seconds,
|
||||
"last_error": self.last_error,
|
||||
"message_acl": [rule.to_dict() for rule in self.message_acl],
|
||||
}
|
||||
|
|
|
|||
|
|
@ -97,7 +97,7 @@ class ApplicationCore:
|
|||
self._record_error(f"cache cleanup failed: {exc}")
|
||||
|
||||
def ingest(self, entry: Mapping[str, Any]) -> JournalEvent | None:
|
||||
event = build_event(entry, self.config.monitored_process_names)
|
||||
event = build_event(entry, self.config.message_acl)
|
||||
if event is None:
|
||||
return None
|
||||
self.cache.put(event, ttl_seconds=self.config.event_ttl_seconds, now=self.clock)
|
||||
|
|
@ -125,11 +125,11 @@ class ApplicationCore:
|
|||
return ServiceStatus(
|
||||
running=self._running and not self._stop_event.is_set(),
|
||||
started_at=self._started_at,
|
||||
monitored_process_names=list(self.config.monitored_process_names),
|
||||
cached_events=self.cache.count(now=self.clock),
|
||||
event_ttl_seconds=self.config.event_ttl_seconds,
|
||||
cleanup_interval_seconds=self.config.cleanup_interval_seconds,
|
||||
last_error=self._last_error,
|
||||
message_acl=list(self.config.message_acl),
|
||||
)
|
||||
|
||||
@property
|
||||
|
|
|
|||
|
|
@ -3,12 +3,13 @@ from __future__ import annotations
|
|||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
from threading import RLock
|
||||
from typing import Any
|
||||
|
||||
from .models import ServiceStatus
|
||||
from .models import MessageAclRule, ServiceStatus
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
|
|
@ -52,18 +53,24 @@ class StateStore:
|
|||
events: list[dict[str, Any]] = []
|
||||
for event_row in conn.execute(
|
||||
"""
|
||||
SELECT id, process_name, message, captured_at, payload_json
|
||||
SELECT id, process_name, message, captured_at, payload_json, acl_json
|
||||
FROM events
|
||||
ORDER BY captured_at DESC, id ASC
|
||||
"""
|
||||
):
|
||||
event_id, process_name, message, captured_at, payload_json = event_row
|
||||
event_id, process_name, message, captured_at, payload_json, acl_json = event_row
|
||||
try:
|
||||
payload = json.loads(payload_json) if payload_json else {}
|
||||
except json.JSONDecodeError:
|
||||
payload = {}
|
||||
if not isinstance(payload, dict):
|
||||
payload = {}
|
||||
try:
|
||||
acl = json.loads(acl_json) if acl_json else {}
|
||||
except json.JSONDecodeError:
|
||||
acl = {}
|
||||
if not isinstance(acl, dict):
|
||||
acl = {}
|
||||
events.append(
|
||||
{
|
||||
"id": event_id,
|
||||
|
|
@ -71,6 +78,7 @@ class StateStore:
|
|||
"message": message,
|
||||
"captured_at": captured_at,
|
||||
"payload": payload,
|
||||
"acl": acl,
|
||||
}
|
||||
)
|
||||
except sqlite3.DatabaseError:
|
||||
|
|
@ -143,10 +151,12 @@ class StateStore:
|
|||
process_name TEXT NOT NULL,
|
||||
message TEXT NOT NULL,
|
||||
captured_at TEXT NOT NULL,
|
||||
payload_json TEXT NOT NULL
|
||||
payload_json TEXT NOT NULL,
|
||||
acl_json TEXT NOT NULL DEFAULT '{}'
|
||||
)
|
||||
"""
|
||||
)
|
||||
self._ensure_events_acl_column(conn)
|
||||
|
||||
def _replace_snapshot(
|
||||
self,
|
||||
|
|
@ -170,8 +180,9 @@ class StateStore:
|
|||
process_name,
|
||||
message,
|
||||
captured_at,
|
||||
payload_json
|
||||
) VALUES (?, ?, ?, ?, ?)
|
||||
payload_json,
|
||||
acl_json
|
||||
) VALUES (?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
[
|
||||
(
|
||||
|
|
@ -180,12 +191,18 @@ class StateStore:
|
|||
str(event.get("message", "")),
|
||||
str(event.get("captured_at", "")),
|
||||
json.dumps(event.get("payload", {}), ensure_ascii=False, default=str),
|
||||
json.dumps(event.get("acl", {}), ensure_ascii=False, default=str),
|
||||
)
|
||||
for event in events
|
||||
],
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
def _ensure_events_acl_column(self, conn: sqlite3.Connection) -> None:
|
||||
columns = {row[1] for row in conn.execute("PRAGMA table_info(events)")}
|
||||
if "acl_json" not in columns:
|
||||
conn.execute("ALTER TABLE events ADD COLUMN acl_json TEXT NOT NULL DEFAULT '{}'")
|
||||
|
||||
def _status_from_legacy(self, status: dict[str, Any]) -> ServiceStatus:
|
||||
started_at_value = status.get("started_at")
|
||||
started_at: datetime | None
|
||||
|
|
@ -197,16 +214,40 @@ class StateStore:
|
|||
else:
|
||||
started_at = None
|
||||
|
||||
monitored_process_names = status.get("monitored_process_names", [])
|
||||
if not isinstance(monitored_process_names, list):
|
||||
monitored_process_names = []
|
||||
|
||||
return ServiceStatus(
|
||||
running=bool(status.get("running", False)),
|
||||
started_at=started_at,
|
||||
monitored_process_names=[str(name) for name in monitored_process_names if isinstance(name, str)],
|
||||
cached_events=int(status.get("cached_events", 0) or 0),
|
||||
event_ttl_seconds=int(status.get("event_ttl_seconds", 300) or 300),
|
||||
cleanup_interval_seconds=int(status.get("cleanup_interval_seconds", 60) or 60),
|
||||
last_error=status.get("last_error") if isinstance(status.get("last_error"), str) else None,
|
||||
message_acl=self._message_acl_from_legacy(status.get("message_acl")),
|
||||
)
|
||||
|
||||
def _message_acl_from_legacy(self, value: Any) -> list[MessageAclRule]:
|
||||
if not isinstance(value, list):
|
||||
return []
|
||||
rules: list[MessageAclRule] = []
|
||||
for item in value:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
process_name = item.get("process_name")
|
||||
message_regex = item.get("message_regex")
|
||||
cache_policy = item.get("cache")
|
||||
send_policy = item.get("send")
|
||||
mark = item.get("mark")
|
||||
if not isinstance(process_name, str) or not isinstance(message_regex, str) or not isinstance(cache_policy, str):
|
||||
continue
|
||||
try:
|
||||
rules.append(
|
||||
MessageAclRule(
|
||||
process_name=process_name,
|
||||
message_regex=message_regex,
|
||||
cache_policy=cache_policy,
|
||||
send_policy=send_policy if isinstance(send_policy, str) else None,
|
||||
mark=mark if isinstance(mark, str) else None,
|
||||
)
|
||||
)
|
||||
except (ValueError, re.error):
|
||||
continue
|
||||
return rules
|
||||
|
|
|
|||
|
|
@ -6,12 +6,17 @@ from fastapi.testclient import TestClient
|
|||
|
||||
from journal_event_collector.api import create_app
|
||||
from journal_event_collector.config import AppConfig
|
||||
from journal_event_collector.models import MessageAclRule
|
||||
from journal_event_collector.service import ApplicationCore
|
||||
from journal_event_collector.state import StateStore
|
||||
|
||||
|
||||
def test_api_exposes_events_and_status() -> None:
|
||||
config = AppConfig(monitored_process_names=["sshd"], event_ttl_seconds=60, cleanup_interval_seconds=5)
|
||||
config = AppConfig(
|
||||
message_acl=[MessageAclRule("sshd", "accepted", "cache", "urgent", "scan123")],
|
||||
event_ttl_seconds=60,
|
||||
cleanup_interval_seconds=5,
|
||||
)
|
||||
core = ApplicationCore(config)
|
||||
core.ingest(
|
||||
{
|
||||
|
|
@ -27,21 +32,23 @@ def test_api_exposes_events_and_status() -> None:
|
|||
status = client.get("/status")
|
||||
assert status.status_code == 200
|
||||
assert status.json()["cached_events"] == 1
|
||||
assert status.json()["message_acl"][0]["mark"] == "scan123"
|
||||
|
||||
events = client.get("/events")
|
||||
assert events.status_code == 200
|
||||
assert events.json()[0]["process_name"] == "sshd"
|
||||
assert events.json()[0]["acl"]["send"] == "urgent"
|
||||
|
||||
|
||||
def test_api_health_reports_ok() -> None:
|
||||
config = AppConfig(monitored_process_names=["sshd"])
|
||||
config = AppConfig(message_acl=[MessageAclRule("sshd", ".*", "drop")])
|
||||
client = TestClient(create_app(ApplicationCore(config)))
|
||||
assert client.get("/health").json() == {"status": "ok"}
|
||||
|
||||
|
||||
def test_api_state_returns_persisted_snapshot(tmp_path) -> None:
|
||||
state_path = tmp_path / "state.sqlite"
|
||||
config = AppConfig(monitored_process_names=["sshd"], state_file=state_path)
|
||||
config = AppConfig(message_acl=[MessageAclRule("sshd", ".*", "drop")], state_file=state_path)
|
||||
store = StateStore(state_path)
|
||||
store.write(
|
||||
status=ApplicationCore(config).status(),
|
||||
|
|
@ -52,6 +59,7 @@ def test_api_state_returns_persisted_snapshot(tmp_path) -> None:
|
|||
"message": "accepted",
|
||||
"captured_at": "2026-01-01T00:00:00+00:00",
|
||||
"payload": {"MESSAGE": "accepted"},
|
||||
"acl": {"process_name": "sshd", "message_regex": "accepted", "cache": "cache", "send": "urgent", "mark": "scan123"},
|
||||
}
|
||||
],
|
||||
)
|
||||
|
|
@ -64,10 +72,11 @@ def test_api_state_returns_persisted_snapshot(tmp_path) -> None:
|
|||
assert payload["updated_at"]
|
||||
assert payload["status"]["running"] is False
|
||||
assert payload["events"][0]["message"] == "accepted"
|
||||
assert payload["events"][0]["acl"]["mark"] == "scan123"
|
||||
|
||||
|
||||
def test_api_state_returns_404_when_snapshot_missing() -> None:
|
||||
config = AppConfig(monitored_process_names=["sshd"])
|
||||
config = AppConfig(message_acl=[MessageAclRule("sshd", ".*", "drop")])
|
||||
client = TestClient(create_app(ApplicationCore(config)))
|
||||
|
||||
response = client.get("/state")
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ from typer.testing import CliRunner
|
|||
from journal_event_collector import cli
|
||||
from journal_event_collector.api import create_app
|
||||
from journal_event_collector.config import AppConfig
|
||||
from journal_event_collector.models import JournalEvent
|
||||
from journal_event_collector.models import JournalEvent, MessageAclRule
|
||||
from journal_event_collector.service import ApplicationCore
|
||||
from journal_event_collector.state import StateStore
|
||||
|
||||
|
|
@ -31,8 +31,11 @@ def test_cli_run_invokes_runtime(monkeypatch, tmp_path: Path) -> None:
|
|||
config_path = tmp_path / "config.toml"
|
||||
config_path.write_text(
|
||||
"""
|
||||
message_acl = [
|
||||
'cache process sshd regexp "accepted" send urgent mark scan123',
|
||||
]
|
||||
|
||||
[application]
|
||||
monitored_process_names = ["sshd"]
|
||||
""".strip(),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
|
@ -51,7 +54,7 @@ monitored_process_names = ["sshd"]
|
|||
result = runner.invoke(cli.app, ["run", "--config", str(config_path)])
|
||||
|
||||
assert result.exit_code == 0
|
||||
assert captured["config"].monitored_process_names == ["sshd"]
|
||||
assert captured["config"].message_acl[0].mark == "scan123"
|
||||
assert captured["run"] is True
|
||||
|
||||
|
||||
|
|
@ -63,7 +66,7 @@ def test_cli_run_help_shows_default_config_path() -> None:
|
|||
|
||||
|
||||
def test_cli_status_and_events_can_query_api(monkeypatch) -> None:
|
||||
config = AppConfig(monitored_process_names=["sshd"])
|
||||
config = AppConfig(message_acl=[MessageAclRule("sshd", "accepted", "cache", "urgent", "scan123")])
|
||||
core = ApplicationCore(config)
|
||||
core.ingest(
|
||||
{
|
||||
|
|
@ -94,8 +97,13 @@ def test_cli_status_uses_api_defaults_from_config(monkeypatch, tmp_path: Path) -
|
|||
config_path = tmp_path / "config.toml"
|
||||
config_path.write_text(
|
||||
"""
|
||||
message_acl = [
|
||||
'drop process sshd regexp ".*"',
|
||||
]
|
||||
|
||||
[application]
|
||||
monitored_process_names = ["sshd"]
|
||||
event_ttl_seconds = 300
|
||||
cleanup_interval_seconds = 60
|
||||
|
||||
[api]
|
||||
host = "0.0.0.0"
|
||||
|
|
@ -124,8 +132,13 @@ def test_cli_reads_persisted_state_without_api(tmp_path: Path) -> None:
|
|||
state_path = tmp_path / "state.sqlite"
|
||||
config_path.write_text(
|
||||
f"""
|
||||
message_acl = [
|
||||
'drop process sshd regexp ".*"',
|
||||
]
|
||||
|
||||
[application]
|
||||
monitored_process_names = ["sshd"]
|
||||
event_ttl_seconds = 300
|
||||
cleanup_interval_seconds = 60
|
||||
|
||||
[storage]
|
||||
state_file = "{state_path.name}"
|
||||
|
|
@ -154,8 +167,13 @@ def test_cli_state_reads_persisted_snapshot(tmp_path: Path) -> None:
|
|||
state_path = tmp_path / "state.sqlite"
|
||||
config_path.write_text(
|
||||
f"""
|
||||
message_acl = [
|
||||
'drop process sshd regexp ".*"',
|
||||
]
|
||||
|
||||
[application]
|
||||
monitored_process_names = ["sshd"]
|
||||
event_ttl_seconds = 300
|
||||
cleanup_interval_seconds = 60
|
||||
|
||||
[storage]
|
||||
state_file = "{state_path.name}"
|
||||
|
|
|
|||
|
|
@ -11,8 +11,12 @@ def test_app_config_from_file(tmp_path: Path) -> None:
|
|||
config_path = tmp_path / "config.toml"
|
||||
config_path.write_text(
|
||||
"""
|
||||
message_acl = [
|
||||
'cache process sshd regexp "^Accepted" send urgent mark scan123',
|
||||
'drop process cron regexp ".*"',
|
||||
]
|
||||
|
||||
[application]
|
||||
monitored_process_names = ["sshd", "cron"]
|
||||
event_ttl_seconds = 120
|
||||
cleanup_interval_seconds = 15
|
||||
log_level = "debug"
|
||||
|
|
@ -29,7 +33,12 @@ command = ["journalctl", "-f", "-o", "json"]
|
|||
|
||||
config = AppConfig.from_file(config_path)
|
||||
|
||||
assert config.monitored_process_names == ["sshd", "cron"]
|
||||
assert len(config.message_acl) == 2
|
||||
assert config.message_acl[0].process_name == "sshd"
|
||||
assert config.message_acl[0].cache_policy == "cache"
|
||||
assert config.message_acl[0].send_policy == "urgent"
|
||||
assert config.message_acl[0].mark == "scan123"
|
||||
assert config.message_acl[1].cache_policy == "drop"
|
||||
assert config.event_ttl_seconds == 120
|
||||
assert config.cleanup_interval_seconds == 15
|
||||
assert config.api_host == "0.0.0.0"
|
||||
|
|
@ -37,22 +46,36 @@ command = ["journalctl", "-f", "-o", "json"]
|
|||
assert config.log_level == "debug"
|
||||
|
||||
|
||||
def test_app_config_rejects_missing_process_names() -> None:
|
||||
with pytest.raises(ConfigError):
|
||||
AppConfig.from_mapping({"application": {}})
|
||||
def test_app_config_defaults_missing_message_acl_to_drop_all() -> None:
|
||||
config = AppConfig.from_mapping({"application": {}})
|
||||
|
||||
assert len(config.message_acl) == 1
|
||||
assert config.message_acl[0].process_name == "*"
|
||||
assert config.message_acl[0].message_regex == ".*"
|
||||
assert config.message_acl[0].cache_policy == "drop"
|
||||
|
||||
|
||||
def test_app_config_deduplicates_process_names() -> None:
|
||||
config = AppConfig.from_mapping({"application": {"monitored_process_names": ["sshd", "SSHD", "cron"]}})
|
||||
assert config.monitored_process_names == ["sshd", "cron"]
|
||||
def test_app_config_rejects_legacy_whitelist() -> None:
|
||||
with pytest.raises(ConfigError, match="monitored_process_names is no longer supported"):
|
||||
AppConfig.from_mapping(
|
||||
{
|
||||
"application": {"monitored_process_names": ["sshd"]},
|
||||
"message_acl": ['cache process sshd regexp "accepted" send urgent mark scan123'],
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_app_config_resolves_state_file_relative_to_config_dir(tmp_path: Path) -> None:
|
||||
config_path = tmp_path / "config.toml"
|
||||
config_path.write_text(
|
||||
"""
|
||||
message_acl = [
|
||||
'drop process sshd regexp ".*"',
|
||||
]
|
||||
|
||||
[application]
|
||||
monitored_process_names = ["sshd"]
|
||||
event_ttl_seconds = 300
|
||||
cleanup_interval_seconds = 60
|
||||
|
||||
[storage]
|
||||
state_file = "./state/state.sqlite"
|
||||
|
|
@ -68,9 +91,52 @@ state_file = "./state/state.sqlite"
|
|||
def test_app_config_builds_cli_api_base_url() -> None:
|
||||
config = AppConfig.from_mapping(
|
||||
{
|
||||
"application": {"monitored_process_names": ["sshd"]},
|
||||
"message_acl": ['cache process sshd regexp "accepted" send urgent mark scan123'],
|
||||
"api": {"host": "0.0.0.0", "port": 9000},
|
||||
}
|
||||
)
|
||||
|
||||
assert config.api_base_url() == "http://127.0.0.1:9000"
|
||||
|
||||
|
||||
def test_app_config_parses_message_acl() -> None:
|
||||
config = AppConfig.from_mapping(
|
||||
{
|
||||
"message_acl": [
|
||||
'cache process sshd regexp "accepted" send urgent mark scan123',
|
||||
'drop process cron regexp "denied"',
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
assert config.message_acl[0].process_name == "sshd"
|
||||
assert config.message_acl[0].message_regex == "accepted"
|
||||
assert config.message_acl[1].cache_policy == "drop"
|
||||
|
||||
|
||||
def test_app_config_rejects_invalid_message_acl_regex() -> None:
|
||||
with pytest.raises(ConfigError, match=r"message_acl\[0\]\.message_regex"):
|
||||
AppConfig.from_mapping(
|
||||
{
|
||||
"message_acl": ['cache process sshd regexp "(" send urgent mark scan123']
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_app_config_rejects_invalid_mark() -> None:
|
||||
with pytest.raises(ConfigError, match=r"message_acl\[0\]\.mark"):
|
||||
AppConfig.from_mapping(
|
||||
{
|
||||
"message_acl": ['cache process sshd regexp "accepted" send urgent mark "bad mark!"']
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_app_config_accepts_drop_rule_without_send_and_mark() -> None:
|
||||
config = AppConfig.from_mapping(
|
||||
{
|
||||
"message_acl": ['drop process sshd regexp ".*"']
|
||||
}
|
||||
)
|
||||
|
||||
assert config.message_acl[0].cache_policy == "drop"
|
||||
|
|
|
|||
|
|
@ -3,24 +3,51 @@ from __future__ import annotations
|
|||
from datetime import datetime, timezone
|
||||
|
||||
from journal_event_collector.journal import build_event
|
||||
from journal_event_collector.models import MessageAclRule
|
||||
|
||||
|
||||
def test_build_event_uses_matching_process_name() -> None:
|
||||
def _rule(process_name: str, message_regex: str, cache_policy: str, send_policy: str | None = None, mark: str | None = None):
|
||||
return MessageAclRule(process_name, message_regex, cache_policy, send_policy, mark)
|
||||
|
||||
|
||||
def test_build_event_uses_matching_acl_rule() -> None:
|
||||
entry = {
|
||||
"_COMM": "sshd",
|
||||
"MESSAGE": "login accepted",
|
||||
"__REALTIME_TIMESTAMP": 1_700_000_000_000_000,
|
||||
}
|
||||
|
||||
event = build_event(entry, ["sshd", "cron"])
|
||||
event = build_event(
|
||||
entry,
|
||||
[_rule("sshd", "accepted", "cache", "urgent", "scan123")],
|
||||
)
|
||||
|
||||
assert event is not None
|
||||
assert event.process_name == "sshd"
|
||||
assert event.message == "login accepted"
|
||||
assert event.acl["cache"] == "cache"
|
||||
assert event.acl["send"] == "urgent"
|
||||
assert event.acl["mark"] == "scan123"
|
||||
assert event.captured_at.tzinfo == timezone.utc
|
||||
|
||||
|
||||
def test_build_event_ignores_non_matching_process_name() -> None:
|
||||
def test_build_event_ignores_non_matching_acl_rule() -> None:
|
||||
entry = {"_COMM": "kernel", "MESSAGE": "ignored"}
|
||||
|
||||
assert build_event(entry, ["sshd"]) is None
|
||||
assert build_event(entry, [_rule("sshd", "ignored", "cache", "urgent", "scan123")]) is None
|
||||
|
||||
|
||||
def test_build_event_drops_when_drop_rule_matches() -> None:
|
||||
entry = {"_COMM": "sshd", "MESSAGE": "login accepted"}
|
||||
|
||||
assert build_event(entry, [_rule("sshd", "accepted", "drop")]) is None
|
||||
|
||||
|
||||
def test_build_event_uses_first_matching_rule() -> None:
|
||||
entry = {"_COMM": "sshd", "MESSAGE": "login accepted"}
|
||||
rules = [
|
||||
_rule("sshd", "accepted", "drop"),
|
||||
_rule("sshd", "accepted", "cache", "urgent", "scan123"),
|
||||
]
|
||||
|
||||
assert build_event(entry, rules) is None
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ from __future__ import annotations
|
|||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from journal_event_collector.config import AppConfig
|
||||
from journal_event_collector.models import MessageAclRule
|
||||
from journal_event_collector.service import ApplicationCore
|
||||
|
||||
|
||||
|
|
@ -24,7 +25,11 @@ class FailingReader:
|
|||
|
||||
def test_application_core_collects_and_reports_status() -> None:
|
||||
base = datetime(2026, 1, 1, tzinfo=timezone.utc)
|
||||
config = AppConfig(monitored_process_names=["sshd"], event_ttl_seconds=60, cleanup_interval_seconds=1)
|
||||
config = AppConfig(
|
||||
message_acl=[MessageAclRule("sshd", "accepted", "cache", "urgent", "scan123")],
|
||||
event_ttl_seconds=60,
|
||||
cleanup_interval_seconds=1,
|
||||
)
|
||||
core = ApplicationCore(
|
||||
config,
|
||||
reader=FiniteReader([
|
||||
|
|
@ -43,10 +48,11 @@ def test_application_core_collects_and_reports_status() -> None:
|
|||
|
||||
assert core.events()[0].message == "accepted"
|
||||
assert core.status().cached_events == 1
|
||||
assert core.status().message_acl[0].mark == "scan123"
|
||||
|
||||
|
||||
def test_application_core_records_fatal_reader_error() -> None:
|
||||
config = AppConfig(monitored_process_names=["sshd"])
|
||||
config = AppConfig(message_acl=[MessageAclRule("sshd", ".*", "drop")])
|
||||
core = ApplicationCore(config, reader=FailingReader())
|
||||
|
||||
exit_code = core.run_forever()
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import json
|
|||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
from journal_event_collector.models import ServiceStatus
|
||||
from journal_event_collector.models import MessageAclRule, ServiceStatus
|
||||
from journal_event_collector.state import StateStore
|
||||
|
||||
|
||||
|
|
@ -13,18 +13,20 @@ def test_state_store_round_trip(tmp_path: Path) -> None:
|
|||
status = ServiceStatus(
|
||||
running=True,
|
||||
started_at=None,
|
||||
monitored_process_names=["sshd"],
|
||||
cached_events=1,
|
||||
event_ttl_seconds=60,
|
||||
cleanup_interval_seconds=5,
|
||||
message_acl=[MessageAclRule("sshd", "accepted", "cache", "urgent", "scan123")],
|
||||
)
|
||||
|
||||
store.write(status, [{"id": "1", "message": "hello"}])
|
||||
store.write(status, [{"id": "1", "message": "hello", "acl": {"cache": "cache", "send": "urgent", "mark": "scan123"}}])
|
||||
snapshot = store.read()
|
||||
|
||||
assert snapshot is not None
|
||||
assert snapshot.status["running"] is True
|
||||
assert snapshot.status["message_acl"][0]["mark"] == "scan123"
|
||||
assert snapshot.events[0]["message"] == "hello"
|
||||
assert snapshot.events[0]["acl"]["send"] == "urgent"
|
||||
|
||||
with sqlite3.connect(tmp_path / "state.sqlite") as conn:
|
||||
tables = {
|
||||
|
|
@ -40,11 +42,19 @@ def test_state_store_migrates_legacy_json_to_sqlite(tmp_path: Path) -> None:
|
|||
"status": {
|
||||
"running": True,
|
||||
"started_at": None,
|
||||
"monitored_process_names": ["sshd"],
|
||||
"cached_events": 1,
|
||||
"event_ttl_seconds": 60,
|
||||
"cleanup_interval_seconds": 5,
|
||||
"last_error": None,
|
||||
"message_acl": [
|
||||
{
|
||||
"process_name": "sshd",
|
||||
"message_regex": "accepted",
|
||||
"cache": "cache",
|
||||
"send": "urgent",
|
||||
"mark": "scan123",
|
||||
}
|
||||
],
|
||||
},
|
||||
"events": [
|
||||
{
|
||||
|
|
@ -53,6 +63,7 @@ def test_state_store_migrates_legacy_json_to_sqlite(tmp_path: Path) -> None:
|
|||
"message": "hello",
|
||||
"captured_at": "2026-01-01T00:00:00+00:00",
|
||||
"payload": {"MESSAGE": "hello"},
|
||||
"acl": {"process_name": "sshd", "message_regex": "accepted", "cache": "cache", "send": "urgent", "mark": "scan123"},
|
||||
}
|
||||
],
|
||||
"updated_at": "2026-01-01T00:00:00+00:00",
|
||||
|
|
@ -64,5 +75,6 @@ def test_state_store_migrates_legacy_json_to_sqlite(tmp_path: Path) -> None:
|
|||
|
||||
assert snapshot is not None
|
||||
assert snapshot.status["running"] is True
|
||||
assert snapshot.status["message_acl"][0]["mark"] == "scan123"
|
||||
assert snapshot.events[0]["message"] == "hello"
|
||||
assert state_path.read_bytes().startswith(b"SQLite format 3\x00")
|
||||
|
|
|
|||
Loading…
Reference in New Issue