chimericmesh 0.2.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. chimericmesh/__init__.py +3 -0
  2. chimericmesh/__main__.py +119 -0
  3. chimericmesh/agent/__init__.py +21 -0
  4. chimericmesh/agent/codesearch.py +131 -0
  5. chimericmesh/agent/digest.py +131 -0
  6. chimericmesh/agent/errors.py +38 -0
  7. chimericmesh/agent/feed.py +47 -0
  8. chimericmesh/agent/limits.py +98 -0
  9. chimericmesh/agent/ports.py +32 -0
  10. chimericmesh/agent/routes.py +92 -0
  11. chimericmesh/agent/service.py +116 -0
  12. chimericmesh/agent/snippet.py +135 -0
  13. chimericmesh/agent/verify.py +215 -0
  14. chimericmesh/agent/watch.py +156 -0
  15. chimericmesh/api.py +626 -0
  16. chimericmesh/approvals/__init__.py +25 -0
  17. chimericmesh/approvals/errors.py +72 -0
  18. chimericmesh/approvals/format.py +76 -0
  19. chimericmesh/approvals/irc.py +54 -0
  20. chimericmesh/approvals/ledger.py +149 -0
  21. chimericmesh/approvals/limits.py +87 -0
  22. chimericmesh/approvals/manager.py +935 -0
  23. chimericmesh/approvals/matching.py +107 -0
  24. chimericmesh/approvals/models.py +251 -0
  25. chimericmesh/approvals/ports.py +36 -0
  26. chimericmesh/approvals/routes.py +220 -0
  27. chimericmesh/approvals/rulebook.py +337 -0
  28. chimericmesh/approvals/schema.py +64 -0
  29. chimericmesh/approvals/scope.py +104 -0
  30. chimericmesh/approvals/validate.py +215 -0
  31. chimericmesh/catalog/demo_apps.json +41 -0
  32. chimericmesh/catalog/legacy_apps.json +612 -0
  33. chimericmesh/commands.py +223 -0
  34. chimericmesh/connectors/__init__.py +1 -0
  35. chimericmesh/connectors/config.py +55 -0
  36. chimericmesh/connectors/framing.py +132 -0
  37. chimericmesh/connectors/limiter.py +42 -0
  38. chimericmesh/connectors/manager.py +252 -0
  39. chimericmesh/connectors/offsets.py +157 -0
  40. chimericmesh/connectors/schema.py +31 -0
  41. chimericmesh/connectors/submit.py +26 -0
  42. chimericmesh/connectors/syslog_tcp.py +141 -0
  43. chimericmesh/connectors/tailer.py +236 -0
  44. chimericmesh/connectors/tailread.py +288 -0
  45. chimericmesh/demo/__init__.py +1 -0
  46. chimericmesh/demo/agent.py +32 -0
  47. chimericmesh/demo/apps/__init__.py +1 -0
  48. chimericmesh/demo/apps/__main__.py +83 -0
  49. chimericmesh/demo/apps/common.py +163 -0
  50. chimericmesh/demo/apps/mail_bridge.py +48 -0
  51. chimericmesh/demo/apps/orders_api.py +31 -0
  52. chimericmesh/demo/apps/spooler.py +28 -0
  53. chimericmesh/demo/config.py +38 -0
  54. chimericmesh/demo/engine.py +68 -0
  55. chimericmesh/demo/env.py +46 -0
  56. chimericmesh/demo/hub.py +172 -0
  57. chimericmesh/demo/launcher.py +165 -0
  58. chimericmesh/demo/ports.py +44 -0
  59. chimericmesh/demo/routes.py +81 -0
  60. chimericmesh/demo/samples.py +32 -0
  61. chimericmesh/demo/scenario.py +95 -0
  62. chimericmesh/demo/supervisor.py +267 -0
  63. chimericmesh/demo/watch.py +46 -0
  64. chimericmesh/diagnostics.py +253 -0
  65. chimericmesh/discovery/__init__.py +17 -0
  66. chimericmesh/discovery/accept.py +131 -0
  67. chimericmesh/discovery/catalog.py +313 -0
  68. chimericmesh/discovery/collect.py +131 -0
  69. chimericmesh/discovery/dismissals.py +46 -0
  70. chimericmesh/discovery/engine.py +41 -0
  71. chimericmesh/discovery/errors.py +34 -0
  72. chimericmesh/discovery/expand.py +151 -0
  73. chimericmesh/discovery/manager.py +220 -0
  74. chimericmesh/discovery/match.py +177 -0
  75. chimericmesh/discovery/models.py +174 -0
  76. chimericmesh/discovery/parse.py +166 -0
  77. chimericmesh/discovery/probe.py +69 -0
  78. chimericmesh/discovery/routes.py +129 -0
  79. chimericmesh/discovery/runner.py +147 -0
  80. chimericmesh/discovery/schema.py +25 -0
  81. chimericmesh/discovery/text.py +53 -0
  82. chimericmesh/events.py +74 -0
  83. chimericmesh/fsperms.py +72 -0
  84. chimericmesh/hub.py +757 -0
  85. chimericmesh/listeners.py +162 -0
  86. chimericmesh/mcp_server.py +199 -0
  87. chimericmesh/mute/__init__.py +10 -0
  88. chimericmesh/mute/models.py +14 -0
  89. chimericmesh/mute/mutelist.py +51 -0
  90. chimericmesh/mute/routes.py +49 -0
  91. chimericmesh/mute/schema.py +29 -0
  92. chimericmesh/mute/store.py +94 -0
  93. chimericmesh/notify.py +47 -0
  94. chimericmesh/parsers/__init__.py +12 -0
  95. chimericmesh/parsers/formats.py +23 -0
  96. chimericmesh/parsers/irc.py +91 -0
  97. chimericmesh/parsers/logctx.py +143 -0
  98. chimericmesh/parsers/ncsa.py +57 -0
  99. chimericmesh/parsers/plain.py +17 -0
  100. chimericmesh/parsers/syslog.py +82 -0
  101. chimericmesh/parsers/syslogtext.py +62 -0
  102. chimericmesh/parsers/telnet.py +56 -0
  103. chimericmesh/parsers/w3c.py +58 -0
  104. chimericmesh/parsers/xferlog.py +31 -0
  105. chimericmesh/replay.py +108 -0
  106. chimericmesh/replay_irc.py +202 -0
  107. chimericmesh/services/__init__.py +39 -0
  108. chimericmesh/services/access.py +224 -0
  109. chimericmesh/services/asgi.py +107 -0
  110. chimericmesh/services/deps.py +42 -0
  111. chimericmesh/services/errors.py +49 -0
  112. chimericmesh/services/limiter.py +130 -0
  113. chimericmesh/services/models.py +160 -0
  114. chimericmesh/services/paths.py +139 -0
  115. chimericmesh/services/registry.py +638 -0
  116. chimericmesh/services/routes.py +161 -0
  117. chimericmesh/services/schema.py +48 -0
  118. chimericmesh/services/status.py +239 -0
  119. chimericmesh/services/tagging.py +63 -0
  120. chimericmesh/services/token.py +129 -0
  121. chimericmesh/services/validate.py +184 -0
  122. chimericmesh/store/__init__.py +43 -0
  123. chimericmesh/store/audit.py +89 -0
  124. chimericmesh/store/config.py +88 -0
  125. chimericmesh/store/connection.py +98 -0
  126. chimericmesh/store/errors.py +65 -0
  127. chimericmesh/store/events.py +430 -0
  128. chimericmesh/store/incidents.py +292 -0
  129. chimericmesh/store/migrations.py +109 -0
  130. chimericmesh/store/models.py +49 -0
  131. chimericmesh/store/ports.py +61 -0
  132. chimericmesh/store/proposals.py +215 -0
  133. chimericmesh/store/schema.py +102 -0
  134. chimericmesh/store/store.py +173 -0
  135. chimericmesh/store/tx.py +143 -0
  136. chimericmesh/store/writer.py +315 -0
  137. chimericmesh/web/__init__.py +1 -0
  138. chimericmesh/web/feed.py +212 -0
  139. chimericmesh/web/index.html +3775 -0
  140. chimericmesh/web/sse.py +74 -0
  141. chimericmesh/web/stream.py +64 -0
  142. chimericmesh-0.2.2.dist-info/METADATA +537 -0
  143. chimericmesh-0.2.2.dist-info/RECORD +147 -0
  144. chimericmesh-0.2.2.dist-info/WHEEL +5 -0
  145. chimericmesh-0.2.2.dist-info/entry_points.txt +2 -0
  146. chimericmesh-0.2.2.dist-info/licenses/LICENSE +21 -0
  147. chimericmesh-0.2.2.dist-info/top_level.txt +1 -0
chimericmesh/api.py ADDED
@@ -0,0 +1,626 @@
1
+ """FastAPI application: REST API for agents/MCP plus the dashboard."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ import os
8
+ import random
9
+ import sys
10
+ import time
11
+ from contextlib import asynccontextmanager
12
+ from pathlib import Path
13
+ from typing import Any, Literal
14
+
15
+ from urllib.parse import urlsplit
16
+
17
+ from fastapi import Depends, FastAPI, HTTPException, Query, Request
18
+ from fastapi.responses import FileResponse, JSONResponse
19
+ from pydantic import BaseModel, Field, field_validator
20
+
21
+ from . import __version__
22
+ from .agent.ports import AgentPorts
23
+ from .agent.routes import build_router as build_agent_router
24
+ from .agent.service import AgentService
25
+ from .agent.snippet import find_workspace_root
26
+ from .approvals.errors import ApprovalsNotMigrated
27
+ from .approvals.manager import ApprovalManager
28
+ from .approvals.models import ApprovalSettings
29
+ from .approvals.routes import build_router as build_approvals_router
30
+ from .approvals.routes import register_error_handlers as register_approvals_errors
31
+ from .approvals.schema import register_migrations as register_approvals_migrations
32
+ from .commands import handle_command, parse_command
33
+ from .connectors.config import resolve_tcp_port
34
+ from .connectors.manager import ConnectorManager
35
+ from .connectors.schema import connectors_registry
36
+ from .connectors.submit import make_submit
37
+ from .connectors.syslog_tcp import start_syslog_tcp
38
+ from .diagnostics import find_code_hints
39
+ from .discovery.accept import Acceptor, RegistrySink
40
+ from .discovery.catalog import load_catalog
41
+ from .discovery.engine import run_scan_sync
42
+ from .discovery.manager import DiscoveryService, ScanManager
43
+ from .discovery.probe import LinuxProcFs, OsFsProbe
44
+ from .discovery.routes import build_router as build_discovery_router
45
+ from .discovery.runner import SubprocessRunner
46
+ from .discovery.schema import register_migrations as register_discovery_migrations
47
+ from .discovery.text import os_name_from_platform
48
+ from .demo.agent import run_demo_agent
49
+ from .demo.config import DemoConfig, validate_return_url
50
+ from .demo.engine import make_demo_engine
51
+ from .demo.env import build_env
52
+ from .demo.launcher import PopenSpawner
53
+ from .demo.routes import build_demo_router, build_real_router
54
+ from .demo.samples import SampleSupervisor
55
+ from .demo.supervisor import DemoSupervisor
56
+ from .events import Event
57
+ from .hub import WEB_NICK, Hub
58
+ from .listeners import IrcServer, start_syslog, start_telnet
59
+ from .mute.models import MutesNotMigrated
60
+ from .mute.routes import build_router as build_mute_router
61
+ from .mute.schema import register_migrations as register_mute_migrations
62
+ from .mute.store import MuteStore
63
+ from .parsers import irc_to_event, parse_syslog, telnet_to_event
64
+ from .parsers.formats import FORMAT_NAMES
65
+ from .services.access import AccessControl, OperatorVerdict, is_loopback, parse_allowed_hosts
66
+ from .services.asgi import MAX_BODY_BYTES, BodyLimit, HostGuard
67
+ from .services.deps import make_require_admin
68
+ from .services.limiter import ReduceAuditLimiter
69
+ from .services.limiter import reduce_key as make_reduce_key
70
+ from .services.registry import ServiceRegistry
71
+ from .services.routes import build_router
72
+ from .services.token import TokenStore, resolve_token_path
73
+ from .services.validate import KNOWN_PROTOCOLS
74
+ from .store import MigrationRegistry, Store, StoreError
75
+ from .store.config import MEMORY, resolve_db_path, resolve_home
76
+ from .store.proposals import is_reserved_decider
77
+ from .web.feed import StreamGate
78
+ from .web.stream import build_stream_router
79
+
80
+ log = logging.getLogger("chimericmesh.api")
81
+
82
+ WEB_DIR = Path(__file__).parent / "web"
83
+
84
+
85
+ class IngestRequest(BaseModel):
86
+ source: Literal["syslog", "irc", "telnet"]
87
+ line: str = Field(min_length=1, max_length=8192)
88
+ host: str = Field(default="api-client", max_length=128)
89
+
90
+
91
+ class SayRequest(BaseModel):
92
+ channel: str = Field(default="#ops", pattern=r"^#[\w\-]{1,48}$")
93
+ text: str = Field(min_length=1, max_length=2000)
94
+
95
+
96
+ class ResolveRequest(BaseModel):
97
+ note: str = Field(default="", max_length=300)
98
+
99
+
100
+ class ProposalRequest(BaseModel):
101
+ # Unknown keys (status, decided_by, approved_by_rule ...) are ignored and never read (L4).
102
+ incident_id: str = Field(min_length=1, max_length=64)
103
+ action: str = Field(min_length=1, max_length=200)
104
+ details: str = Field(default="", max_length=500)
105
+ # Optional structure; ``approvals.validate`` checks the values and names the bad field in a 422.
106
+ files: Any = None
107
+ estimated_lines: Any = None
108
+ verification: Any = None
109
+ kind: Any = None
110
+
111
+
112
+ class DecideRequest(BaseModel):
113
+ approve: bool
114
+ by: str = Field(default="api", min_length=1, max_length=30)
115
+
116
+
117
+ class CompleteRequest(BaseModel):
118
+ note: str = Field(default="", max_length=300)
119
+ files_changed: Any = None
120
+ lines_changed: Any = None
121
+ verification_result: Any = None
122
+
123
+
124
+ class TerminalRequest(BaseModel):
125
+ text: str = Field(min_length=1, max_length=200)
126
+
127
+ @field_validator("text")
128
+ @classmethod
129
+ def _strip_nonempty(cls, v: str) -> str:
130
+ v = v.strip()
131
+ if not v:
132
+ raise ValueError("text must not be blank")
133
+ return v
134
+
135
+
136
+ MUTATING = {"POST", "PUT", "PATCH", "DELETE"}
137
+
138
+
139
+ SHUTDOWN_SECONDS = 5.0
140
+ LIMITER_FLUSH_SECONDS = 0.5
141
+
142
+
143
+ def build_registry() -> MigrationRegistry:
144
+ """Every module's migrations. Later modules add their ``register_migrations`` call here."""
145
+ registry = connectors_registry() # core, services and connectors migrations
146
+ register_discovery_migrations(registry)
147
+ register_approvals_migrations(registry)
148
+ register_mute_migrations(registry)
149
+ return registry
150
+
151
+
152
+ def _build_access(enforce: bool, hub: Hub, store: Store) -> AccessControl:
153
+ """The access object. Enforcing: token file under the home directory (memory only for ``:memory:``)."""
154
+ if not enforce:
155
+ return AccessControl.disabled()
156
+ tokens = TokenStore.open(resolve_token_path(os.environ, Path(resolve_home())),
157
+ in_memory=store.path == MEMORY, redact=store.add_redaction)
158
+ return AccessControl(enforce=True, tokens=tokens,
159
+ allowed_hosts=parse_allowed_hosts(os.environ.get("CHIMERICMESH_ALLOWED_HOSTS")),
160
+ audit=store.audit, now=hub.now)
161
+
162
+
163
+ def _protected_dirs(store: Store) -> tuple[str, ...]:
164
+ """Folders a service's code folder may never contain or lie inside (R2.2)."""
165
+ home = resolve_home()
166
+ token_dir = str(resolve_token_path(os.environ, Path(home)).parent)
167
+ db_dir = home if store.path == MEMORY else str(Path(store.path).parent)
168
+ return tuple(dict.fromkeys((home, db_dir, token_dir)))
169
+
170
+
171
+ def _detach_approvals(hub: Hub, approvals: ApprovalManager | None) -> None:
172
+ """Shutdown: a hub the caller keeps drops the closed manager (fails closed, and breaks the hub-manager cycle)."""
173
+ if approvals is not None and hub.approver is approvals:
174
+ hub.approver = None
175
+ if approvals is not None and hub.approvals is approvals:
176
+ hub.approvals = None
177
+
178
+
179
+ def _wire_store(hub: Hub | None, store: Store | None) -> tuple[Hub, Store, bool]:
180
+ """Apply the create_app contract. Returns (hub, store, whether the lifespan closes the store)."""
181
+ if hub is None:
182
+ if store is not None:
183
+ return Hub(store=store), store, False
184
+ opened = Store.open(resolve_db_path(), registry=build_registry())
185
+ return Hub(store=opened), opened, True
186
+ if hub.store is not None:
187
+ if store is not None and store is not hub.store:
188
+ raise ValueError("create_app: the hub is backed by a different store")
189
+ return hub, hub.store, False
190
+ owned = store is None
191
+ store = store or Store.open(MEMORY, registry=build_registry()) # tables, counters, audit of new modules
192
+ if hub.audit is None:
193
+ hub.audit = store.audit # an audit sink already attached is never overwritten
194
+ return hub, store, owned
195
+
196
+
197
+ def _wire_mutes(hub: Hub, registry: ServiceRegistry, store: Store) -> MuteStore | None:
198
+ """Load the mute set and connect the gate, the stats skip and the status fields to it."""
199
+ try:
200
+ mutes = MuteStore.load(store)
201
+ except MutesNotMigrated:
202
+ log.warning("the store has no mute migration: muting is off") # fails open: events are kept
203
+ return None
204
+ mutes.attach(registry)
205
+ hub.gate = mutes.gate
206
+ registry.set_mute_check(mutes.mutes.is_muted)
207
+ registry.set_mute_view(mutes.mutes.view)
208
+ return mutes
209
+
210
+
211
+ def _is_admin() -> bool:
212
+ """Whether the hub runs with administrator rights. Only used to explain a ``limited`` scan; never elevates."""
213
+ try:
214
+ if os.name == "nt":
215
+ import ctypes
216
+ return bool(ctypes.windll.shell32.IsUserAnAdmin()) # type: ignore[attr-defined]
217
+ return os.geteuid() == 0
218
+ except Exception: # noqa: BLE001
219
+ return False
220
+
221
+
222
+ def _build_discovery(registry: ServiceRegistry, store: Store, hub: Hub,
223
+ samples: SampleSupervisor | None = None) -> DiscoveryService:
224
+ """Build discovery. Nothing here starts a scan, a task or a thread (R1.1).
225
+ The demo hub passes its sample supervisor: it loads the demo catalog and scans the sample apps, not this machine."""
226
+ known_formats = frozenset(FORMAT_NAMES)
227
+ load = load_catalog(known_formats) if samples is None else load_catalog(known_formats, resource="demo_apps.json")
228
+ os_name = os_name_from_platform(sys.platform)
229
+ system_root = {k: v for k, v in os.environ.items() if k.upper() == "SYSTEMROOT"}
230
+ manager = ScanManager(
231
+ load=load, engine=run_scan_sync if samples is None else make_demo_engine(samples.procs),
232
+ runner=SubprocessRunner(os_name or "linux", system_root),
233
+ procfs=LinuxProcFs(), fs=OsFsProbe(), store=store, registry=registry, known_formats=known_formats,
234
+ now=hub.now, os_name=os_name, is_admin=_is_admin(), own_pid=os.getpid(), env=dict(os.environ))
235
+ acceptor = Acceptor(manager, RegistrySink(registry), registry, store, known_formats)
236
+ return DiscoveryService(manager, acceptor, load)
237
+
238
+
239
+ def create_app(hub: Hub | None = None, start_listeners: bool = True, *,
240
+ store: Store | None = None, enforce_access: bool | None = None,
241
+ demo: DemoConfig | None = None) -> FastAPI:
242
+ # R7.5: an explicit value wins; None means off for an injected hub and on for a hub this call builds.
243
+ effective = enforce_access if enforce_access is not None else hub is None
244
+ hub_arg, store_arg = hub, store
245
+ if hub is not None and enforce_access is None and hub.enforce_access:
246
+ log.warning("create_app: the hub was built with enforce_access=True but create_app got "
247
+ "enforce_access=None, which means False for an injected hub; pass "
248
+ "enforce_access=True to keep enforcement on")
249
+ hub, store, owns_store = _wire_store(hub, store)
250
+ hub.enforce_access = effective
251
+ if demo is not None:
252
+ hub.webhook_url = None # the demo never calls out, whatever the environment says (R4.2)
253
+ bind = os.environ.get("CHIMERICMESH_BIND", "127.0.0.1")
254
+ if not is_loopback(bind):
255
+ log.warning("CHIMERICMESH_BIND=%s is not a loopback address: the dashboard and the REST API "
256
+ "are reachable from other machines", bind)
257
+ registry = ServiceRegistry.load(store, state=hub, protected=_protected_dirs(store), clock=hub.now)
258
+ hub.tagger = registry.tag
259
+ mutes = _wire_mutes(hub, registry, store)
260
+ access = _build_access(effective, hub, store)
261
+ hub.access = access if effective else None
262
+ reduce_limiter = ReduceAuditLimiter(store.audit, now=hub.now)
263
+ require_admin = make_require_admin(access)
264
+ irc = IrcServer(hub)
265
+ submit = make_submit(hub.ingest)
266
+ manager = ConnectorManager(registry, store, submit)
267
+ samples: SampleSupervisor | None = None
268
+ demo_supervisor: DemoSupervisor | None = None
269
+ if demo is not None:
270
+ samples = SampleSupervisor(demo.spawner or PopenSpawner(), demo.ports, build_env(os.environ, demo.home, demo.ports),
271
+ demo.home)
272
+ else:
273
+ demo_supervisor = DemoSupervisor(PopenSpawner())
274
+ discovery = _build_discovery(registry, store, hub, samples)
275
+ demo_tasks: list[asyncio.Task] = []
276
+
277
+ async def announce(text: str) -> None:
278
+ await hub.say(hub.irc_channel, text)
279
+
280
+ approvals: ApprovalManager | None
281
+ try:
282
+ approvals = ApprovalManager.load(
283
+ store, state=hub, writer=hub, registry=registry, limiter=reduce_limiter, announce=announce,
284
+ protected=_protected_dirs(store), settings=ApprovalSettings.from_env(os.environ), now=hub.now)
285
+ except ApprovalsNotMigrated:
286
+ # Fail closed: without the tables there are no rules, so nothing is ever auto-approved (blockers B4).
287
+ log.warning("the store has no approvals migrations: standing approval rules are off")
288
+ approvals = None
289
+ hub.approver = approvals
290
+ hub.approvals = approvals
291
+ if approvals is not None and hub_arg is None and store_arg is None:
292
+ hub.enforce_limits = True # B3: the production path (create_app() and python -m chimericmesh)
293
+
294
+ agent = AgentService(AgentPorts(
295
+ state=hub, registry=registry, approvals=approvals, protected_dirs=_protected_dirs(store),
296
+ workspace_root=find_workspace_root(os.environ, os.getcwd())))
297
+
298
+ @asynccontextmanager
299
+ async def lifespan(app: FastAPI):
300
+ closers = []
301
+ syslog_tcp = None
302
+ try:
303
+ if start_listeners:
304
+ ports = {
305
+ "syslog": int(os.environ.get("CHIMERICMESH_SYSLOG_PORT", 5514)),
306
+ "irc": int(os.environ.get("CHIMERICMESH_IRC_PORT", 6667)),
307
+ "telnet": int(os.environ.get("CHIMERICMESH_TELNET_PORT", 2323)),
308
+ }
309
+ syslog_t = await start_syslog(hub, bind, ports["syslog"])
310
+ closers.append(syslog_t.close)
311
+ telnet_s = await start_telnet(hub, bind, ports["telnet"])
312
+ closers.append(telnet_s.close)
313
+ irc_s = await irc.start(bind, ports["irc"])
314
+ closers.append(irc_s.close)
315
+ # A busy TCP port is a warning, never a failed start (B15).
316
+ syslog_tcp = await start_syslog_tcp(submit, bind, resolve_tcp_port(os.environ))
317
+ app.state.syslog_tcp = syslog_tcp
318
+ hub.start()
319
+ if approvals is not None:
320
+ await approvals.start()
321
+ # Tailers are not sockets: they start whether or not the listeners do.
322
+ await manager.start()
323
+ if samples is not None:
324
+ await asyncio.to_thread(samples.start)
325
+ demo_tasks.append(asyncio.create_task(run_demo_agent(hub, poll=demo.agent_poll), name="demo-agent"))
326
+ app.state.demo_agent = demo_tasks[0]
327
+ except BaseException:
328
+ for task in demo_tasks:
329
+ task.cancel()
330
+ if samples is not None:
331
+ await asyncio.to_thread(samples.stop)
332
+ agent.aclose()
333
+ for close in closers:
334
+ close()
335
+ await discovery.manager.aclose(0.2)
336
+ if approvals is not None:
337
+ await approvals.aclose(0.2)
338
+ _detach_approvals(hub, approvals)
339
+ if syslog_tcp is not None:
340
+ await syslog_tcp.aclose(0.4)
341
+ await manager.aclose(0.6)
342
+ app.state.syslog_tcp = None
343
+ if owns_store:
344
+ store.close(timeout=SHUTDOWN_SECONDS, clean=False) # a start that never served stays unclean
345
+ raise
346
+ yield
347
+ # Shutdown order: the listeners stop calling ingest, the TCP server and the manager stop (one second
348
+ # between them), then the limiter flushes its audit rows, then the hub flushes, then the store closes,
349
+ # all against one deadline taken when shutdown begins. The hub keeps at least 3 seconds.
350
+ deadline = time.monotonic() + SHUTDOWN_SECONDS
351
+
352
+ def remaining() -> float:
353
+ return max(0.05, deadline - time.monotonic())
354
+
355
+ agent.aclose() # held wait_for_work calls end with imeout first (R4.6)
356
+ for close in closers:
357
+ close()
358
+ await discovery.manager.aclose(min(0.2, remaining())) # a running scan stops before the connector steps
359
+ for task in demo_tasks:
360
+ task.cancel()
361
+ if samples is not None:
362
+ await asyncio.to_thread(samples.stop) # the demo's sample apps end before the connector manager
363
+ shown = getattr(app.state, "demo_supervisor", None)
364
+ if shown is not None:
365
+ try:
366
+ await asyncio.wait_for(shown.aclose(), min(3.5, remaining()))
367
+ except Exception: # includes the timeout: the child still ends, its standard input is closed first
368
+ log.error("the demo did not stop cleanly at shutdown")
369
+ if approvals is not None:
370
+ await approvals.aclose(min(1.0, remaining())) # the sweep, then in-flight units
371
+ if syslog_tcp is not None:
372
+ await syslog_tcp.aclose(min(0.4, remaining()))
373
+ app.state.syslog_tcp = None
374
+ await manager.aclose(min(0.6, remaining()))
375
+ try:
376
+ await asyncio.wait_for(reduce_limiter.aclose(), min(LIMITER_FLUSH_SECONDS, remaining()))
377
+ except Exception: # includes the timeout: the hub flush matters more than a coalesced audit row
378
+ log.error("the reduce-operations limiter did not flush before its slice ended")
379
+ await hub.aclose(max(0.1, remaining()))
380
+ _detach_approvals(hub, approvals)
381
+ if owns_store:
382
+ store.close(timeout=max(0.1, remaining()))
383
+ app = FastAPI(title="ChimericMesh", version="0.1.0", lifespan=lifespan)
384
+ app.state.hub = hub
385
+ app.state.store = store
386
+ app.state.services = registry
387
+ app.state.mutes = mutes
388
+ app.state.access = access
389
+ app.state.reduce_limiter = reduce_limiter
390
+ app.state.connectors = manager
391
+ app.state.discovery = discovery
392
+ app.state.approvals = approvals
393
+ app.state.agent = agent
394
+ app.state.syslog_tcp = None
395
+ app.state.demo = demo
396
+ app.state.demo_supervisor = demo_supervisor
397
+ app.state.samples = samples
398
+ app.state.demo_agent = None
399
+
400
+ @app.exception_handler(StoreError)
401
+ async def store_unavailable(request: Request, exc: StoreError):
402
+ log.error("store error in %s %s: %s", request.method, request.url.path, type(exc).__name__)
403
+ return JSONResponse({"detail": "store unavailable"}, status_code=503)
404
+
405
+ @app.middleware("http")
406
+ async def same_origin_only(request: Request, call_next):
407
+ # Browser CSRF defence for a localhost service: a page on another site can fire
408
+ # POSTs at 127.0.0.1, but the browser labels them with its own Origin. Reject
409
+ # state-changing requests whose Origin differs from Host. Non-browser clients
410
+ # (curl, httpx, MCP server) send no Origin and pass.
411
+ origin = request.headers.get("origin")
412
+ if origin is not None and request.method in MUTATING:
413
+ if urlsplit(origin).netloc != request.headers.get("host", ""):
414
+ return JSONResponse({"detail": "cross-origin request blocked"}, status_code=403)
415
+ return await call_next(request)
416
+
417
+ # Added after the same-origin middleware; the last one added runs first: HostGuard, then BodyLimit.
418
+ app.add_middleware(BodyLimit, max_bytes=MAX_BODY_BYTES)
419
+ app.add_middleware(HostGuard, access=access)
420
+ app.include_router(build_router(registry, access, require_admin))
421
+ app.include_router(build_discovery_router(discovery, require_admin))
422
+ if mutes is not None:
423
+ app.include_router(build_mute_router(mutes, require_admin))
424
+ if approvals is not None:
425
+ app.include_router(build_approvals_router(approvals, access, require_admin))
426
+ register_approvals_errors(app)
427
+ app.include_router(build_agent_router(agent))
428
+ app.include_router(build_demo_router(demo) if demo is not None else build_real_router())
429
+ stream_gate = StreamGate(lease_grace=10.0) # the live-log slots (dashboard R5.3); lease_grace is set here only
430
+ app.state.stream_gate = stream_gate
431
+ app.include_router(build_stream_router(
432
+ hub, service_exists=lambda sid: sid == "unassigned" or registry.get(sid) is not None,
433
+ gate=stream_gate, clock=time.monotonic))
434
+
435
+ @app.get("/", include_in_schema=False)
436
+ async def index():
437
+ return FileResponse(WEB_DIR / "index.html",
438
+ headers={"X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer"})
439
+
440
+ @app.get("/api/ui-config")
441
+ async def ui_config():
442
+ # What the page needs to lock its controls and fill its forms. Read-only; never the token itself.
443
+ enforcing = bool(access.enforce)
444
+ token_path = access.token_path if enforcing else None
445
+ body = {"enforce_access": enforcing, "token_file": None if token_path is None else str(token_path),
446
+ "formats": list(FORMAT_NAMES), "protocols": list(KNOWN_PROTOCOLS), "version": __version__}
447
+ if demo is not None:
448
+ body.update(demo=True, return_url=validate_return_url(demo.return_url))
449
+ return body
450
+
451
+ @app.get("/api/stats")
452
+ async def stats():
453
+ return hub.stats()
454
+
455
+ @app.get("/api/events")
456
+ async def events(limit: int = 50, source: str | None = None, after_id: int | None = Query(None, ge=0),
457
+ service_id: str | None = Query(None, max_length=64)):
458
+ limit = max(1, min(limit, 500))
459
+ if after_id is not None: # a cursor read: oldest first
460
+ found = await hub.events_after(after_id, limit, source=source, service_id=service_id)
461
+ return [e.to_dict() for e in found]
462
+ return [e.to_dict() for e in hub.recent(limit, source, service_id)]
463
+
464
+ @app.post("/api/ingest", status_code=202)
465
+ async def ingest(req: IngestRequest):
466
+ event: Event | None
467
+ if req.source == "syslog":
468
+ event = parse_syslog(req.line, default_host=req.host)
469
+ elif req.source == "irc":
470
+ raw = req.line if req.line.startswith(":") else f":{req.host}!u@h {req.line}"
471
+ event = irc_to_event(raw)
472
+ else:
473
+ event = telnet_to_event(req.line.encode(), host=req.host)
474
+ if event is None:
475
+ raise HTTPException(422, "line produced no event")
476
+ tagged = await hub.ingest(event)
477
+ if tagged.id == 0: # dropped by Mute: not stored, not counted (an ingested event always has an id)
478
+ return {**tagged.to_dict(), "muted": True}
479
+ return tagged.to_dict()
480
+
481
+ @app.get("/api/incidents")
482
+ async def incidents(status: Literal["open", "resolved"] | None = None,
483
+ service_id: str | None = Query(None, max_length=64),
484
+ limit: int | None = Query(None, ge=1, le=500)):
485
+ return [i.to_dict() for i in hub.incidents(status=status, service_id=service_id, limit=limit)]
486
+
487
+ @app.get("/api/incidents/{incident_id}")
488
+ async def incident(incident_id: str):
489
+ inc = hub.get_incident(incident_id)
490
+ if inc is None:
491
+ raise HTTPException(404, "incident not found")
492
+ return inc.to_dict()
493
+
494
+ @app.get("/api/incidents/{incident_id}/code")
495
+ async def incident_code(incident_id: str):
496
+ inc = hub.get_incident(incident_id)
497
+ if inc is None:
498
+ raise HTTPException(404, "incident not found")
499
+ folder = agent.code_folder_for_incident(inc) # B6: the incident's own service first
500
+ if folder:
501
+ return find_code_hints(inc, Path(folder))
502
+ return hub.code_hints(inc)
503
+
504
+ @app.post("/api/incidents/{incident_id}/resolve")
505
+ async def resolve(incident_id: str, req: ResolveRequest):
506
+ inc = await hub.resolve(incident_id, req.note)
507
+ if inc is None:
508
+ raise HTTPException(404, "incident not found")
509
+ return inc.to_dict()
510
+
511
+ # Proposals only record a human decision; nothing here executes the proposed action.
512
+ def _proposal_or_404(pid: str):
513
+ prop = hub.get_proposal(pid)
514
+ if prop is None:
515
+ raise HTTPException(404, "proposal not found")
516
+ return prop
517
+
518
+ def _view(prop):
519
+ return prop.to_dict() if approvals is None else approvals.proposal_view(prop)
520
+
521
+ @app.get("/api/proposals")
522
+ async def proposals(status: Literal["pending", "approved", "denied", "done"] | None = None,
523
+ service_id: str | None = Query(None, max_length=64),
524
+ limit: int = Query(200, ge=1, le=500)):
525
+ if approvals is not None:
526
+ await approvals.expire_due()
527
+ return [_view(p) for p in hub.list_proposals(status, service_id=service_id, limit=limit)]
528
+
529
+ @app.get("/api/proposals/{pid}")
530
+ async def proposal(pid: str):
531
+ if approvals is not None:
532
+ await approvals.expire_due()
533
+ return _view(_proposal_or_404(pid))
534
+
535
+ @app.post("/api/proposals", status_code=201)
536
+ async def create_proposal(req: ProposalRequest):
537
+ extra = {k: v for k, v in (("kind", req.kind), ("files", req.files), ("estimated_lines", req.estimated_lines),
538
+ ("verification", req.verification)) if v is not None}
539
+ prop = await hub.create_proposal(req.incident_id, req.action, req.details, extra=extra or None)
540
+ if prop is None:
541
+ raise HTTPException(404, "incident not found")
542
+ return _view(prop)
543
+
544
+ @app.post("/api/proposals/{pid}/decide", dependencies=[Depends(require_admin)])
545
+ async def decide_proposal(pid: str, req: DecideRequest):
546
+ _proposal_or_404(pid)
547
+ if is_reserved_decider(req.by): # R4.8: these prefixes belong to the hub's own rule logic
548
+ return JSONResponse({"detail": "that decider name is reserved", "field": "by"}, status_code=422)
549
+ prop = await hub.decide(pid, req.approve, req.by)
550
+ if prop is None:
551
+ raise HTTPException(409, "proposal is not pending")
552
+ return _view(prop)
553
+
554
+ @app.post("/api/proposals/{pid}/complete")
555
+ async def complete_proposal(pid: str, req: CompleteRequest):
556
+ _proposal_or_404(pid)
557
+ extra = {k: v for k, v in (("files_changed", req.files_changed), ("lines_changed", req.lines_changed),
558
+ ("verification_result", req.verification_result)) if v is not None}
559
+ prop = await hub.complete(pid, req.note, extra=extra or None)
560
+ if prop is None:
561
+ raise HTTPException(409, "proposal is not approved")
562
+ return _view(prop)
563
+
564
+ @app.post("/api/irc/say", status_code=202)
565
+ async def say(req: SayRequest):
566
+ await hub.say(req.channel, req.text)
567
+ return {"ok": True}
568
+
569
+ @app.post("/api/demo/storm", status_code=202)
570
+ async def storm():
571
+ """Inject a realistic multi-protocol failure burst for demos."""
572
+ now = time.time()
573
+ lines = [
574
+ ("syslog", "<27>Nov 13 11:10:08 db01 postgres[4121]: FATAL: could not write block 8812: No space left on device", "db01"),
575
+ ("syslog", "<27>Nov 13 11:10:09 db01 postgres[4121]: FATAL: could not write block 8813: No space left on device", "db01"),
576
+ ("syslog", "<27>Nov 13 11:10:11 db01 postgres[4121]: FATAL: could not write block 8814: No space left on device", "db01"),
577
+ ("irc", "#ops :web02: upstream timed out connecting to 10.0.4.17:5432", "web02"),
578
+ ("irc", "#ops :web02: upstream timed out connecting to 10.0.4.17:5432", "web02"),
579
+ ("irc", "#ops :web02: upstream timed out connecting to 10.0.4.17:5432", "web02"),
580
+ ("telnet", "ALERT sw-core-1: Failed password for admin from 203.0.113.9 port 4%d" % random.randint(10, 99), "sw-core-1"),
581
+ ("telnet", "ALERT sw-core-1: Failed password for admin from 203.0.113.9 port 4%d" % random.randint(10, 99), "sw-core-1"),
582
+ ("telnet", "ALERT sw-core-1: Failed password for admin from 203.0.113.9 port 4%d" % random.randint(10, 99), "sw-core-1"),
583
+ ]
584
+ for source, line, host in lines:
585
+ if source == "syslog":
586
+ ev = parse_syslog(line, default_host=host)
587
+ elif source == "irc":
588
+ ev = irc_to_event(f":{host}!u@h PRIVMSG {line}")
589
+ else:
590
+ ev = telnet_to_event(line.encode(), host=host)
591
+ if ev:
592
+ await hub.ingest(ev)
593
+ return {"injected": len(lines), "at": now}
594
+
595
+ @app.get("/api/chat")
596
+ async def chat(after: int = 0, limit: int = 100):
597
+ return hub.chat(after, limit)
598
+
599
+ @app.post("/api/terminal")
600
+ async def terminal(req: TerminalRequest, request: Request):
601
+ # Identity is fixed server-side; the client can never choose a nick.
602
+ text = req.text
603
+ cmd = parse_command(text)
604
+ verdict: OperatorVerdict | None = None
605
+ if cmd is not None and cmd.name in {"approve", "deny"}:
606
+ # Token first, transcript second: a refused request leaves no forged "dashboard> !approve" line.
607
+ await require_admin(request)
608
+ verdict = OperatorVerdict.ALLOWED if hub.enforce_access else None
609
+ elif cmd is not None and cmd.name == "resolve":
610
+ verdict = OperatorVerdict.BASELINE
611
+ hub.record(WEB_NICK, text, "user")
612
+ if cmd is None:
613
+ reply = "commands start with ! - try !help"
614
+ hub.record("ChimericBot", reply, "system")
615
+ return {"ok": True, "handled": False, "replies": [reply]}
616
+ who = request.client.host if request.client is not None and request.client.host else "unknown"
617
+ replies = await handle_command(hub, WEB_NICK, hub.irc_channel, cmd, verdict=verdict,
618
+ reduce_key=make_reduce_key("terminal", who),
619
+ actor=f"dashboard-terminal:{who}")
620
+ return {"ok": True, "handled": True, "replies": replies}
621
+
622
+ @app.get("/api/workflow")
623
+ async def workflow():
624
+ return hub.workflow()
625
+
626
+ return app
@@ -0,0 +1,25 @@
1
+ """Standing approval rules: hub-side matching, limits, audit and the token-free emergency stop.
2
+
3
+ This file imports no web framework; ``approvals.routes`` is imported by ``api.py`` only.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ from .errors import (
8
+ ActiveProposalExists,
9
+ ApprovalsError,
10
+ ApprovalsNotMigrated,
11
+ ProposalExpired,
12
+ ProposalInvalid,
13
+ ProposalRateLimited,
14
+ RuleConflict,
15
+ RuleInvalid,
16
+ RuleLimitReached,
17
+ RuleNotApplicable,
18
+ RuleNotFound,
19
+ )
20
+
21
+ __all__ = [
22
+ "ActiveProposalExists", "ApprovalsError", "ApprovalsNotMigrated", "ProposalExpired", "ProposalInvalid",
23
+ "ProposalRateLimited", "RuleConflict", "RuleInvalid", "RuleLimitReached", "RuleNotApplicable",
24
+ "RuleNotFound",
25
+ ]