nacho-python 0.1.1__py3-none-any.whl → 1.0.0__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.
nacho/__init__.py CHANGED
@@ -4,6 +4,7 @@ from ._version import __version__
4
4
  from .config import Nacho
5
5
  from .event import EventType
6
6
  from .schema import HAS_SCHEMA_DEPS, ValidationError
7
+ from .server import HAS_SERVER_DEPS, NachoOrchestrator
7
8
  from .storage import (
8
9
  HAS_REMOTE_DEPS,
9
10
  AuthError,
@@ -16,13 +17,6 @@ from .storage import (
16
17
  StorageError,
17
18
  )
18
19
 
19
- try:
20
- from .server.app import NachoOrchestrator
21
-
22
- HAS_SERVER_DEPS = True
23
- except ImportError: # pragma: no cover - optional 'server' extra not installed
24
- HAS_SERVER_DEPS = False
25
-
26
20
  __all__ = [
27
21
  "__version__",
28
22
  "Nacho",
@@ -41,6 +35,3 @@ __all__ = [
41
35
  "HAS_REMOTE_DEPS",
42
36
  "HAS_SERVER_DEPS",
43
37
  ]
44
- if not HAS_SERVER_DEPS:
45
- # Keep __all__ truthful so `from nacho import *` never hits an undefined name.
46
- __all__.remove("NachoOrchestrator")
nacho/_version.py CHANGED
@@ -1,3 +1,3 @@
1
1
  """Version information for Nacho."""
2
2
 
3
- __version__ = "0.1.1"
3
+ __version__ = "1.0.0"
nacho/cli/main.py CHANGED
@@ -26,11 +26,9 @@ if TYPE_CHECKING: # pragma: no cover - typing only
26
26
 
27
27
  LOGGER = logging.getLogger("nacho.cli")
28
28
 
29
- # Exit codes. EXIT_USAGE is argparse's own code for bad arguments; the rest
30
- # are produced by the @cli_command wrapper from the typed client errors.
29
+ # Exit codes produced by the @cli_command wrapper from typed client errors.
31
30
  EXIT_OK = 0
32
31
  EXIT_ERROR = 1
33
- EXIT_USAGE = 2
34
32
  EXIT_NOT_FOUND = 3
35
33
  EXIT_CONFLICT = 4
36
34
  EXIT_AUTH = 5
@@ -245,10 +243,6 @@ def create_parser() -> argparse.ArgumentParser:
245
243
  server.add_argument("--schema", help="Schema file path")
246
244
  server.add_argument("--data-dir", help="Directory for API-created app state")
247
245
  server.add_argument("--api-key", help="API key for authentication")
248
- server.add_argument(
249
- "--read-only-api-key",
250
- help="Additional API key granting read access only (GETs and WebSocket watch)",
251
- )
252
246
  server.add_argument("--app-name", help="Application name for config server")
253
247
  server.add_argument(
254
248
  "--history-limit",
@@ -256,7 +250,11 @@ def create_parser() -> argparse.ArgumentParser:
256
250
  default=50,
257
251
  help="Revision snapshots to keep per app for rollback (0 disables history)",
258
252
  )
259
- server.add_argument("--read-only", action="store_true", help="Read-only mode")
253
+ server.add_argument(
254
+ "--read-only",
255
+ action="store_true",
256
+ help="Serve reads only — every write is refused, whoever the caller is",
257
+ )
260
258
  server.add_argument("--reload", action="store_true", help="Auto-reload for development")
261
259
  server.set_defaults(func=cmd_server)
262
260
 
@@ -443,9 +441,7 @@ def cmd_server(args: argparse.Namespace) -> int:
443
441
 
444
442
  print(banner())
445
443
 
446
- # With only a read-only key configured, nobody can write at all, so the
447
- # exposure warning only applies when NO key protects the server.
448
- if not args.api_key and not args.read_only_api_key and not is_loopback_host(args.host):
444
+ if not args.api_key and not is_loopback_host(args.host):
449
445
  print(
450
446
  "WARNING: serving on a non-loopback interface without --api-key — "
451
447
  "anyone who can reach this host has full write access.",
@@ -460,7 +456,6 @@ def cmd_server(args: argparse.Namespace) -> int:
460
456
  orchestrator = NachoOrchestrator(
461
457
  apps=apps,
462
458
  api_key=args.api_key,
463
- read_only_api_key=args.read_only_api_key,
464
459
  read_only=args.read_only,
465
460
  data_dir=args.data_dir,
466
461
  history_limit=args.history_limit,
nacho/client.py CHANGED
@@ -12,6 +12,7 @@ Requires the ``remote`` extra (``pip install nacho-python[remote]``).
12
12
  from __future__ import annotations
13
13
 
14
14
  from typing import Any, Dict, List, Optional, Tuple
15
+ from urllib.parse import quote
15
16
 
16
17
  import requests
17
18
 
@@ -40,6 +41,7 @@ class NachoClient:
40
41
  self.app_name = app_name
41
42
  self.api_key = api_key
42
43
  self.timeout = timeout
44
+ self.last_generation: Optional[str] = None
43
45
 
44
46
  # ------------------------------------------------------------------
45
47
  # Low-level request plumbing
@@ -109,7 +111,12 @@ class NachoClient:
109
111
  raise RemoteError(message, status=status_code, detail=detail)
110
112
 
111
113
  def _app(self, suffix: str = "") -> str:
112
- return f"/api/apps/{self.app_name}{suffix}"
114
+ return f"/api/apps/{quote(self.app_name, safe='')}{suffix}"
115
+
116
+ def _record_generation(self, resp: requests.Response) -> None:
117
+ generation = resp.headers.get("X-Nacho-Generation")
118
+ if generation:
119
+ self.last_generation = generation
113
120
 
114
121
  @staticmethod
115
122
  def _revision_from(resp: requests.Response) -> Optional[int]:
@@ -181,6 +188,7 @@ class NachoClient:
181
188
 
182
189
  def get_config(self) -> Tuple[Dict[str, Any], Optional[int]]:
183
190
  resp = self.request("GET", self._app("/config"))
191
+ self._record_generation(resp)
184
192
  return resp.json(), self._revision_from(resp)
185
193
 
186
194
  def put_config(
@@ -192,7 +200,8 @@ class NachoClient:
192
200
  return self.request("PUT", self._app("/config"), json_body=payload).json()
193
201
 
194
202
  def get_path(self, path: str) -> Tuple[Any, Optional[int]]:
195
- resp = self.request("GET", self._app(f"/config/{path}"))
203
+ resp = self.request("GET", self._app(f"/config/{quote(path, safe='')}"))
204
+ self._record_generation(resp)
196
205
  return resp.json()["value"], self._revision_from(resp)
197
206
 
198
207
  def set_path(
@@ -206,11 +215,15 @@ class NachoClient:
206
215
  payload: Dict[str, Any] = {"value": value, "type": value_type}
207
216
  if revision is not None:
208
217
  payload["revision"] = revision
209
- return self.request("PUT", self._app(f"/config/{path}"), json_body=payload).json()
218
+ return self.request(
219
+ "PUT", self._app(f"/config/{quote(path, safe='')}"), json_body=payload
220
+ ).json()
210
221
 
211
222
  def delete_path(self, path: str, *, revision: Optional[int] = None) -> Dict[str, Any]:
212
223
  params = {"revision": revision} if revision is not None else None
213
- return self.request("DELETE", self._app(f"/config/{path}"), params=params).json()
224
+ return self.request(
225
+ "DELETE", self._app(f"/config/{quote(path, safe='')}"), params=params
226
+ ).json()
214
227
 
215
228
  # ------------------------------------------------------------------
216
229
  # Schema
nacho/config.py CHANGED
@@ -451,6 +451,13 @@ class Nacho:
451
451
  data = copy.deepcopy(self._data)
452
452
  return self._validator.check(data)
453
453
 
454
+ @property
455
+ def schema(self) -> Optional[Dict[str, Any]]:
456
+ """The currently enforced JSON Schema, or ``None`` when validation is off."""
457
+ if self._validator is None:
458
+ return None
459
+ return self._validator.schema
460
+
454
461
  # ------------------------------------------------------------------
455
462
  # Transactions
456
463
  # ------------------------------------------------------------------
nacho/schema.py CHANGED
@@ -7,6 +7,7 @@ has to check a return value — invalid writes are refused immediately.
7
7
 
8
8
  from __future__ import annotations
9
9
 
10
+ import copy
10
11
  import logging
11
12
  from pathlib import Path
12
13
  from typing import Any, Dict, List, Union
@@ -60,6 +61,11 @@ class SchemaValidator:
60
61
  format_checker=jsonschema.FormatChecker(),
61
62
  )
62
63
 
64
+ @property
65
+ def schema(self) -> Dict[str, Any]:
66
+ """Return an isolated copy of the schema enforced by this validator."""
67
+ return copy.deepcopy(self._schema)
68
+
63
69
  # ------------------------------------------------------------------
64
70
  # Public API
65
71
  # ------------------------------------------------------------------
nacho/server/app.py CHANGED
@@ -67,7 +67,6 @@ class NachoOrchestrator:
67
67
  data_dir: Optional[Union[str, Path]] = None,
68
68
  logger: Optional[logging.Logger] = None,
69
69
  history_limit: int = 50,
70
- read_only_api_key: Optional[str] = None,
71
70
  ) -> None:
72
71
  self.read_only = read_only
73
72
  # No CORS by default: the bundled UI is same-origin and SDK/CLI
@@ -78,12 +77,7 @@ class NachoOrchestrator:
78
77
  # (e.g. an empty list from a caller's own config) would otherwise
79
78
  # skip AuthGuard entirely and leave the server unauthenticated.
80
79
  api_key = validate_api_key("api_key", api_key)
81
- read_only_api_key = validate_api_key("read_only_api_key", read_only_api_key)
82
- self.auth = (
83
- AuthGuard(api_key=api_key, read_only_api_key=read_only_api_key)
84
- if (api_key or read_only_api_key)
85
- else None
86
- )
80
+ self.auth = AuthGuard(api_key=api_key) if api_key else None
87
81
  self.manager = AppManager(
88
82
  data_dir=Path(data_dir) if data_dir else None,
89
83
  logger=self.logger,
@@ -128,12 +122,20 @@ class NachoOrchestrator:
128
122
  async def cap_body_size(request: Request, call_next):
129
123
  length = request.headers.get("content-length")
130
124
  if length and length.isdigit() and int(length) > _MAX_BODY_BYTES:
131
- return JSONResponse(
132
- status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
133
- content={
134
- "detail": f"Request body exceeds {_MAX_BODY_BYTES // (1024 * 1024)} MiB"
135
- },
136
- )
125
+ return self._body_too_large()
126
+ if request.method in {"POST", "PUT", "PATCH"} and not (length and length.isdigit()):
127
+ # Transfer-Encoding: chunked has no Content-Length. Consume only
128
+ # up to the limit, then let Starlette replay the cached body to
129
+ # the endpoint. This closes the header-bypass without buffering
130
+ # an unbounded request.
131
+ chunks = []
132
+ size = 0
133
+ async for chunk in request.stream():
134
+ size += len(chunk)
135
+ if size > _MAX_BODY_BYTES:
136
+ return self._body_too_large()
137
+ chunks.append(chunk)
138
+ request._body = b"".join(chunks)
137
139
  return await call_next(request)
138
140
 
139
141
  if self.cors_origins:
@@ -165,6 +167,8 @@ class NachoOrchestrator:
165
167
  "apps": len(self.manager.apps),
166
168
  "read_only": self.read_only,
167
169
  "auth_required": self.auth is not None,
170
+ "generation": self.manager.generation,
171
+ "load_errors": len(self.manager.store.load_errors),
168
172
  }
169
173
 
170
174
  @self.app.get("/ui", include_in_schema=False)
@@ -273,11 +277,12 @@ class NachoOrchestrator:
273
277
  @self.app.get("/api/apps/{app_name}/config")
274
278
  def get_config(app_name: str, request: Request, response: Response) -> Any:
275
279
  app = self._get_app(app_name)
276
- not_modified = self._not_modified(request, app)
280
+ snapshot = app.snapshot()
281
+ not_modified = self._not_modified(request, snapshot["revision"])
277
282
  if not_modified is not None:
278
283
  return not_modified
279
- self._set_revision_headers(response, app)
280
- return app.config.get_all()
284
+ self._set_revision_headers(response, snapshot["revision"])
285
+ return snapshot["config"]
281
286
 
282
287
  @self.app.put("/api/apps/{app_name}/config")
283
288
  def replace_config(
@@ -308,8 +313,7 @@ class NachoOrchestrator:
308
313
 
309
314
  @self.app.get("/api/apps/{app_name}/schema")
310
315
  def get_schema(app_name: str) -> Dict[str, Any]:
311
- app = self._get_app(app_name)
312
- return {"data": app.schema}
316
+ return {"data": self._get_app(app_name).snapshot()["schema"]}
313
317
 
314
318
  @self.app.put("/api/apps/{app_name}/schema")
315
319
  def replace_schema(
@@ -337,15 +341,16 @@ class NachoOrchestrator:
337
341
  @self.app.get("/api/apps/{app_name}/config/{path:path}")
338
342
  def get_path(app_name: str, path: str, request: Request, response: Response) -> Any:
339
343
  app = self._get_app(app_name)
340
- not_modified = self._not_modified(request, app)
344
+ snapshot = app.snapshot()
345
+ not_modified = self._not_modified(request, snapshot["revision"])
341
346
  if not_modified is not None:
342
347
  return not_modified
343
- self._set_revision_headers(response, app)
348
+ self._set_revision_headers(response, snapshot["revision"])
344
349
  # Resolve against the snapshot directly: Nacho.get() deep-copies its
345
350
  # result, so an identity-sentinel passed to it would never compare
346
351
  # equal — get_nested_value preserves the sentinel by identity.
347
352
  missing = object()
348
- value = get_nested_value(app.config.get_all(), path, missing)
353
+ value = get_nested_value(snapshot["config"], path, missing)
349
354
  if value is missing:
350
355
  raise HTTPException(
351
356
  status_code=status.HTTP_404_NOT_FOUND,
@@ -487,14 +492,7 @@ class NachoOrchestrator:
487
492
 
488
493
  await app.hub.connect(websocket)
489
494
  try:
490
- await websocket.send_json(
491
- {
492
- "type": "initial_config",
493
- "app": app.name,
494
- "revision": app.revision,
495
- "data": app.config.get_all(),
496
- }
497
- )
495
+ await websocket.send_json(app.event_payload("initial_config"))
498
496
  while True:
499
497
  # receive() (not receive_text) so a binary frame is
500
498
  # ignored instead of killing the connection.
@@ -557,6 +555,12 @@ class NachoOrchestrator:
557
555
  def _allow_cors_credentials(self) -> bool:
558
556
  return "*" not in self.cors_origins
559
557
 
558
+ def _body_too_large(self) -> JSONResponse:
559
+ return JSONResponse(
560
+ status_code=413,
561
+ content={"detail": f"Request body exceeds {_MAX_BODY_BYTES // (1024 * 1024)} MiB"},
562
+ )
563
+
560
564
  def _get_app(self, name: str) -> ConfigApp:
561
565
  app = self.manager.get(name)
562
566
  if app is None:
@@ -579,12 +583,13 @@ class NachoOrchestrator:
579
583
  },
580
584
  )
581
585
 
582
- def _set_revision_headers(self, response: Response, app: ConfigApp) -> None:
583
- revision = str(app.revision)
584
- response.headers["ETag"] = f'"{revision}"'
586
+ def _set_revision_headers(self, response: Response, revision_value: int) -> None:
587
+ revision = str(revision_value)
588
+ response.headers["ETag"] = f'"{self.manager.generation}:{revision}"'
585
589
  response.headers["X-Nacho-Revision"] = revision
590
+ response.headers["X-Nacho-Generation"] = self.manager.generation
586
591
 
587
- def _not_modified(self, request: Request, app: ConfigApp) -> Optional[Response]:
592
+ def _not_modified(self, request: Request, revision: int) -> Optional[Response]:
588
593
  """304 response when If-None-Match already names the current revision.
589
594
 
590
595
  Lets pollers re-check cheaply: the config body is only sent when the
@@ -595,10 +600,11 @@ class NachoOrchestrator:
595
600
  return None
596
601
  tags = {tag.strip() for tag in header.split(",")}
597
602
  tags |= {tag[2:] for tag in tags if tag.startswith("W/")}
598
- if "*" not in tags and f'"{app.revision}"' not in tags:
603
+ current = f'"{self.manager.generation}:{revision}"'
604
+ if "*" not in tags and current not in tags:
599
605
  return None
600
606
  response = Response(status_code=status.HTTP_304_NOT_MODIFIED)
601
- self._set_revision_headers(response, app)
607
+ self._set_revision_headers(response, revision)
602
608
  return response
603
609
 
604
610
  def _check_writable(self) -> None:
nacho/server/auth.py CHANGED
@@ -20,11 +20,6 @@ _SESSION_COOKIE = "NACHO_api_key"
20
20
  _DEFAULT_PUBLIC_PATHS = ("/", "/health", "/favicon.ico", "/ui", "/docs", "/redoc", "/openapi.json")
21
21
 
22
22
 
23
- # Access roles granted by a matching key.
24
- ROLE_ADMIN = "admin" # full read/write access
25
- ROLE_READ = "read" # safe HTTP methods and WebSocket subscriptions only
26
-
27
-
28
23
  def validate_api_key(name: str, value: Any) -> Optional[str]:
29
24
  """Return *value* if it is a usable API key, raising TypeError otherwise.
30
25
 
@@ -41,100 +36,67 @@ def validate_api_key(name: str, value: Any) -> Optional[str]:
41
36
 
42
37
 
43
38
  class AuthGuard:
44
- """Verifies API keys from headers, cookies, and WebSocket handshakes.
39
+ """Verifies the API key from headers, cookies, and WebSocket handshakes.
45
40
 
46
- Two keys can be configured: *api_key* grants full access, and the
47
- optional *read_only_api_key* grants read access only — the middleware
48
- rejects unsafe methods presented with it. Handing dashboards and
49
- pollers the read-only key keeps write credentials out of them.
41
+ One key grants access, and access is all-or-nothing. There are no roles:
42
+ a client that wants to hold itself to reads constructs its ``Nacho``
43
+ instance with ``read_only=True``, and a deployment that must refuse every
44
+ write runs the server with ``--read-only``.
50
45
  """
51
46
 
52
- def __init__(
53
- self,
54
- api_key: Optional[str] = None,
55
- read_only_api_key: Optional[str] = None,
56
- ) -> None:
47
+ def __init__(self, api_key: Optional[str] = None) -> None:
57
48
  self.api_key = validate_api_key("api_key", api_key)
58
- self.read_only_api_key = validate_api_key("read_only_api_key", read_only_api_key)
59
49
 
60
50
  @property
61
51
  def enabled(self) -> bool:
62
- return bool(self.api_key or self.read_only_api_key)
52
+ return bool(self.api_key)
63
53
 
64
54
  @staticmethod
65
55
  def _matches(token: str, key: str) -> bool:
66
56
  # Compare as bytes: compare_digest raises TypeError on non-ASCII str input.
67
57
  return hmac.compare_digest(token.encode("utf-8"), key.encode("utf-8"))
68
58
 
69
- def role_for_token(self, token: Optional[str]) -> Optional[str]:
70
- """Return the role *token* grants: ROLE_ADMIN, ROLE_READ, or None."""
59
+ def verify_token(self, token: Optional[str]) -> bool:
60
+ """True when *token* carries the API key (with or without "Bearer ")."""
71
61
  if not self.enabled:
72
- return ROLE_ADMIN
62
+ return True
73
63
  if not token:
74
- return None
64
+ return False
75
65
  token = token.strip()
76
66
  if token.startswith(_AUTH_PREFIX):
77
67
  token = token[len(_AUTH_PREFIX) :]
78
68
  if not token:
79
- return None
80
- if self.api_key and self._matches(token, self.api_key):
81
- return ROLE_ADMIN
82
- if self.read_only_api_key and self._matches(token, self.read_only_api_key):
83
- return ROLE_READ
84
- return None
69
+ return False
70
+ return self._matches(token, self.api_key)
85
71
 
86
- def role_for_cookie(self, raw: Optional[str]) -> Optional[str]:
87
- """Role granted by the session cookie, which the UI writes URL-encoded.
72
+ def verify_cookie(self, raw: Optional[str]) -> bool:
73
+ """Verify the session cookie, which the UI writes URL-encoded.
88
74
 
89
75
  The raw form is also accepted so a cookie written before encoding
90
76
  was introduced keeps working until it is rewritten.
91
77
  """
92
78
  if not raw:
93
- return None
94
- role = self.role_for_token(raw)
95
- if role is not None:
96
- return role
79
+ return False
80
+ if self.verify_token(raw):
81
+ return True
97
82
  decoded = unquote(raw)
98
- if decoded != raw:
99
- return self.role_for_token(decoded)
100
- return None
101
-
102
- def role_for_request(self, request: Request) -> Optional[str]:
103
- """Best role granted by the session cookie or Authorization header."""
104
- roles = {
105
- self.role_for_cookie(request.cookies.get(_SESSION_COOKIE)),
106
- self.role_for_token(request.headers.get("Authorization")),
107
- }
108
- if ROLE_ADMIN in roles:
109
- return ROLE_ADMIN
110
- if ROLE_READ in roles:
111
- return ROLE_READ
112
- return None
113
-
114
- # -- boolean convenience wrappers ----------------------------------
115
-
116
- def verify_token(self, token: Optional[str]) -> bool:
117
- """True when *token* grants full access."""
118
- return self.role_for_token(token) == ROLE_ADMIN
119
-
120
- def verify_cookie(self, raw: Optional[str]) -> bool:
121
- """True when the cookie grants any access."""
122
- return self.role_for_cookie(raw) is not None
83
+ return decoded != raw and self.verify_token(decoded)
123
84
 
124
85
  def verify_request(self, request: Request) -> bool:
125
- """True when the request carries any valid credential (read or admin)."""
126
- return self.role_for_request(request) is not None
86
+ """True when the session cookie or Authorization header carries the key."""
87
+ if not self.enabled:
88
+ return True
89
+ return self.verify_cookie(request.cookies.get(_SESSION_COOKIE)) or self.verify_token(
90
+ request.headers.get("Authorization")
91
+ )
127
92
 
128
93
  def verify_websocket(self, websocket: WebSocket) -> bool:
129
- """Verify WebSocket auth from cookie or Authorization header.
130
-
131
- Subscriptions are read-only by nature, so either key is accepted.
132
- """
94
+ """Verify WebSocket auth from cookie or Authorization header."""
133
95
  if not self.enabled:
134
96
  return True
135
- if self.role_for_cookie(websocket.cookies.get(_SESSION_COOKIE)) is not None:
97
+ if self.verify_cookie(websocket.cookies.get(_SESSION_COOKIE)):
136
98
  return True
137
- return self.role_for_token(websocket.headers.get("Authorization")) is not None
99
+ return self.verify_token(websocket.headers.get("Authorization"))
138
100
 
139
101
 
140
102
  class AuthMiddleware(BaseHTTPMiddleware):
@@ -152,23 +114,14 @@ class AuthMiddleware(BaseHTTPMiddleware):
152
114
  self.logger = logger or LOGGER
153
115
  self.public_paths = tuple(public_paths)
154
116
 
155
- _SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
156
-
157
117
  async def dispatch(self, request: Request, call_next):
158
118
  if request.method == "OPTIONS" or self._is_public(request.url.path):
159
119
  return await call_next(request)
160
- role = self.auth.role_for_request(request)
161
- if role == ROLE_ADMIN or (role == ROLE_READ and request.method in self._SAFE_METHODS):
120
+ if self.auth.verify_request(request):
162
121
  return await call_next(request)
163
122
 
164
123
  # Same {"detail": ...} envelope FastAPI uses for HTTPException, so
165
124
  # clients only ever parse one error shape.
166
- if role == ROLE_READ:
167
- self.logger.debug("Rejected read-only-key write to %s", request.url.path)
168
- return JSONResponse(
169
- status_code=403,
170
- content={"detail": "Forbidden: this API key grants read-only access"},
171
- )
172
125
  self.logger.debug("Rejected unauthenticated request to %s", request.url.path)
173
126
  return JSONResponse(
174
127
  status_code=401,