nacho-python 0.1.0__tar.gz → 1.0.0__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 (35) hide show
  1. {nacho_python-0.1.0/nacho_python.egg-info → nacho_python-1.0.0}/PKG-INFO +63 -10
  2. {nacho_python-0.1.0 → nacho_python-1.0.0}/README.md +61 -9
  3. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho/__init__.py +1 -10
  4. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho/_version.py +1 -1
  5. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho/cli/main.py +7 -12
  6. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho/client.py +17 -4
  7. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho/config.py +7 -0
  8. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho/schema.py +6 -0
  9. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho/server/app.py +46 -35
  10. nacho_python-1.0.0/nacho/server/auth.py +136 -0
  11. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho/server/runtime.py +194 -55
  12. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho/server/ui/index.html +1173 -227
  13. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho/storage/__init__.py +6 -4
  14. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho/storage/remote.py +51 -1
  15. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho/utils/io.py +2 -2
  16. {nacho_python-0.1.0 → nacho_python-1.0.0/nacho_python.egg-info}/PKG-INFO +63 -10
  17. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho_python.egg-info/SOURCES.txt +0 -22
  18. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho_python.egg-info/requires.txt +1 -0
  19. {nacho_python-0.1.0 → nacho_python-1.0.0}/pyproject.toml +3 -3
  20. nacho_python-0.1.0/nacho/server/auth.py +0 -168
  21. {nacho_python-0.1.0 → nacho_python-1.0.0}/LICENSE +0 -0
  22. {nacho_python-0.1.0 → nacho_python-1.0.0}/MANIFEST.in +0 -0
  23. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho/cli/__init__.py +0 -0
  24. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho/env.py +0 -0
  25. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho/event.py +0 -0
  26. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho/server/__init__.py +0 -0
  27. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho/server/models.py +0 -0
  28. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho/storage/base.py +0 -0
  29. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho/storage/file.py +0 -0
  30. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho/utils/__init__.py +0 -0
  31. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho/utils/path.py +0 -0
  32. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho_python.egg-info/dependency_links.txt +0 -0
  33. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho_python.egg-info/entry_points.txt +0 -0
  34. {nacho_python-0.1.0 → nacho_python-1.0.0}/nacho_python.egg-info/top_level.txt +0 -0
  35. {nacho_python-0.1.0 → nacho_python-1.0.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nacho-python
3
- Version: 0.1.0
3
+ Version: 1.0.0
4
4
  Summary: Nacho - Lightweight, schema-first dynamic configuration service
5
5
  Author-email: "Nya Foundation Team (k3scat)" <k3scat@github.com>
6
6
  License-Expression: MIT
@@ -22,6 +22,7 @@ Requires-Dist: tomli>=2.0.0; python_version < "3.11"
22
22
  Requires-Dist: tomli-w>=1.0.0
23
23
  Provides-Extra: server
24
24
  Requires-Dist: fastapi>=0.100.0; extra == "server"
25
+ Requires-Dist: pydantic>=2.0.0; extra == "server"
25
26
  Requires-Dist: uvicorn>=0.22.0; extra == "server"
26
27
  Requires-Dist: websockets>=10.0; extra == "server"
27
28
  Provides-Extra: remote
@@ -198,7 +199,6 @@ missed live updates.
198
199
  | `--app-name` | `default` | App name for the `--config` file |
199
200
  | `--data-dir` | none | Directory for API-created app state and history |
200
201
  | `--api-key` | none | Enable bearer-token authentication |
201
- | `--read-only-api-key` | none | Additional key granting read access only |
202
202
  | `--history-limit` | `50` | Revision snapshots kept per app (`0` disables history) |
203
203
  | `--read-only` | off | Reject every write |
204
204
  | `--reload` | off | Auto-reload for development |
@@ -246,6 +246,43 @@ When the server runs with `--api-key`, the UI prompts for the key on first
246
246
  load. The `/ui` page itself is public so the sign-in screen can load; every
247
247
  API call behind it requires authentication.
248
248
 
249
+ #### Pre-authenticating an embedded UI
250
+
251
+ When the orchestrator is mounted inside a host application that already has
252
+ its own session auth, users should not face a second login. The UI reads its
253
+ credential from two same-origin browser stores, and **these two names are a
254
+ stable contract** — seed them before navigating to `/ui` and the UI comes up
255
+ already signed in:
256
+
257
+ | Store | Name | Used for |
258
+ |---|---|---|
259
+ | `localStorage` | `nacho_api_key` | `Authorization: Bearer` header on REST calls |
260
+ | Cookie | `NACHO_api_key` | The WebSocket handshake, which cannot send headers |
261
+
262
+ The cookie value must be URL-encoded, and its path must match the mount
263
+ point — the UI derives it as `location.pathname` with a trailing `/ui`
264
+ removed (so `/config/ui` yields a cookie path of `/config`, and a top-level
265
+ mount yields `/`):
266
+
267
+ ```js
268
+ // Run on your own login page, same origin as the mounted UI.
269
+ function preauthenticateNacho(key, mountPath = "") {
270
+ localStorage.setItem("nacho_api_key", key);
271
+ const secure = location.protocol === "https:" ? "; Secure" : "";
272
+ document.cookie =
273
+ "NACHO_api_key=" + encodeURIComponent(key) +
274
+ "; path=" + (mountPath || "/") + "; SameSite=Strict" + secure;
275
+ }
276
+ ```
277
+
278
+ Seed the key only for users your own application has already authorised to
279
+ manage configuration. The key grants full access, so a host application that
280
+ wants some users to look without touching must enforce that itself — by not
281
+ seeding the key, or by mounting the UI only for the users it trusts.
282
+
283
+ Do not pass the key in the URL (`?token=`): query strings leak through
284
+ browser history, `Referer` headers, and proxy logs.
285
+
249
286
  ### Authentication
250
287
 
251
288
  Passing `--api-key` (or `api_key=` to `NachoOrchestrator`) enables bearer
@@ -254,11 +291,14 @@ authentication for the whole API. Clients send the key either as an
254
291
  its own WebSocket handshake. Requests with a missing or wrong key receive
255
292
  `401 Unauthorized`. The comparison is timing-safe.
256
293
 
257
- A second key can be added with `--read-only-api-key` (or
258
- `read_only_api_key=`). It authenticates GETs and WebSocket subscriptions but
259
- receives `403 Forbidden` on any write — hand it to dashboards, pollers, and
260
- services that only consume configuration, so the write credential never
261
- leaves the operators who need it.
294
+ There is one key and access is all-or-nothing — no roles, no second key.
295
+ Two separate controls cover the read-only cases:
296
+
297
+ - A **client** that should never write constructs its instance with
298
+ `read_only=True`; every mutating call then raises `PermissionError`
299
+ locally, without a round trip.
300
+ - A **server** that should refuse every write runs with `--read-only`, which
301
+ answers `403 Forbidden` to any mutation regardless of the caller.
262
302
 
263
303
  `/`, `/health`, `/ui`, `/docs`, `/redoc`, and `/openapi.json` stay public: the
264
304
  API surface is not a secret, only the data behind it.
@@ -298,7 +338,8 @@ is how the CLI and UI submit YAML and TOML:
298
338
 
299
339
  Every app carries a monotonically increasing revision, bumped on each
300
340
  successful write. Reads of `/config` (full or per-path) return the current
301
- revision in the `ETag` and `X-Nacho-Revision` response headers. Writes may
341
+ revision in `X-Nacho-Revision`; `X-Nacho-Generation` identifies the current
342
+ server process, and `ETag` combines both values. Writes may
302
343
  include a `revision` field stating the revision the client last saw; if the
303
344
  server has moved on, the write fails with `409 Conflict` and the stored
304
345
  configuration is left untouched:
@@ -316,7 +357,8 @@ The `ETag` also enables cheap polling: send it back as `If-None-Match` and
316
357
  the server answers `304 Not Modified` — no body — until the revision moves.
317
358
 
318
359
  ```bash
319
- curl -H 'If-None-Match: "3"' http://127.0.0.1:8000/api/apps/my-service/config
360
+ curl -H 'If-None-Match: "<generation>:3"' \
361
+ http://127.0.0.1:8000/api/apps/my-service/config
320
362
  ```
321
363
 
322
364
  ### History and rollback
@@ -391,7 +433,9 @@ Real-time:
391
433
 
392
434
  The WebSocket is receive-only: the server sends an `initial_config` message
393
435
  on subscribe followed by an `update` message per change, each carrying the
394
- app name, revision, and full configuration. Writes always go through REST, so
436
+ server generation, app name, revision, full configuration, schema, and current
437
+ metadata. The generation lets clients recover safely when an ephemeral server
438
+ restarts its revision counter. Writes always go through REST, so
395
439
  there is never ambiguity about who owns the state.
396
440
 
397
441
  ## Remote clients
@@ -464,6 +508,9 @@ the counter resets on every successful connection. Keepalive pings detect
464
508
  half-open connections, and permanent failures (bad key, deleted app) stop
465
509
  the retry loop with a clear log line instead of retrying forever. Stale or
466
510
  out-of-order pushes are dropped, so the local snapshot never rolls backwards.
511
+ Applications can expose `storage.watching`, `storage.last_watch_error`, and
512
+ `storage.generation` in their own health checks instead of relying on logs to
513
+ detect a stale subscription.
467
514
 
468
515
  The CLI covers the same ground without the SDK — see
469
516
  [Command-line interface](#command-line-interface).
@@ -774,6 +821,10 @@ Or with Compose:
774
821
  docker compose up --build
775
822
  ```
776
823
 
824
+ Compose binds to loopback by default and persists server state in the
825
+ `nacho-data` volume. Add `--api-key` before exposing the port beyond the local
826
+ machine.
827
+
777
828
  The image entrypoint is `nacho`; the default command is
778
829
  `server --host 0.0.0.0 --config config.yaml`. Append any `nacho server` flags
779
830
  to override the defaults. The container exposes port `8000`.
@@ -792,6 +843,8 @@ to override the defaults. The container exposes port `8000`.
792
843
  - Editing a `--config` file by hand while the server is running is not
793
844
  detected; the server's next write wins. Make changes through the API, CLI,
794
845
  or UI.
846
+ - Newly created server state and history directories use mode `0700`, and
847
+ their JSON files use mode `0600`. Existing permissions are preserved.
795
848
 
796
849
  ## Development
797
850
 
@@ -151,7 +151,6 @@ missed live updates.
151
151
  | `--app-name` | `default` | App name for the `--config` file |
152
152
  | `--data-dir` | none | Directory for API-created app state and history |
153
153
  | `--api-key` | none | Enable bearer-token authentication |
154
- | `--read-only-api-key` | none | Additional key granting read access only |
155
154
  | `--history-limit` | `50` | Revision snapshots kept per app (`0` disables history) |
156
155
  | `--read-only` | off | Reject every write |
157
156
  | `--reload` | off | Auto-reload for development |
@@ -199,6 +198,43 @@ When the server runs with `--api-key`, the UI prompts for the key on first
199
198
  load. The `/ui` page itself is public so the sign-in screen can load; every
200
199
  API call behind it requires authentication.
201
200
 
201
+ #### Pre-authenticating an embedded UI
202
+
203
+ When the orchestrator is mounted inside a host application that already has
204
+ its own session auth, users should not face a second login. The UI reads its
205
+ credential from two same-origin browser stores, and **these two names are a
206
+ stable contract** — seed them before navigating to `/ui` and the UI comes up
207
+ already signed in:
208
+
209
+ | Store | Name | Used for |
210
+ |---|---|---|
211
+ | `localStorage` | `nacho_api_key` | `Authorization: Bearer` header on REST calls |
212
+ | Cookie | `NACHO_api_key` | The WebSocket handshake, which cannot send headers |
213
+
214
+ The cookie value must be URL-encoded, and its path must match the mount
215
+ point — the UI derives it as `location.pathname` with a trailing `/ui`
216
+ removed (so `/config/ui` yields a cookie path of `/config`, and a top-level
217
+ mount yields `/`):
218
+
219
+ ```js
220
+ // Run on your own login page, same origin as the mounted UI.
221
+ function preauthenticateNacho(key, mountPath = "") {
222
+ localStorage.setItem("nacho_api_key", key);
223
+ const secure = location.protocol === "https:" ? "; Secure" : "";
224
+ document.cookie =
225
+ "NACHO_api_key=" + encodeURIComponent(key) +
226
+ "; path=" + (mountPath || "/") + "; SameSite=Strict" + secure;
227
+ }
228
+ ```
229
+
230
+ Seed the key only for users your own application has already authorised to
231
+ manage configuration. The key grants full access, so a host application that
232
+ wants some users to look without touching must enforce that itself — by not
233
+ seeding the key, or by mounting the UI only for the users it trusts.
234
+
235
+ Do not pass the key in the URL (`?token=`): query strings leak through
236
+ browser history, `Referer` headers, and proxy logs.
237
+
202
238
  ### Authentication
203
239
 
204
240
  Passing `--api-key` (or `api_key=` to `NachoOrchestrator`) enables bearer
@@ -207,11 +243,14 @@ authentication for the whole API. Clients send the key either as an
207
243
  its own WebSocket handshake. Requests with a missing or wrong key receive
208
244
  `401 Unauthorized`. The comparison is timing-safe.
209
245
 
210
- A second key can be added with `--read-only-api-key` (or
211
- `read_only_api_key=`). It authenticates GETs and WebSocket subscriptions but
212
- receives `403 Forbidden` on any write — hand it to dashboards, pollers, and
213
- services that only consume configuration, so the write credential never
214
- leaves the operators who need it.
246
+ There is one key and access is all-or-nothing — no roles, no second key.
247
+ Two separate controls cover the read-only cases:
248
+
249
+ - A **client** that should never write constructs its instance with
250
+ `read_only=True`; every mutating call then raises `PermissionError`
251
+ locally, without a round trip.
252
+ - A **server** that should refuse every write runs with `--read-only`, which
253
+ answers `403 Forbidden` to any mutation regardless of the caller.
215
254
 
216
255
  `/`, `/health`, `/ui`, `/docs`, `/redoc`, and `/openapi.json` stay public: the
217
256
  API surface is not a secret, only the data behind it.
@@ -251,7 +290,8 @@ is how the CLI and UI submit YAML and TOML:
251
290
 
252
291
  Every app carries a monotonically increasing revision, bumped on each
253
292
  successful write. Reads of `/config` (full or per-path) return the current
254
- revision in the `ETag` and `X-Nacho-Revision` response headers. Writes may
293
+ revision in `X-Nacho-Revision`; `X-Nacho-Generation` identifies the current
294
+ server process, and `ETag` combines both values. Writes may
255
295
  include a `revision` field stating the revision the client last saw; if the
256
296
  server has moved on, the write fails with `409 Conflict` and the stored
257
297
  configuration is left untouched:
@@ -269,7 +309,8 @@ The `ETag` also enables cheap polling: send it back as `If-None-Match` and
269
309
  the server answers `304 Not Modified` — no body — until the revision moves.
270
310
 
271
311
  ```bash
272
- curl -H 'If-None-Match: "3"' http://127.0.0.1:8000/api/apps/my-service/config
312
+ curl -H 'If-None-Match: "<generation>:3"' \
313
+ http://127.0.0.1:8000/api/apps/my-service/config
273
314
  ```
274
315
 
275
316
  ### History and rollback
@@ -344,7 +385,9 @@ Real-time:
344
385
 
345
386
  The WebSocket is receive-only: the server sends an `initial_config` message
346
387
  on subscribe followed by an `update` message per change, each carrying the
347
- app name, revision, and full configuration. Writes always go through REST, so
388
+ server generation, app name, revision, full configuration, schema, and current
389
+ metadata. The generation lets clients recover safely when an ephemeral server
390
+ restarts its revision counter. Writes always go through REST, so
348
391
  there is never ambiguity about who owns the state.
349
392
 
350
393
  ## Remote clients
@@ -417,6 +460,9 @@ the counter resets on every successful connection. Keepalive pings detect
417
460
  half-open connections, and permanent failures (bad key, deleted app) stop
418
461
  the retry loop with a clear log line instead of retrying forever. Stale or
419
462
  out-of-order pushes are dropped, so the local snapshot never rolls backwards.
463
+ Applications can expose `storage.watching`, `storage.last_watch_error`, and
464
+ `storage.generation` in their own health checks instead of relying on logs to
465
+ detect a stale subscription.
420
466
 
421
467
  The CLI covers the same ground without the SDK — see
422
468
  [Command-line interface](#command-line-interface).
@@ -727,6 +773,10 @@ Or with Compose:
727
773
  docker compose up --build
728
774
  ```
729
775
 
776
+ Compose binds to loopback by default and persists server state in the
777
+ `nacho-data` volume. Add `--api-key` before exposing the port beyond the local
778
+ machine.
779
+
730
780
  The image entrypoint is `nacho`; the default command is
731
781
  `server --host 0.0.0.0 --config config.yaml`. Append any `nacho server` flags
732
782
  to override the defaults. The container exposes port `8000`.
@@ -745,6 +795,8 @@ to override the defaults. The container exposes port `8000`.
745
795
  - Editing a `--config` file by hand while the server is running is not
746
796
  detected; the server's next write wins. Make changes through the API, CLI,
747
797
  or UI.
798
+ - Newly created server state and history directories use mode `0700`, and
799
+ their JSON files use mode `0600`. Existing permissions are preserved.
748
800
 
749
801
  ## Development
750
802
 
@@ -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")
@@ -1,3 +1,3 @@
1
1
  """Version information for Nacho."""
2
2
 
3
- __version__ = "0.1.0"
3
+ __version__ = "1.0.0"
@@ -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,
@@ -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
@@ -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
  # ------------------------------------------------------------------
@@ -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
  # ------------------------------------------------------------------
@@ -24,7 +24,7 @@ from fastapi.responses import FileResponse, JSONResponse
24
24
  from nacho._version import __version__
25
25
  from nacho.config import Nacho
26
26
  from nacho.schema import ValidationError
27
- from nacho.server.auth import AuthGuard, AuthMiddleware
27
+ from nacho.server.auth import AuthGuard, AuthMiddleware, validate_api_key
28
28
  from nacho.utils.io import dump_string, load_string
29
29
  from nacho.utils.path import get_nested_value
30
30
 
@@ -67,18 +67,17 @@ 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
74
73
  # clients are not browsers, so cross-origin access is opt-in.
75
74
  self.cors_origins = list(cors_origins) if cors_origins is not None else []
76
75
  self.logger = logger or LOGGER
77
- self.auth = (
78
- AuthGuard(api_key=api_key, read_only_api_key=read_only_api_key)
79
- if (api_key or read_only_api_key)
80
- else None
81
- )
76
+ # Validate before the truthiness check below: a falsy non-str key
77
+ # (e.g. an empty list from a caller's own config) would otherwise
78
+ # skip AuthGuard entirely and leave the server unauthenticated.
79
+ api_key = validate_api_key("api_key", api_key)
80
+ self.auth = AuthGuard(api_key=api_key) if api_key else None
82
81
  self.manager = AppManager(
83
82
  data_dir=Path(data_dir) if data_dir else None,
84
83
  logger=self.logger,
@@ -123,12 +122,20 @@ class NachoOrchestrator:
123
122
  async def cap_body_size(request: Request, call_next):
124
123
  length = request.headers.get("content-length")
125
124
  if length and length.isdigit() and int(length) > _MAX_BODY_BYTES:
126
- return JSONResponse(
127
- status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
128
- content={
129
- "detail": f"Request body exceeds {_MAX_BODY_BYTES // (1024 * 1024)} MiB"
130
- },
131
- )
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)
132
139
  return await call_next(request)
133
140
 
134
141
  if self.cors_origins:
@@ -160,6 +167,8 @@ class NachoOrchestrator:
160
167
  "apps": len(self.manager.apps),
161
168
  "read_only": self.read_only,
162
169
  "auth_required": self.auth is not None,
170
+ "generation": self.manager.generation,
171
+ "load_errors": len(self.manager.store.load_errors),
163
172
  }
164
173
 
165
174
  @self.app.get("/ui", include_in_schema=False)
@@ -268,11 +277,12 @@ class NachoOrchestrator:
268
277
  @self.app.get("/api/apps/{app_name}/config")
269
278
  def get_config(app_name: str, request: Request, response: Response) -> Any:
270
279
  app = self._get_app(app_name)
271
- not_modified = self._not_modified(request, app)
280
+ snapshot = app.snapshot()
281
+ not_modified = self._not_modified(request, snapshot["revision"])
272
282
  if not_modified is not None:
273
283
  return not_modified
274
- self._set_revision_headers(response, app)
275
- return app.config.get_all()
284
+ self._set_revision_headers(response, snapshot["revision"])
285
+ return snapshot["config"]
276
286
 
277
287
  @self.app.put("/api/apps/{app_name}/config")
278
288
  def replace_config(
@@ -303,8 +313,7 @@ class NachoOrchestrator:
303
313
 
304
314
  @self.app.get("/api/apps/{app_name}/schema")
305
315
  def get_schema(app_name: str) -> Dict[str, Any]:
306
- app = self._get_app(app_name)
307
- return {"data": app.schema}
316
+ return {"data": self._get_app(app_name).snapshot()["schema"]}
308
317
 
309
318
  @self.app.put("/api/apps/{app_name}/schema")
310
319
  def replace_schema(
@@ -332,15 +341,16 @@ class NachoOrchestrator:
332
341
  @self.app.get("/api/apps/{app_name}/config/{path:path}")
333
342
  def get_path(app_name: str, path: str, request: Request, response: Response) -> Any:
334
343
  app = self._get_app(app_name)
335
- not_modified = self._not_modified(request, app)
344
+ snapshot = app.snapshot()
345
+ not_modified = self._not_modified(request, snapshot["revision"])
336
346
  if not_modified is not None:
337
347
  return not_modified
338
- self._set_revision_headers(response, app)
348
+ self._set_revision_headers(response, snapshot["revision"])
339
349
  # Resolve against the snapshot directly: Nacho.get() deep-copies its
340
350
  # result, so an identity-sentinel passed to it would never compare
341
351
  # equal — get_nested_value preserves the sentinel by identity.
342
352
  missing = object()
343
- value = get_nested_value(app.config.get_all(), path, missing)
353
+ value = get_nested_value(snapshot["config"], path, missing)
344
354
  if value is missing:
345
355
  raise HTTPException(
346
356
  status_code=status.HTTP_404_NOT_FOUND,
@@ -482,14 +492,7 @@ class NachoOrchestrator:
482
492
 
483
493
  await app.hub.connect(websocket)
484
494
  try:
485
- await websocket.send_json(
486
- {
487
- "type": "initial_config",
488
- "app": app.name,
489
- "revision": app.revision,
490
- "data": app.config.get_all(),
491
- }
492
- )
495
+ await websocket.send_json(app.event_payload("initial_config"))
493
496
  while True:
494
497
  # receive() (not receive_text) so a binary frame is
495
498
  # ignored instead of killing the connection.
@@ -552,6 +555,12 @@ class NachoOrchestrator:
552
555
  def _allow_cors_credentials(self) -> bool:
553
556
  return "*" not in self.cors_origins
554
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
+
555
564
  def _get_app(self, name: str) -> ConfigApp:
556
565
  app = self.manager.get(name)
557
566
  if app is None:
@@ -574,12 +583,13 @@ class NachoOrchestrator:
574
583
  },
575
584
  )
576
585
 
577
- def _set_revision_headers(self, response: Response, app: ConfigApp) -> None:
578
- revision = str(app.revision)
579
- 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}"'
580
589
  response.headers["X-Nacho-Revision"] = revision
590
+ response.headers["X-Nacho-Generation"] = self.manager.generation
581
591
 
582
- def _not_modified(self, request: Request, app: ConfigApp) -> Optional[Response]:
592
+ def _not_modified(self, request: Request, revision: int) -> Optional[Response]:
583
593
  """304 response when If-None-Match already names the current revision.
584
594
 
585
595
  Lets pollers re-check cheaply: the config body is only sent when the
@@ -590,10 +600,11 @@ class NachoOrchestrator:
590
600
  return None
591
601
  tags = {tag.strip() for tag in header.split(",")}
592
602
  tags |= {tag[2:] for tag in tags if tag.startswith("W/")}
593
- 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:
594
605
  return None
595
606
  response = Response(status_code=status.HTTP_304_NOT_MODIFIED)
596
- self._set_revision_headers(response, app)
607
+ self._set_revision_headers(response, revision)
597
608
  return response
598
609
 
599
610
  def _check_writable(self) -> None: