appecosystem-client 0.4.0__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.
Files changed (27) hide show
  1. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/PKG-INFO +1 -1
  2. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/appecosystem_client.egg-info/PKG-INFO +1 -1
  3. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/appecosystem_client.egg-info/SOURCES.txt +1 -0
  4. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/ecosystem_client/__init__.py +1 -1
  5. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/ecosystem_client/contracts.py +70 -11
  6. appecosystem_client-0.4.2/ecosystem_client/registration.py +118 -0
  7. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/pyproject.toml +1 -1
  8. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/LICENSE +0 -0
  9. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/README.md +0 -0
  10. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/appecosystem_client.egg-info/dependency_links.txt +0 -0
  11. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/appecosystem_client.egg-info/requires.txt +0 -0
  12. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/appecosystem_client.egg-info/top_level.txt +0 -0
  13. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/ecosystem_client/config.py +0 -0
  14. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/ecosystem_client/discovery.py +0 -0
  15. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/ecosystem_client/event_publisher.py +0 -0
  16. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/ecosystem_client/event_subscriber.py +0 -0
  17. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/ecosystem_client/log_handler.py +0 -0
  18. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/ecosystem_client/match.py +0 -0
  19. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/ecosystem_client/peer.py +0 -0
  20. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/ecosystem_client/schemas/capability-manifest.v1.schema.json +0 -0
  21. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/ecosystem_client/schemas/command-envelope.v1.schema.json +0 -0
  22. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/ecosystem_client/schemas/event-envelope.v2.schema.json +0 -0
  23. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/ecosystem_client/schemas/notification-envelope.v1.schema.json +0 -0
  24. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/ecosystem_client/schemas/policy-state.v1.schema.json +0 -0
  25. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/ecosystem_client/topology.py +0 -0
  26. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/ecosystem_client/ulid.py +0 -0
  27. {appecosystem_client-0.4.0 → appecosystem_client-0.4.2}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: appecosystem-client
3
- Version: 0.4.0
3
+ Version: 0.4.2
4
4
  Summary: Service registration, peer discovery and event bus client for appEcosystem
5
5
  Author: Mikel Smart
6
6
  License-Expression: MIT
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: appecosystem-client
3
- Version: 0.4.0
3
+ Version: 0.4.2
4
4
  Summary: Service registration, peer discovery and event bus client for appEcosystem
5
5
  Author: Mikel Smart
6
6
  License-Expression: MIT
@@ -15,6 +15,7 @@ ecosystem_client/event_subscriber.py
15
15
  ecosystem_client/log_handler.py
16
16
  ecosystem_client/match.py
17
17
  ecosystem_client/peer.py
18
+ ecosystem_client/registration.py
18
19
  ecosystem_client/topology.py
19
20
  ecosystem_client/ulid.py
20
21
  ecosystem_client/schemas/capability-manifest.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.4.0"
19
+ __version__ = "0.4.2"
20
20
 
21
21
  logger = logging.getLogger(__name__)
22
22
 
@@ -2,6 +2,7 @@
2
2
  from __future__ import annotations
3
3
 
4
4
  import json
5
+ import math
5
6
  import re
6
7
  import time
7
8
  from datetime import datetime, timezone
@@ -146,7 +147,15 @@ def _matches_json_type(value: Any, expected: str) -> bool:
146
147
  return True
147
148
 
148
149
 
149
- def _validate_node(value: Any, schema: dict[str, Any], path: str, errors: list[str]) -> None:
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
150
159
  expected_type = schema.get("type")
151
160
  if expected_type is not None:
152
161
  allowed_types = expected_type if isinstance(expected_type, list) else [expected_type]
@@ -154,8 +163,20 @@ def _validate_node(value: Any, schema: dict[str, Any], path: str, errors: list[s
154
163
  errors.append(f"{path}: expected type {allowed_types}, got {type(value).__name__}")
155
164
  return
156
165
 
157
- if value is None:
158
- return
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")
159
180
 
160
181
  if "const" in schema and value != schema["const"]:
161
182
  errors.append(f"{path}: expected const {schema['const']!r}, got {value!r}")
@@ -166,18 +187,35 @@ def _validate_node(value: Any, schema: dict[str, Any], path: str, errors: list[s
166
187
  if isinstance(value, str):
167
188
  if "minLength" in schema and len(value) < int(schema["minLength"]):
168
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']}")
169
192
  if "pattern" in schema and not re.search(schema["pattern"], value):
170
193
  errors.append(f"{path}: {value!r} does not match pattern {schema['pattern']!r}")
171
194
 
172
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
173
203
  if "minimum" in schema and value < schema["minimum"]:
174
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']}")
175
211
 
176
212
  if isinstance(value, list):
177
213
  if "minItems" in schema and len(value) < int(schema["minItems"]):
178
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")
179
217
  item_schema = schema.get("items")
180
- if isinstance(item_schema, dict):
218
+ if isinstance(item_schema, (dict, bool)):
181
219
  for idx, item in enumerate(value):
182
220
  _validate_node(item, item_schema, f"{path}[{idx}]", errors)
183
221
 
@@ -185,14 +223,35 @@ def _validate_node(value: Any, schema: dict[str, Any], path: str, errors: list[s
185
223
  for req_key in schema.get("required", []):
186
224
  if req_key not in value:
187
225
  errors.append(f"{path}: missing required property {req_key!r}")
188
- props = schema.get("properties", {})
189
- if schema.get("additionalProperties") is False and props:
190
- for key in value:
191
- if key not in props:
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:
192
240
  errors.append(f"{path}: unexpected property {key!r}")
193
- for key, subschema in props.items():
194
- if key in value and isinstance(subschema, dict):
195
- _validate_node(value[key], subschema, f"{path}.{key}", errors)
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
196
255
 
197
256
 
198
257
  def validate_against_schema(
@@ -0,0 +1,118 @@
1
+ """Self-service registration for third-party apps joining the ecosystem.
2
+
3
+ A third-party app calls `register_app` once to obtain its own HMAC key from the
4
+ hub. The key it gets back is PENDING: it authenticates nothing until the
5
+ ecosystem owner approves the app and assigns it the service names and scopes it
6
+ may hold. After approval the app signs its requests with the returned
7
+ `key_id` + `secret` using `ecosystem_auth.tokens.sign_request(..., key_id=key_id)`.
8
+
9
+ from ecosystem_client.registration import register_app, save_credentials, load_credentials
10
+
11
+ creds = load_credentials(path)
12
+ if creds is None:
13
+ creds = register_app("https://hub.local:8500", "org.widget",
14
+ requested_names=["widget_sensor"],
15
+ requested_scopes=["commands:dispatch"])
16
+ save_credentials(path, creds) # keep the secret; it is shown only once
17
+ # ... wait for the owner to approve, then sign requests with creds["key_id"]/["secret"].
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import os
23
+ import tempfile
24
+ from pathlib import Path
25
+ from typing import Any, Callable, Optional
26
+
27
+ __all__ = ["register_app", "save_credentials", "load_credentials"]
28
+
29
+
30
+ _LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1", "[::1]", ""}
31
+
32
+
33
+ def _require_secure_transport(registry_url: str, *, allow_insecure: bool) -> None:
34
+ """Raise ValueError if the URL would send the secret in cleartext to a non-loopback host."""
35
+ if allow_insecure:
36
+ return
37
+ from urllib.parse import urlsplit
38
+
39
+ parts = urlsplit(registry_url if "://" in registry_url else f"//{registry_url}")
40
+ scheme = (parts.scheme or "http").lower()
41
+ host = (parts.hostname or "").lower()
42
+ if scheme == "https":
43
+ return
44
+ if host in _LOOPBACK_HOSTS or host.endswith(".localhost"):
45
+ return
46
+ raise ValueError(
47
+ f"refusing to register over plaintext {scheme or 'http'}:// to non-loopback host "
48
+ f"{host!r}: the HMAC secret would be exposed on the wire. Use https://, or pass "
49
+ f"allow_insecure=True only on a trusted private network."
50
+ )
51
+
52
+
53
+ def register_app(
54
+ registry_url: str,
55
+ app_id: str,
56
+ *,
57
+ display_name: Optional[str] = None,
58
+ owner: str = "",
59
+ requested_names: Optional[list[str]] = None,
60
+ requested_scopes: Optional[list[str]] = None,
61
+ timeout: float = 10.0,
62
+ allow_insecure: bool = False,
63
+ client_factory: Optional[Callable[[], Any]] = None,
64
+ ) -> dict[str, Any]:
65
+ """Register `app_id` with the hub and return its credentials.
66
+
67
+ Returns a dict with `app_id`, `key_id`, `secret` and `status` ("pending").
68
+ The names and scopes are only a request for the owner to review; the key
69
+ holds nothing until approved. Raises `httpx.HTTPStatusError` if the hub
70
+ refuses (e.g. 409 when `app_id` already exists — it is never overwritten).
71
+
72
+ The response carries the app's reusable HMAC `secret`, so plaintext `http://`
73
+ to a non-loopback hub is refused (`ValueError`): on the wire the secret would
74
+ be readable by anyone on the path. Use `https://` for a remote hub. Plain
75
+ `http://localhost` / `127.0.0.1` / `[::1]` is allowed (the loopback never
76
+ leaves the machine); `allow_insecure=True` overrides the check for a trusted
77
+ private network and is not recommended.
78
+ """
79
+ import httpx
80
+
81
+ _require_secure_transport(registry_url, allow_insecure=allow_insecure)
82
+ payload = {
83
+ "app_id": app_id,
84
+ "display_name": display_name or app_id,
85
+ "owner": owner,
86
+ "requested_names": list(requested_names or []),
87
+ "requested_scopes": list(requested_scopes or []),
88
+ }
89
+ url = f"{registry_url.rstrip('/')}/apps/register"
90
+ client_cm = client_factory() if client_factory is not None else httpx.Client(timeout=timeout)
91
+ with client_cm as client:
92
+ resp = client.post(url, json=payload)
93
+ resp.raise_for_status()
94
+ return resp.json()
95
+
96
+
97
+ def save_credentials(path: str | Path, creds: dict[str, Any]) -> None:
98
+ """Write `{app_id, key_id, secret}` to `path` as JSON, mode 0600 (it holds a secret)."""
99
+ p = Path(path)
100
+ p.parent.mkdir(parents=True, exist_ok=True)
101
+ keep = {k: creds[k] for k in ("app_id", "key_id", "secret") if k in creds}
102
+ fd, tmp = tempfile.mkstemp(dir=str(p.parent), prefix=".creds.", suffix=".tmp")
103
+ try:
104
+ with os.fdopen(fd, "w") as f:
105
+ json.dump(keep, f)
106
+ os.chmod(tmp, 0o600)
107
+ os.replace(tmp, p)
108
+ finally:
109
+ if os.path.exists(tmp):
110
+ os.remove(tmp)
111
+
112
+
113
+ def load_credentials(path: str | Path) -> Optional[dict[str, Any]]:
114
+ """Load credentials previously saved by `save_credentials`, or None if absent/unreadable."""
115
+ try:
116
+ return json.loads(Path(path).read_text())
117
+ except (OSError, ValueError):
118
+ return None
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
7
7
  # Prefixed to group the family under the reserved `appEcosystem` PyPI name.
8
8
  # Import name is unchanged: `pip install appecosystem-client` -> `import ecosystem_client`.
9
9
  name = "appecosystem-client"
10
- version = "0.4.0"
10
+ version = "0.4.2"
11
11
  description = "Service registration, peer discovery and event bus client for appEcosystem"
12
12
  readme = "README.md"
13
13
  license = "MIT"