appecosystem-client 0.3.1__tar.gz → 0.4.2__tar.gz
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.
- {appecosystem_client-0.3.1 → appecosystem_client-0.4.2}/PKG-INFO +1 -1
- {appecosystem_client-0.3.1 → appecosystem_client-0.4.2}/appecosystem_client.egg-info/PKG-INFO +1 -1
- {appecosystem_client-0.3.1 → appecosystem_client-0.4.2}/appecosystem_client.egg-info/SOURCES.txt +9 -1
- {appecosystem_client-0.3.1 → appecosystem_client-0.4.2}/ecosystem_client/__init__.py +86 -12
- appecosystem_client-0.4.2/ecosystem_client/contracts.py +499 -0
- {appecosystem_client-0.3.1 → appecosystem_client-0.4.2}/ecosystem_client/discovery.py +18 -0
- {appecosystem_client-0.3.1 → appecosystem_client-0.4.2}/ecosystem_client/event_publisher.py +26 -22
- {appecosystem_client-0.3.1 → appecosystem_client-0.4.2}/ecosystem_client/event_subscriber.py +3 -14
- appecosystem_client-0.4.2/ecosystem_client/registration.py +118 -0
- appecosystem_client-0.4.2/ecosystem_client/schemas/capability-manifest.v1.schema.json +117 -0
- appecosystem_client-0.4.2/ecosystem_client/schemas/command-envelope.v1.schema.json +133 -0
- appecosystem_client-0.4.2/ecosystem_client/schemas/event-envelope.v2.schema.json +63 -0
- appecosystem_client-0.4.2/ecosystem_client/schemas/notification-envelope.v1.schema.json +106 -0
- appecosystem_client-0.4.2/ecosystem_client/schemas/policy-state.v1.schema.json +163 -0
- appecosystem_client-0.4.2/ecosystem_client/ulid.py +88 -0
- {appecosystem_client-0.3.1 → appecosystem_client-0.4.2}/pyproject.toml +4 -1
- {appecosystem_client-0.3.1 → appecosystem_client-0.4.2}/LICENSE +0 -0
- {appecosystem_client-0.3.1 → appecosystem_client-0.4.2}/README.md +0 -0
- {appecosystem_client-0.3.1 → appecosystem_client-0.4.2}/appecosystem_client.egg-info/dependency_links.txt +0 -0
- {appecosystem_client-0.3.1 → appecosystem_client-0.4.2}/appecosystem_client.egg-info/requires.txt +0 -0
- {appecosystem_client-0.3.1 → appecosystem_client-0.4.2}/appecosystem_client.egg-info/top_level.txt +0 -0
- {appecosystem_client-0.3.1 → appecosystem_client-0.4.2}/ecosystem_client/config.py +0 -0
- {appecosystem_client-0.3.1 → appecosystem_client-0.4.2}/ecosystem_client/log_handler.py +0 -0
- {appecosystem_client-0.3.1 → appecosystem_client-0.4.2}/ecosystem_client/match.py +0 -0
- {appecosystem_client-0.3.1 → appecosystem_client-0.4.2}/ecosystem_client/peer.py +0 -0
- {appecosystem_client-0.3.1 → appecosystem_client-0.4.2}/ecosystem_client/topology.py +0 -0
- {appecosystem_client-0.3.1 → appecosystem_client-0.4.2}/setup.cfg +0 -0
{appecosystem_client-0.3.1 → appecosystem_client-0.4.2}/appecosystem_client.egg-info/SOURCES.txt
RENAMED
|
@@ -8,10 +8,18 @@ appecosystem_client.egg-info/requires.txt
|
|
|
8
8
|
appecosystem_client.egg-info/top_level.txt
|
|
9
9
|
ecosystem_client/__init__.py
|
|
10
10
|
ecosystem_client/config.py
|
|
11
|
+
ecosystem_client/contracts.py
|
|
11
12
|
ecosystem_client/discovery.py
|
|
12
13
|
ecosystem_client/event_publisher.py
|
|
13
14
|
ecosystem_client/event_subscriber.py
|
|
14
15
|
ecosystem_client/log_handler.py
|
|
15
16
|
ecosystem_client/match.py
|
|
16
17
|
ecosystem_client/peer.py
|
|
17
|
-
ecosystem_client/
|
|
18
|
+
ecosystem_client/registration.py
|
|
19
|
+
ecosystem_client/topology.py
|
|
20
|
+
ecosystem_client/ulid.py
|
|
21
|
+
ecosystem_client/schemas/capability-manifest.v1.schema.json
|
|
22
|
+
ecosystem_client/schemas/command-envelope.v1.schema.json
|
|
23
|
+
ecosystem_client/schemas/event-envelope.v2.schema.json
|
|
24
|
+
ecosystem_client/schemas/notification-envelope.v1.schema.json
|
|
25
|
+
ecosystem_client/schemas/policy-state.v1.schema.json
|
|
@@ -16,7 +16,7 @@ from .peer import Peer
|
|
|
16
16
|
# Keep in step with packages/ecosystem-client/pyproject.toml. This drifted to
|
|
17
17
|
# 0.1.0 while pyproject said 0.3.1, so anything reporting the runtime version
|
|
18
18
|
# (logs, diagnostics, compatibility checks) named a release that never shipped.
|
|
19
|
-
__version__ = "0.
|
|
19
|
+
__version__ = "0.4.2"
|
|
20
20
|
|
|
21
21
|
logger = logging.getLogger(__name__)
|
|
22
22
|
|
|
@@ -67,10 +67,34 @@ class EcosystemClient:
|
|
|
67
67
|
self._refresh_task: asyncio.Task | None = None
|
|
68
68
|
self._advertised_host: str | None = None # last host we registered with
|
|
69
69
|
|
|
70
|
+
# Backoff tracking for registration failures (401 Unauthorized / offline)
|
|
71
|
+
self._consecutive_auth_failures: int = 0
|
|
72
|
+
self._next_register_time: float = 0.0
|
|
73
|
+
self._base_backoff: float = 10.0
|
|
74
|
+
self._max_backoff: float = 300.0
|
|
75
|
+
|
|
70
76
|
@property
|
|
71
77
|
def mode(self) -> DiscoveryMode:
|
|
72
78
|
return self._discovery.mode
|
|
73
79
|
|
|
80
|
+
@property
|
|
81
|
+
def is_authenticated(self) -> bool:
|
|
82
|
+
"""True if client is not currently backed off or rejected with 401."""
|
|
83
|
+
return not self._discovery.is_unauthorized and self._consecutive_auth_failures == 0
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def registration_backoff(self) -> float:
|
|
87
|
+
"""Seconds remaining before next registration attempt, or 0.0."""
|
|
88
|
+
import time
|
|
89
|
+
return max(0.0, self._next_register_time - time.monotonic())
|
|
90
|
+
|
|
91
|
+
def reset_backoff(self) -> None:
|
|
92
|
+
"""Reset exponential backoff so the next refresh attempts registration immediately."""
|
|
93
|
+
self._consecutive_auth_failures = 0
|
|
94
|
+
self._next_register_time = 0.0
|
|
95
|
+
self._discovery.is_unauthorized = False
|
|
96
|
+
self._discovery.last_status_code = None
|
|
97
|
+
|
|
74
98
|
async def start(self) -> None:
|
|
75
99
|
"""Start the ecosystem client: detect mode, register, discover peers."""
|
|
76
100
|
if self._started:
|
|
@@ -80,7 +104,13 @@ class EcosystemClient:
|
|
|
80
104
|
self._publisher._mode = mode
|
|
81
105
|
|
|
82
106
|
if mode == DiscoveryMode.REGISTRY:
|
|
83
|
-
await self._register_self()
|
|
107
|
+
registered = await self._register_self(force=True)
|
|
108
|
+
if not registered and self._discovery.is_unauthorized:
|
|
109
|
+
logger.warning(
|
|
110
|
+
f"Ecosystem registry rejected registration with 401 Unauthorized for '{self._service_name}'. "
|
|
111
|
+
"Operating in standalone mode until credentials are valid."
|
|
112
|
+
)
|
|
113
|
+
self._publisher._mode = DiscoveryMode.STANDALONE
|
|
84
114
|
|
|
85
115
|
# Discover peers
|
|
86
116
|
await self._refresh_peers()
|
|
@@ -156,11 +186,26 @@ class EcosystemClient:
|
|
|
156
186
|
except Exception:
|
|
157
187
|
return self._get_local_ip()
|
|
158
188
|
|
|
159
|
-
async def _register_self(self) -> bool:
|
|
189
|
+
async def _register_self(self, force: bool = False) -> bool:
|
|
160
190
|
"""(Re-)register this service with the registry using the current
|
|
161
191
|
advertise host. Idempotent — the registry upserts by name, so calling
|
|
162
192
|
this on an interval acts as a heartbeat that keeps our IP and last-seen
|
|
163
|
-
fresh and re-adds us if we were pruned while unreachable.
|
|
193
|
+
fresh and re-adds us if we were pruned while unreachable.
|
|
194
|
+
|
|
195
|
+
If a previous registration attempt failed with 401 Unauthorized,
|
|
196
|
+
respects exponential backoff (10s -> 20s -> 40s -> ... up to 300s max)
|
|
197
|
+
unless force=True.
|
|
198
|
+
"""
|
|
199
|
+
import time
|
|
200
|
+
now = time.monotonic()
|
|
201
|
+
if not force and now < self._next_register_time:
|
|
202
|
+
remaining = int(self._next_register_time - now)
|
|
203
|
+
logger.debug(
|
|
204
|
+
f"Skipping registration heartbeat for '{self._service_name}': "
|
|
205
|
+
f"backing off for {remaining}s due to previous authentication failure"
|
|
206
|
+
)
|
|
207
|
+
return False
|
|
208
|
+
|
|
164
209
|
host = await self._current_advertise_host()
|
|
165
210
|
webhook_url = f"http://{host}:{self._service_port}{self._config.webhook_path}"
|
|
166
211
|
all_subs = list(set(self._subscriptions + self._subscriber.subscriptions))
|
|
@@ -175,7 +220,24 @@ class EcosystemClient:
|
|
|
175
220
|
)
|
|
176
221
|
if ok:
|
|
177
222
|
self._advertised_host = host
|
|
178
|
-
|
|
223
|
+
if self._consecutive_auth_failures > 0:
|
|
224
|
+
logger.info(
|
|
225
|
+
f"Ecosystem registration recovered and authenticated for '{self._service_name}'"
|
|
226
|
+
)
|
|
227
|
+
self._consecutive_auth_failures = 0
|
|
228
|
+
self._next_register_time = 0.0
|
|
229
|
+
self._discovery.is_unauthorized = False
|
|
230
|
+
return True
|
|
231
|
+
else:
|
|
232
|
+
if self._discovery.is_unauthorized or self._discovery.last_status_code == 401:
|
|
233
|
+
self._consecutive_auth_failures += 1
|
|
234
|
+
backoff = min(self._base_backoff * (2 ** (self._consecutive_auth_failures - 1)), self._max_backoff)
|
|
235
|
+
self._next_register_time = now + backoff
|
|
236
|
+
logger.warning(
|
|
237
|
+
f"Ecosystem registration 401 Unauthorized for '{self._service_name}'; "
|
|
238
|
+
f"backing off retry for {backoff:.0f}s (failure count: {self._consecutive_auth_failures})"
|
|
239
|
+
)
|
|
240
|
+
return False
|
|
179
241
|
|
|
180
242
|
async def _refresh_peers(self) -> None:
|
|
181
243
|
"""Refresh the peer list from discovery."""
|
|
@@ -214,14 +276,26 @@ class EcosystemClient:
|
|
|
214
276
|
)
|
|
215
277
|
self._publisher._mode = new_mode
|
|
216
278
|
if new_mode == DiscoveryMode.REGISTRY:
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
logger.info(
|
|
221
|
-
f"Advertise host changed {prev} -> {self._advertised_host}; "
|
|
222
|
-
"re-registered with the new address"
|
|
279
|
+
if self._discovery.is_unauthorized and self.registration_backoff > 0:
|
|
280
|
+
logger.debug(
|
|
281
|
+
f"Periodic refresh: skipping registry heartbeat (backoff active: {self.registration_backoff:.1f}s remaining)"
|
|
223
282
|
)
|
|
224
|
-
|
|
283
|
+
else:
|
|
284
|
+
prev = self._advertised_host
|
|
285
|
+
registered = await self._register_self() # heartbeat / IP refresh
|
|
286
|
+
if registered:
|
|
287
|
+
self._publisher._mode = DiscoveryMode.REGISTRY
|
|
288
|
+
if prev and prev != self._advertised_host:
|
|
289
|
+
logger.info(
|
|
290
|
+
f"Advertise host changed {prev} -> {self._advertised_host}; "
|
|
291
|
+
"re-registered with the new address"
|
|
292
|
+
)
|
|
293
|
+
else:
|
|
294
|
+
if self._discovery.is_unauthorized:
|
|
295
|
+
self._publisher._mode = DiscoveryMode.STANDALONE
|
|
296
|
+
|
|
297
|
+
if not self._discovery.is_unauthorized:
|
|
298
|
+
await self._refresh_peers()
|
|
225
299
|
except Exception as e:
|
|
226
300
|
logger.debug(f"Periodic refresh error: {e}")
|
|
227
301
|
|
|
@@ -0,0 +1,499 @@
|
|
|
1
|
+
"""Phase 1 ecosystem event/command/notification/capability contracts and JSON Schema validation."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
import time
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
from enum import Enum
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from .ulid import generate_ulid, resolve_device_id
|
|
14
|
+
|
|
15
|
+
_SCHEMAS_DIR = Path(__file__).resolve().parent / "schemas"
|
|
16
|
+
_SCHEMA_CACHE: dict[str, dict[str, Any]] = {}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class SchemaValidationError(ValueError):
|
|
20
|
+
"""Raised when an envelope or manifest fails JSON Schema validation."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class EventType(str, Enum):
|
|
24
|
+
"""Canonical dot-delimited event types across the appEcosystem mesh."""
|
|
25
|
+
|
|
26
|
+
# Security events (OpenEye, AegisSIEM, cyber-agents)
|
|
27
|
+
SECURITY_ALERT = "security.alert"
|
|
28
|
+
SECURITY_MOTION_DETECTED = "security.motion_detected"
|
|
29
|
+
SECURITY_PERSON_DETECTED = "security.person_detected"
|
|
30
|
+
SECURITY_INTRUSION = "security.intrusion"
|
|
31
|
+
SECURITY_THREAT_BLOCKED = "security.threat_blocked"
|
|
32
|
+
SECURITY_IOC_MATCH = "security.ioc_match"
|
|
33
|
+
|
|
34
|
+
# System events (any project)
|
|
35
|
+
SYSTEM_STARTUP = "system.startup"
|
|
36
|
+
SYSTEM_SHUTDOWN = "system.shutdown"
|
|
37
|
+
SYSTEM_HEALTH_CHANGED = "system.health_changed"
|
|
38
|
+
SYSTEM_ERROR = "system.error"
|
|
39
|
+
SYSTEM_CONFIG_CHANGED = "system.config_changed"
|
|
40
|
+
|
|
41
|
+
# Network events (AegisSIEM)
|
|
42
|
+
NETWORK_DEVICE_CONNECTED = "network.device_connected"
|
|
43
|
+
NETWORK_DEVICE_DISCONNECTED = "network.device_disconnected"
|
|
44
|
+
NETWORK_ANOMALY = "network.anomaly"
|
|
45
|
+
NETWORK_BANDWIDTH_ALERT = "network.bandwidth_alert"
|
|
46
|
+
|
|
47
|
+
# Display events (MagicMirror)
|
|
48
|
+
DISPLAY_UPDATE = "display.update"
|
|
49
|
+
DISPLAY_ALERT = "display.alert"
|
|
50
|
+
DISPLAY_WIDGET_CHANGED = "display.widget_changed"
|
|
51
|
+
|
|
52
|
+
# AI events (AI_For_Survival, ecosystem-ai)
|
|
53
|
+
AI_ANALYSIS_COMPLETE = "ai.analysis_complete"
|
|
54
|
+
AI_RECOMMENDATION = "ai.recommendation"
|
|
55
|
+
AI_PLAYBOOK_TRIGGERED = "ai.playbook_triggered"
|
|
56
|
+
|
|
57
|
+
# Ecosystem service & freeze lifecycle (registry / hub)
|
|
58
|
+
ECOSYSTEM_SERVICE_REGISTERED = "ecosystem.service_registered"
|
|
59
|
+
ECOSYSTEM_SERVICE_DEREGISTERED = "ecosystem.service_deregistered"
|
|
60
|
+
ECOSYSTEM_SERVICE_UNHEALTHY = "ecosystem.service_unhealthy"
|
|
61
|
+
ECOSYSTEM_AI_PROFILE_CHANGED = "ecosystem.ai_profile_changed"
|
|
62
|
+
ECOSYSTEM_FREEZE_REQUESTED = "ecosystem.freeze_requested"
|
|
63
|
+
ECOSYSTEM_FREEZE_APPLIED = "ecosystem.freeze_applied"
|
|
64
|
+
ECOSYSTEM_RESUME_REQUESTED = "ecosystem.resume_requested"
|
|
65
|
+
|
|
66
|
+
# Scanning lifecycle (Zero-Breach-Toolkit / scan_agent)
|
|
67
|
+
SCAN_REQUESTED = "scan.requested"
|
|
68
|
+
SCAN_STARTED = "scan.started"
|
|
69
|
+
SCAN_PROGRESS = "scan.progress"
|
|
70
|
+
SCAN_COMPLETED = "scan.completed"
|
|
71
|
+
SCAN_FINDING = "scan.finding"
|
|
72
|
+
SCAN_AUTHORIZATION_CHANGED = "scan.authorization_changed"
|
|
73
|
+
|
|
74
|
+
# Policy, approvals & containment (ecosystem-policy / hub)
|
|
75
|
+
POLICY_DECISION = "policy.decision"
|
|
76
|
+
POLICY_MODE_CHANGED = "policy.mode_changed"
|
|
77
|
+
POLICY_RESTRICTIONS_CHANGED = "policy.restrictions_changed"
|
|
78
|
+
APPROVAL_REQUESTED = "approval.requested"
|
|
79
|
+
APPROVAL_DECIDED = "approval.decided"
|
|
80
|
+
CONTAINMENT_APPLIED = "containment.applied"
|
|
81
|
+
CONTAINMENT_REVERTED = "containment.reverted"
|
|
82
|
+
|
|
83
|
+
# Capabilities & automations
|
|
84
|
+
CAPABILITY_REGISTERED = "capability.registered"
|
|
85
|
+
CAPABILITY_WITHDRAWN = "capability.withdrawn"
|
|
86
|
+
AUTOMATION_REQUESTED = "automation.requested"
|
|
87
|
+
AUTOMATION_COMPLETED = "automation.completed"
|
|
88
|
+
AUTOMATION_FAILED = "automation.failed"
|
|
89
|
+
|
|
90
|
+
# Cross-device notifications (notify.*)
|
|
91
|
+
NOTIFY_SECURITY = "notify.security"
|
|
92
|
+
NOTIFY_SYSTEM = "notify.system"
|
|
93
|
+
NOTIFY_SCAN = "notify.scan"
|
|
94
|
+
NOTIFY_POLICY = "notify.policy"
|
|
95
|
+
NOTIFY_APPROVAL = "notify.approval"
|
|
96
|
+
NOTIFY_AUTOMATION = "notify.automation"
|
|
97
|
+
|
|
98
|
+
# Compute broker & Model Forge
|
|
99
|
+
COMPUTE_JOB_STARTED = "compute.job.started"
|
|
100
|
+
COMPUTE_JOB_COMPLETED = "compute.job.completed"
|
|
101
|
+
COMPUTE_JOB_FAILED = "compute.job.failed"
|
|
102
|
+
MODEL_PUBLISHED = "model.published"
|
|
103
|
+
|
|
104
|
+
# Device enrollment
|
|
105
|
+
DEVICE_ENROLLED = "device.enrolled"
|
|
106
|
+
DEVICE_UNENROLLED = "device.unenrolled"
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def list_schemas() -> list[str]:
|
|
110
|
+
"""Return available contract schema base names (e.g. 'event-envelope.v2')."""
|
|
111
|
+
if not _SCHEMAS_DIR.is_dir():
|
|
112
|
+
return []
|
|
113
|
+
return sorted(
|
|
114
|
+
p.name[: -len(".schema.json")]
|
|
115
|
+
for p in _SCHEMAS_DIR.glob("*.schema.json")
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def load_schema(name: str) -> dict[str, Any]:
|
|
120
|
+
"""Load a published JSON Schema by name (with or without '.schema.json')."""
|
|
121
|
+
key = name[: -len(".schema.json")] if name.endswith(".schema.json") else name
|
|
122
|
+
if key in _SCHEMA_CACHE:
|
|
123
|
+
return _SCHEMA_CACHE[key]
|
|
124
|
+
path = _SCHEMAS_DIR / f"{key}.schema.json"
|
|
125
|
+
if not path.is_file():
|
|
126
|
+
raise FileNotFoundError(f"Unknown ecosystem contract schema: {name!r}")
|
|
127
|
+
schema = json.loads(path.read_text(encoding="utf-8"))
|
|
128
|
+
_SCHEMA_CACHE[key] = schema
|
|
129
|
+
return schema
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _matches_json_type(value: Any, expected: str) -> bool:
|
|
133
|
+
if expected == "null":
|
|
134
|
+
return value is None
|
|
135
|
+
if expected == "boolean":
|
|
136
|
+
return isinstance(value, bool)
|
|
137
|
+
if expected == "integer":
|
|
138
|
+
return isinstance(value, int) and not isinstance(value, bool)
|
|
139
|
+
if expected == "number":
|
|
140
|
+
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
|
141
|
+
if expected == "string":
|
|
142
|
+
return isinstance(value, str)
|
|
143
|
+
if expected == "object":
|
|
144
|
+
return isinstance(value, dict)
|
|
145
|
+
if expected == "array":
|
|
146
|
+
return isinstance(value, list)
|
|
147
|
+
return True
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _validate_node(value: Any, schema: Any, path: str, errors: list[str]) -> None:
|
|
151
|
+
# Boolean schemas are schemas: true accepts every instance, false rejects every one.
|
|
152
|
+
if schema is True:
|
|
153
|
+
return
|
|
154
|
+
if schema is False:
|
|
155
|
+
errors.append(f"{path}: no value is allowed here")
|
|
156
|
+
return
|
|
157
|
+
if not isinstance(schema, dict):
|
|
158
|
+
return
|
|
159
|
+
expected_type = schema.get("type")
|
|
160
|
+
if expected_type is not None:
|
|
161
|
+
allowed_types = expected_type if isinstance(expected_type, list) else [expected_type]
|
|
162
|
+
if not any(_matches_json_type(value, t) for t in allowed_types):
|
|
163
|
+
errors.append(f"{path}: expected type {allowed_types}, got {type(value).__name__}")
|
|
164
|
+
return
|
|
165
|
+
|
|
166
|
+
# Combinators apply to every instance, null included. Each branch is validated
|
|
167
|
+
# in a scratch list so a failing branch reports only through the combinator.
|
|
168
|
+
for sub in _subschemas(schema.get("allOf")):
|
|
169
|
+
_validate_node(value, sub, path, errors)
|
|
170
|
+
any_of = _subschemas(schema.get("anyOf"))
|
|
171
|
+
if any_of and not any(_passes(value, sub, path) for sub in any_of):
|
|
172
|
+
errors.append(f"{path}: matches none of the anyOf alternatives")
|
|
173
|
+
one_of = _subschemas(schema.get("oneOf"))
|
|
174
|
+
if one_of:
|
|
175
|
+
matched = sum(1 for sub in one_of if _passes(value, sub, path))
|
|
176
|
+
if matched != 1:
|
|
177
|
+
errors.append(f"{path}: must match exactly one oneOf alternative, matched {matched}")
|
|
178
|
+
if "not" in schema and isinstance(schema["not"], (dict, bool)) and _passes(value, schema["not"], path):
|
|
179
|
+
errors.append(f"{path}: must not match the 'not' schema")
|
|
180
|
+
|
|
181
|
+
if "const" in schema and value != schema["const"]:
|
|
182
|
+
errors.append(f"{path}: expected const {schema['const']!r}, got {value!r}")
|
|
183
|
+
|
|
184
|
+
if "enum" in schema and value not in schema["enum"]:
|
|
185
|
+
errors.append(f"{path}: value {value!r} not in {schema['enum']}")
|
|
186
|
+
|
|
187
|
+
if isinstance(value, str):
|
|
188
|
+
if "minLength" in schema and len(value) < int(schema["minLength"]):
|
|
189
|
+
errors.append(f"{path}: string shorter than minLength {schema['minLength']}")
|
|
190
|
+
if "maxLength" in schema and len(value) > int(schema["maxLength"]):
|
|
191
|
+
errors.append(f"{path}: string longer than maxLength {schema['maxLength']}")
|
|
192
|
+
if "pattern" in schema and not re.search(schema["pattern"], value):
|
|
193
|
+
errors.append(f"{path}: {value!r} does not match pattern {schema['pattern']!r}")
|
|
194
|
+
|
|
195
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
196
|
+
# NaN compares false against every bound and Infinity passes "type": "number";
|
|
197
|
+
# Python's json accepts both. A bounded number must be finite.
|
|
198
|
+
if isinstance(value, float) and not math.isfinite(value) and any(
|
|
199
|
+
k in schema for k in ("minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum")
|
|
200
|
+
):
|
|
201
|
+
errors.append(f"{path}: {value} is not a finite number")
|
|
202
|
+
return
|
|
203
|
+
if "minimum" in schema and value < schema["minimum"]:
|
|
204
|
+
errors.append(f"{path}: {value} < minimum {schema['minimum']}")
|
|
205
|
+
if "maximum" in schema and value > schema["maximum"]:
|
|
206
|
+
errors.append(f"{path}: {value} > maximum {schema['maximum']}")
|
|
207
|
+
if "exclusiveMinimum" in schema and value <= schema["exclusiveMinimum"]:
|
|
208
|
+
errors.append(f"{path}: {value} <= exclusiveMinimum {schema['exclusiveMinimum']}")
|
|
209
|
+
if "exclusiveMaximum" in schema and value >= schema["exclusiveMaximum"]:
|
|
210
|
+
errors.append(f"{path}: {value} >= exclusiveMaximum {schema['exclusiveMaximum']}")
|
|
211
|
+
|
|
212
|
+
if isinstance(value, list):
|
|
213
|
+
if "minItems" in schema and len(value) < int(schema["minItems"]):
|
|
214
|
+
errors.append(f"{path}: array has fewer than {schema['minItems']} items")
|
|
215
|
+
if "maxItems" in schema and len(value) > int(schema["maxItems"]):
|
|
216
|
+
errors.append(f"{path}: array has more than {schema['maxItems']} items")
|
|
217
|
+
item_schema = schema.get("items")
|
|
218
|
+
if isinstance(item_schema, (dict, bool)):
|
|
219
|
+
for idx, item in enumerate(value):
|
|
220
|
+
_validate_node(item, item_schema, f"{path}[{idx}]", errors)
|
|
221
|
+
|
|
222
|
+
if isinstance(value, dict):
|
|
223
|
+
for req_key in schema.get("required", []):
|
|
224
|
+
if req_key not in value:
|
|
225
|
+
errors.append(f"{path}: missing required property {req_key!r}")
|
|
226
|
+
props = schema.get("properties") or {}
|
|
227
|
+
patterns = schema.get("patternProperties") or {}
|
|
228
|
+
additional = schema.get("additionalProperties", True)
|
|
229
|
+
for key, item in value.items():
|
|
230
|
+
if key in props:
|
|
231
|
+
_validate_node(item, props[key], f"{path}.{key}", errors)
|
|
232
|
+
matched = [sub for pattern, sub in patterns.items() if re.search(pattern, key)]
|
|
233
|
+
for sub in matched:
|
|
234
|
+
_validate_node(item, sub, f"{path}.{key}", errors)
|
|
235
|
+
if key not in props and not matched:
|
|
236
|
+
# A key no property or pattern names. With additionalProperties false,
|
|
237
|
+
# even when nothing is declared (a command that takes no parameters),
|
|
238
|
+
# it is not allowed; a schema there validates it instead.
|
|
239
|
+
if additional is False:
|
|
240
|
+
errors.append(f"{path}: unexpected property {key!r}")
|
|
241
|
+
elif isinstance(additional, dict):
|
|
242
|
+
_validate_node(item, additional, f"{path}.{key}", errors)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _subschemas(items: Any) -> list[Any]:
|
|
246
|
+
"""The usable subschemas of a combinator: objects and booleans, never silently dropped."""
|
|
247
|
+
return [s for s in (items or []) if isinstance(s, (dict, bool))]
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _passes(value: Any, schema: Any, path: str) -> bool:
|
|
251
|
+
"""Whether `value` satisfies `schema`, without recording that schema's errors."""
|
|
252
|
+
scratch: list[str] = []
|
|
253
|
+
_validate_node(value, schema, path, scratch)
|
|
254
|
+
return not scratch
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def validate_against_schema(
|
|
258
|
+
instance: Any, schema: str | dict[str, Any]
|
|
259
|
+
) -> list[str]:
|
|
260
|
+
"""Validate an instance against a named or inline JSON Schema. Returns errors."""
|
|
261
|
+
schema_dict = load_schema(schema) if isinstance(schema, str) else schema
|
|
262
|
+
errors: list[str] = []
|
|
263
|
+
_validate_node(instance, schema_dict, "$", errors)
|
|
264
|
+
return errors
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def assert_valid_schema(instance: Any, schema: str | dict[str, Any]) -> None:
|
|
268
|
+
"""Raise SchemaValidationError if instance violates schema."""
|
|
269
|
+
errors = validate_against_schema(instance, schema)
|
|
270
|
+
if errors:
|
|
271
|
+
raise SchemaValidationError("; ".join(errors))
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _norm_ts(value: Any) -> Any:
|
|
275
|
+
"""Normalize whole-number floats to int so Python json.dumps matches JS JSON.stringify."""
|
|
276
|
+
if isinstance(value, float) and value.is_integer():
|
|
277
|
+
return int(value)
|
|
278
|
+
return value
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def canonical_signable_event(envelope: dict[str, Any]) -> dict[str, Any]:
|
|
282
|
+
"""Produce the canonical dict signed by HMAC-SHA256 for v2 or legacy v1 events."""
|
|
283
|
+
version = envelope.get("schema_version")
|
|
284
|
+
if isinstance(version, int) and version >= 2:
|
|
285
|
+
src = envelope.get("source")
|
|
286
|
+
if isinstance(src, str):
|
|
287
|
+
src_obj = {"app": src, "device_id": resolve_device_id()}
|
|
288
|
+
elif isinstance(src, dict):
|
|
289
|
+
src_obj = {"app": str(src.get("app", "")), "device_id": str(src.get("device_id", ""))}
|
|
290
|
+
else:
|
|
291
|
+
src_obj = {
|
|
292
|
+
"app": str(getattr(src, "app", "")),
|
|
293
|
+
"device_id": str(getattr(src, "device_id", "")),
|
|
294
|
+
}
|
|
295
|
+
signable: dict[str, Any] = {
|
|
296
|
+
"schema_version": version,
|
|
297
|
+
"id": envelope.get("id", ""),
|
|
298
|
+
"type": envelope.get("type", ""),
|
|
299
|
+
"source": src_obj,
|
|
300
|
+
"timestamp": _norm_ts(envelope.get("timestamp", 0)),
|
|
301
|
+
"data": envelope.get("data", {}),
|
|
302
|
+
}
|
|
303
|
+
if envelope.get("correlation_id") is not None:
|
|
304
|
+
signable["correlation_id"] = envelope["correlation_id"]
|
|
305
|
+
return signable
|
|
306
|
+
|
|
307
|
+
# Legacy v1 envelope (5-field layout; coerce EventSource/dict back to app string)
|
|
308
|
+
raw_src = envelope.get("source", "")
|
|
309
|
+
if isinstance(raw_src, dict):
|
|
310
|
+
v1_source = str(raw_src.get("app", ""))
|
|
311
|
+
elif isinstance(raw_src, str):
|
|
312
|
+
v1_source = raw_src
|
|
313
|
+
else:
|
|
314
|
+
v1_source = str(getattr(raw_src, "app", raw_src))
|
|
315
|
+
return {
|
|
316
|
+
"id": envelope.get("id", ""),
|
|
317
|
+
"type": envelope.get("type", ""),
|
|
318
|
+
"source": v1_source,
|
|
319
|
+
"timestamp": envelope.get("timestamp", 0),
|
|
320
|
+
"data": envelope.get("data", {}),
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def build_event_envelope_v2(
|
|
325
|
+
event_type: str,
|
|
326
|
+
source_app: str,
|
|
327
|
+
data: dict[str, Any] | None = None,
|
|
328
|
+
secret: str = "",
|
|
329
|
+
*,
|
|
330
|
+
device_id: str | None = None,
|
|
331
|
+
correlation_id: str | None = None,
|
|
332
|
+
event_id: str | None = None,
|
|
333
|
+
timestamp: float | None = None,
|
|
334
|
+
) -> dict[str, Any]:
|
|
335
|
+
"""Construct and HMAC-sign a v2 event envelope."""
|
|
336
|
+
from ecosystem_auth.tokens import sign_payload
|
|
337
|
+
|
|
338
|
+
envelope: dict[str, Any] = {
|
|
339
|
+
"schema_version": 2,
|
|
340
|
+
"id": event_id or generate_ulid(),
|
|
341
|
+
"type": event_type,
|
|
342
|
+
"source": {
|
|
343
|
+
"app": source_app,
|
|
344
|
+
"device_id": device_id or resolve_device_id(),
|
|
345
|
+
},
|
|
346
|
+
"timestamp": _norm_ts(time.time() if timestamp is None else float(timestamp)),
|
|
347
|
+
"data": dict(data or {}),
|
|
348
|
+
}
|
|
349
|
+
if correlation_id is not None:
|
|
350
|
+
envelope["correlation_id"] = correlation_id
|
|
351
|
+
|
|
352
|
+
envelope["signature"] = sign_payload(canonical_signable_event(envelope), secret)
|
|
353
|
+
return envelope
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def verify_event_envelope(envelope: dict[str, Any], secret: str) -> bool:
|
|
357
|
+
"""Verify HMAC-SHA256 signature on either a v2 or legacy v1 event envelope."""
|
|
358
|
+
from ecosystem_auth.tokens import verify_signature
|
|
359
|
+
|
|
360
|
+
signature = envelope.get("signature")
|
|
361
|
+
if not signature or not isinstance(signature, str):
|
|
362
|
+
return False
|
|
363
|
+
return verify_signature(canonical_signable_event(envelope), signature, secret)
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def canonical_signable_command(envelope: dict[str, Any]) -> dict[str, Any]:
|
|
367
|
+
"""Return the canonical dict signed for a v1 CommandEnvelope."""
|
|
368
|
+
out: dict[str, Any] = {}
|
|
369
|
+
for k, v in envelope.items():
|
|
370
|
+
if k == "signature":
|
|
371
|
+
continue
|
|
372
|
+
if k in ("issued_at", "expires_at"):
|
|
373
|
+
out[k] = _norm_ts(v)
|
|
374
|
+
else:
|
|
375
|
+
out[k] = v
|
|
376
|
+
return out
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def build_command_envelope(
|
|
380
|
+
command: str,
|
|
381
|
+
action_class: str,
|
|
382
|
+
actor: dict[str, Any],
|
|
383
|
+
target: dict[str, Any],
|
|
384
|
+
secret: str,
|
|
385
|
+
*,
|
|
386
|
+
parameters: dict[str, Any] | None = None,
|
|
387
|
+
ttl_seconds: float = 60.0,
|
|
388
|
+
correlation_id: str | None = None,
|
|
389
|
+
idempotency_key: str | None = None,
|
|
390
|
+
authorization_ref: str | None = None,
|
|
391
|
+
rationale: str | None = None,
|
|
392
|
+
ack_required: bool = True,
|
|
393
|
+
issued_at: float | None = None,
|
|
394
|
+
command_id: str | None = None,
|
|
395
|
+
) -> dict[str, Any]:
|
|
396
|
+
"""Build and sign a v1 CommandEnvelope enforcing actor, target, expiry, and idempotency."""
|
|
397
|
+
from ecosystem_auth.tokens import sign_payload
|
|
398
|
+
|
|
399
|
+
if authorization_ref and str(authorization_ref).startswith(("notify:", "notify.")):
|
|
400
|
+
raise ValueError("A notification identifier is never a valid command authorization_ref")
|
|
401
|
+
|
|
402
|
+
cid = command_id or generate_ulid()
|
|
403
|
+
now_ts = time.time() if issued_at is None else float(issued_at)
|
|
404
|
+
envelope: dict[str, Any] = {
|
|
405
|
+
"schema_version": 1,
|
|
406
|
+
"id": cid,
|
|
407
|
+
"command": command,
|
|
408
|
+
"action_class": action_class,
|
|
409
|
+
"actor": dict(actor),
|
|
410
|
+
"target": dict(target),
|
|
411
|
+
"parameters": dict(parameters or {}),
|
|
412
|
+
"issued_at": _norm_ts(now_ts),
|
|
413
|
+
"expires_at": _norm_ts(now_ts + float(ttl_seconds)),
|
|
414
|
+
"correlation_id": correlation_id or cid,
|
|
415
|
+
"idempotency_key": idempotency_key or cid,
|
|
416
|
+
"authorization_ref": authorization_ref,
|
|
417
|
+
"rationale": rationale,
|
|
418
|
+
"ack_required": bool(ack_required),
|
|
419
|
+
}
|
|
420
|
+
envelope["signature"] = sign_payload(canonical_signable_command(envelope), secret)
|
|
421
|
+
assert_valid_schema(envelope, "command-envelope.v1")
|
|
422
|
+
return envelope
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def verify_command_envelope(
|
|
426
|
+
envelope: dict[str, Any],
|
|
427
|
+
secret: str,
|
|
428
|
+
*,
|
|
429
|
+
now: float | None = None,
|
|
430
|
+
) -> tuple[bool, str]:
|
|
431
|
+
"""Verify schema, authorization_ref safety, expiry, and HMAC signature of a CommandEnvelope."""
|
|
432
|
+
from ecosystem_auth.tokens import verify_signature
|
|
433
|
+
|
|
434
|
+
errors = validate_against_schema(envelope, "command-envelope.v1")
|
|
435
|
+
if errors:
|
|
436
|
+
return False, f"schema invalid: {errors[0]}"
|
|
437
|
+
|
|
438
|
+
auth_ref = envelope.get("authorization_ref")
|
|
439
|
+
if auth_ref and str(auth_ref).startswith(("notify:", "notify.")):
|
|
440
|
+
return False, "notification reference cannot authorize a command"
|
|
441
|
+
|
|
442
|
+
current = time.time() if now is None else float(now)
|
|
443
|
+
issued_at = float(envelope["issued_at"])
|
|
444
|
+
expires_at = float(envelope["expires_at"])
|
|
445
|
+
if expires_at <= issued_at:
|
|
446
|
+
return False, "expires_at must be greater than issued_at"
|
|
447
|
+
if current > expires_at:
|
|
448
|
+
return False, "command expired"
|
|
449
|
+
|
|
450
|
+
sig = envelope.get("signature", "")
|
|
451
|
+
if not verify_signature(canonical_signable_command(envelope), sig, secret):
|
|
452
|
+
return False, "invalid command signature"
|
|
453
|
+
|
|
454
|
+
return True, "ok"
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def build_notification_envelope(
|
|
458
|
+
notify_type: str,
|
|
459
|
+
source_app: str,
|
|
460
|
+
severity: str,
|
|
461
|
+
title: str,
|
|
462
|
+
body: str,
|
|
463
|
+
*,
|
|
464
|
+
dedupe_key: str,
|
|
465
|
+
device_id: str | None = None,
|
|
466
|
+
actions: list[dict[str, Any]] | None = None,
|
|
467
|
+
privacy: str = "redacted",
|
|
468
|
+
ttl: str = "24h",
|
|
469
|
+
deep_link: str | None = None,
|
|
470
|
+
secret: str | None = None,
|
|
471
|
+
notification_id: str | None = None,
|
|
472
|
+
created_at: str | None = None,
|
|
473
|
+
) -> dict[str, Any]:
|
|
474
|
+
"""Build (and optionally sign) a v1 NotificationEnvelope."""
|
|
475
|
+
from ecosystem_auth.tokens import sign_payload
|
|
476
|
+
|
|
477
|
+
envelope: dict[str, Any] = {
|
|
478
|
+
"schema_version": 1,
|
|
479
|
+
"type": notify_type,
|
|
480
|
+
"id": notification_id or generate_ulid(),
|
|
481
|
+
"dedupe_key": dedupe_key,
|
|
482
|
+
"source": {
|
|
483
|
+
"app": source_app,
|
|
484
|
+
"device_id": device_id or resolve_device_id(),
|
|
485
|
+
},
|
|
486
|
+
"severity": severity,
|
|
487
|
+
"title": title,
|
|
488
|
+
"body": body,
|
|
489
|
+
"actions": list(actions or []),
|
|
490
|
+
"privacy": privacy,
|
|
491
|
+
"ttl": ttl,
|
|
492
|
+
"deep_link": deep_link,
|
|
493
|
+
"created_at": created_at or datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
494
|
+
}
|
|
495
|
+
if secret:
|
|
496
|
+
signable = {k: v for k, v in envelope.items() if k != "signature"}
|
|
497
|
+
envelope["signature"] = sign_payload(signable, secret)
|
|
498
|
+
assert_valid_schema(envelope, "notification-envelope.v1")
|
|
499
|
+
return envelope
|