nacho-python 0.0.1__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/server/app.py ADDED
@@ -0,0 +1,515 @@
1
+ """API-first Nacho configuration server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ from contextlib import asynccontextmanager
8
+ from pathlib import Path
9
+ from typing import Any, Dict, List, Optional, Union
10
+
11
+ import uvicorn
12
+ from fastapi import FastAPI, Header, HTTPException, Response, WebSocket, WebSocketDisconnect, status
13
+ from fastapi.middleware.cors import CORSMiddleware
14
+ from fastapi.responses import FileResponse
15
+
16
+ from nacho._version import __version__
17
+ from nacho.config import Nacho
18
+ from nacho.schema import ValidationError
19
+ from nacho.server.auth import AuthGuard, AuthMiddleware
20
+ from nacho.utils.io import dump_string, load_string
21
+
22
+ from .models import (
23
+ AppCreateRequest,
24
+ AppMetadataRequest,
25
+ ConfigRequest,
26
+ ConvertRequest,
27
+ PathUpdateRequest,
28
+ SchemaUpdateRequest,
29
+ )
30
+ from .runtime import AppManager, ConfigApp, RevisionConflictError
31
+
32
+ LOGGER = logging.getLogger(__name__)
33
+
34
+ _UI_INDEX = Path(__file__).parent / "ui" / "index.html"
35
+
36
+
37
+ class InvalidConfigDataError(ValueError):
38
+ """Raised when a request body cannot be parsed as config data."""
39
+
40
+
41
+ class NachoOrchestrator:
42
+ """Small FastAPI wrapper around one or more :class:`Nacho` instances."""
43
+
44
+ def __init__(
45
+ self,
46
+ apps: Union[Dict[str, Nacho], Nacho, None] = None,
47
+ api_key: Optional[str] = None,
48
+ read_only: bool = False,
49
+ cors_origins: Optional[List[str]] = None,
50
+ data_dir: Optional[Union[str, Path]] = None,
51
+ logger: Optional[logging.Logger] = None,
52
+ ) -> None:
53
+ self.read_only = read_only
54
+ self.cors_origins = list(cors_origins) if cors_origins is not None else ["*"]
55
+ self.logger = logger or LOGGER
56
+ self.auth = AuthGuard(api_key=api_key) if api_key else None
57
+ self.manager = AppManager(
58
+ data_dir=Path(data_dir) if data_dir else None,
59
+ logger=self.logger,
60
+ )
61
+
62
+ self.manager.load_persisted()
63
+ self._load_initial_apps(apps)
64
+
65
+ if not self.manager.apps:
66
+ self.manager.create("default", config_data={}, description="Default config")
67
+
68
+ self.app = self._create_app()
69
+ self._setup_middleware()
70
+ self._setup_routes()
71
+
72
+ def _load_initial_apps(self, apps: Union[Dict[str, Nacho], Nacho, None]) -> None:
73
+ if apps is None:
74
+ return
75
+ if isinstance(apps, Nacho):
76
+ apps = {"default": apps}
77
+ for name, config in apps.items():
78
+ self.manager.create(name, config=config, replace=True)
79
+
80
+ def _create_app(self) -> FastAPI:
81
+ @asynccontextmanager
82
+ async def lifespan(_: FastAPI):
83
+ self.logger.info("Starting Nacho API server")
84
+ yield
85
+ self.logger.info("Stopping Nacho API server")
86
+ self.manager.cleanup()
87
+
88
+ return FastAPI(
89
+ title="Nacho API",
90
+ description="Schema-first dynamic configuration service",
91
+ version=__version__,
92
+ lifespan=lifespan,
93
+ )
94
+
95
+ def _setup_middleware(self) -> None:
96
+ self.app.add_middleware(
97
+ CORSMiddleware,
98
+ allow_origins=self.cors_origins,
99
+ allow_credentials=self._allow_cors_credentials(),
100
+ allow_methods=["*"],
101
+ allow_headers=["*"],
102
+ )
103
+ if self.auth:
104
+ self.app.add_middleware(AuthMiddleware, auth=self.auth, logger=self.logger)
105
+
106
+ def _setup_routes(self) -> None:
107
+ @self.app.get("/")
108
+ async def root() -> Dict[str, Any]:
109
+ return {
110
+ "name": "nacho",
111
+ "version": __version__,
112
+ "docs": "/docs",
113
+ "health": "/health",
114
+ }
115
+
116
+ @self.app.get("/health")
117
+ async def health() -> Dict[str, Any]:
118
+ return {
119
+ "status": "ok",
120
+ "version": __version__,
121
+ "apps": len(self.manager.apps),
122
+ "read_only": self.read_only,
123
+ "auth_required": self.auth is not None,
124
+ }
125
+
126
+ @self.app.get("/ui", include_in_schema=False)
127
+ async def ui() -> FileResponse:
128
+ if not _UI_INDEX.is_file():
129
+ raise HTTPException(
130
+ status_code=status.HTTP_404_NOT_FOUND,
131
+ detail="Management UI is not bundled with this installation",
132
+ )
133
+ return FileResponse(_UI_INDEX, media_type="text/html")
134
+
135
+ @self.app.get("/api/apps")
136
+ async def list_apps() -> Dict[str, Dict[str, Dict[str, Any]]]:
137
+ return {"data": self.manager.list_info()}
138
+
139
+ @self.app.post("/api/convert")
140
+ async def convert_payload(request: ConvertRequest) -> Dict[str, Any]:
141
+ """Convert a config/schema payload between json, yaml, and toml."""
142
+ try:
143
+ obj = self._parse_config(request.data, request.from_)
144
+ text = dump_string(obj, request.to)
145
+ except (InvalidConfigDataError, ValueError) as exc:
146
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))
147
+ return {"format": request.to, "data": text}
148
+
149
+ @self.app.post("/api/apps", status_code=status.HTTP_201_CREATED)
150
+ async def create_app(request: AppCreateRequest) -> Dict[str, Any]:
151
+ self._check_writable()
152
+ try:
153
+ config_data = self._parse_config(request.data, request.format)
154
+ schema = self._parse_schema(request.schema_, request.schema_format)
155
+ app = self.manager.create(
156
+ request.name,
157
+ config_data=config_data,
158
+ description=request.description,
159
+ schema=schema,
160
+ )
161
+ except (InvalidConfigDataError, ValueError, ValidationError) as exc:
162
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))
163
+ return {"message": "App created", "app": app.info}
164
+
165
+ @self.app.get("/api/apps/{app_name}")
166
+ async def get_app(app_name: str) -> Dict[str, Dict[str, Any]]:
167
+ return {"data": self._get_app(app_name).info}
168
+
169
+ @self.app.put("/api/apps/{app_name}")
170
+ async def replace_app(
171
+ app_name: str,
172
+ request: AppCreateRequest,
173
+ if_match: Optional[str] = Header(default=None, alias="If-Match"),
174
+ ) -> Dict[str, Any]:
175
+ self._check_writable()
176
+ try:
177
+ config_data = self._parse_config(request.data, request.format)
178
+ schema = self._parse_schema(request.schema_, request.schema_format)
179
+ app = self.manager.replace(
180
+ app_name,
181
+ new_name=request.name,
182
+ config_data=config_data,
183
+ description=request.description,
184
+ schema=schema,
185
+ expected_revision=self._expected_revision(request.revision, if_match),
186
+ )
187
+ except KeyError:
188
+ raise self._not_found(app_name)
189
+ except RevisionConflictError as exc:
190
+ raise self._conflict(exc)
191
+ except (InvalidConfigDataError, ValueError, ValidationError) as exc:
192
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))
193
+ return {"message": "App replaced", "app": app.info}
194
+
195
+ @self.app.patch("/api/apps/{app_name}/metadata")
196
+ async def update_metadata(
197
+ app_name: str,
198
+ request: AppMetadataRequest,
199
+ if_match: Optional[str] = Header(default=None, alias="If-Match"),
200
+ ) -> Dict[str, Any]:
201
+ self._check_writable()
202
+ try:
203
+ app = self.manager.rename(
204
+ app_name,
205
+ new_name=request.name,
206
+ description=request.description,
207
+ expected_revision=self._expected_revision(request.revision, if_match),
208
+ )
209
+ except KeyError:
210
+ raise self._not_found(app_name)
211
+ except RevisionConflictError as exc:
212
+ raise self._conflict(exc)
213
+ except ValueError as exc:
214
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))
215
+ return {"message": "App metadata updated", "app": app.info}
216
+
217
+ @self.app.delete("/api/apps/{app_name}")
218
+ async def delete_app(app_name: str) -> Dict[str, str]:
219
+ self._check_writable()
220
+ if not self.manager.delete(app_name):
221
+ raise self._not_found(app_name)
222
+ return {"message": f"App {app_name!r} deleted"}
223
+
224
+ @self.app.get("/api/apps/{app_name}/config")
225
+ async def get_config(app_name: str, response: Response) -> Dict[str, Any]:
226
+ app = self._get_app(app_name)
227
+ self._set_revision_headers(response, app)
228
+ return app.config.get_all()
229
+
230
+ @self.app.put("/api/apps/{app_name}/config")
231
+ async def replace_config(
232
+ app_name: str,
233
+ request: ConfigRequest,
234
+ if_match: Optional[str] = Header(default=None, alias="If-Match"),
235
+ ) -> Dict[str, Any]:
236
+ self._check_writable()
237
+ try:
238
+ config_data = self._parse_config(request.data, request.format)
239
+ app = self.manager.replace_config(
240
+ app_name,
241
+ config_data,
242
+ expected_revision=self._expected_revision(request.revision, if_match),
243
+ )
244
+ except KeyError:
245
+ raise self._not_found(app_name)
246
+ except RevisionConflictError as exc:
247
+ raise self._conflict(exc)
248
+ except (InvalidConfigDataError, ValidationError) as exc:
249
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))
250
+ return {
251
+ "message": "Configuration replaced",
252
+ "revision": app.revision,
253
+ "data": app.config.get_all(),
254
+ }
255
+
256
+ @self.app.get("/api/apps/{app_name}/schema")
257
+ async def get_schema(app_name: str) -> Dict[str, Any]:
258
+ app = self._get_app(app_name)
259
+ return {"data": {"schema": app.schema}}
260
+
261
+ @self.app.put("/api/apps/{app_name}/schema")
262
+ async def replace_schema(
263
+ app_name: str,
264
+ request: SchemaUpdateRequest,
265
+ if_match: Optional[str] = Header(default=None, alias="If-Match"),
266
+ ) -> Dict[str, Any]:
267
+ self._check_writable()
268
+ try:
269
+ schema = self._parse_schema(request.schema_, request.schema_format)
270
+ app = self.manager.update_schema(
271
+ app_name,
272
+ schema,
273
+ expected_revision=self._expected_revision(request.revision, if_match),
274
+ )
275
+ except KeyError:
276
+ raise self._not_found(app_name)
277
+ except RevisionConflictError as exc:
278
+ raise self._conflict(exc)
279
+ except (InvalidConfigDataError, ValueError, ValidationError) as exc:
280
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))
281
+ return {"message": "Schema updated", "revision": app.revision, "schema": app.schema}
282
+
283
+ @self.app.get("/api/apps/{app_name}/config/{path:path}")
284
+ async def get_path(app_name: str, path: str) -> Dict[str, Any]:
285
+ app = self._get_app(app_name)
286
+ missing = object()
287
+ value = app.config.get(path, missing)
288
+ if value is missing:
289
+ raise HTTPException(
290
+ status_code=status.HTTP_404_NOT_FOUND,
291
+ detail=f"Configuration path {path!r} not found",
292
+ )
293
+ return {"path": path, "value": value}
294
+
295
+ @self.app.put("/api/apps/{app_name}/config/{path:path}")
296
+ async def set_path(
297
+ app_name: str,
298
+ path: str,
299
+ request: PathUpdateRequest,
300
+ if_match: Optional[str] = Header(default=None, alias="If-Match"),
301
+ ) -> Dict[str, Any]:
302
+ self._check_writable()
303
+ try:
304
+ value = self._convert_value(request.value, request.type)
305
+ app = self.manager.get(app_name)
306
+ self.manager.set_config_path(
307
+ app_name,
308
+ path,
309
+ value,
310
+ expected_revision=self._expected_revision(request.revision, if_match),
311
+ )
312
+ app = self._get_app(app_name) if app is None else app
313
+ except KeyError:
314
+ raise self._not_found(app_name)
315
+ except RevisionConflictError as exc:
316
+ raise self._conflict(exc)
317
+ except (ValueError, TypeError, json.JSONDecodeError, ValidationError) as exc:
318
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))
319
+ return {
320
+ "message": "Configuration path updated",
321
+ "path": path,
322
+ "value": value,
323
+ "revision": app.revision,
324
+ }
325
+
326
+ @self.app.delete("/api/apps/{app_name}/config/{path:path}")
327
+ async def delete_path(
328
+ app_name: str,
329
+ path: str,
330
+ revision: Optional[int] = None,
331
+ if_match: Optional[str] = Header(default=None, alias="If-Match"),
332
+ ) -> Dict[str, Any]:
333
+ self._check_writable()
334
+ try:
335
+ deleted = self.manager.delete_config_path(
336
+ app_name,
337
+ path,
338
+ expected_revision=self._expected_revision(revision, if_match),
339
+ )
340
+ if not deleted:
341
+ raise HTTPException(
342
+ status_code=status.HTTP_404_NOT_FOUND,
343
+ detail=f"Configuration path {path!r} not found",
344
+ )
345
+ app = self._get_app(app_name)
346
+ except KeyError:
347
+ raise self._not_found(app_name)
348
+ except RevisionConflictError as exc:
349
+ raise self._conflict(exc)
350
+ except ValidationError as exc:
351
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))
352
+ return {"message": f"Configuration path {path!r} deleted", "revision": app.revision}
353
+
354
+ @self.app.post("/api/apps/{app_name}/validate")
355
+ async def validate_config(app_name: str, request: ConfigRequest) -> Dict[str, Any]:
356
+ app = self._get_app(app_name)
357
+ try:
358
+ config_data = self._parse_config(request.data, request.format)
359
+ except InvalidConfigDataError as exc:
360
+ return {"valid": False, "errors": [str(exc)], "data": app.config.get_all()}
361
+ errors = app.config.check(config_data)
362
+ return {"valid": not errors, "errors": errors, "data": config_data}
363
+
364
+ @self.app.websocket("/ws/{app_name}")
365
+ async def watch(websocket: WebSocket, app_name: str) -> None:
366
+ if self.auth and not self.auth.verify_websocket(websocket):
367
+ await websocket.close(code=1008, reason="Unauthorized")
368
+ return
369
+ app = self.manager.get(app_name)
370
+ if app is None:
371
+ await websocket.close(code=4004, reason=f"App {app_name!r} not found")
372
+ return
373
+
374
+ await app.hub.connect(websocket)
375
+ try:
376
+ await websocket.send_json(
377
+ {
378
+ "type": "initial_config",
379
+ "app": app.name,
380
+ "revision": app.revision,
381
+ "data": app.config.get_all(),
382
+ }
383
+ )
384
+ while True:
385
+ await websocket.receive_text()
386
+ except WebSocketDisconnect:
387
+ pass
388
+ finally:
389
+ app.hub.disconnect(websocket)
390
+
391
+ def _parse_config(self, data: Any, fmt: str) -> Dict[str, Any]:
392
+ if isinstance(data, dict):
393
+ return data
394
+ try:
395
+ parsed = load_string(data, fmt)
396
+ except Exception as exc:
397
+ raise InvalidConfigDataError(f"Invalid {fmt} config: {exc}") from exc
398
+ if not isinstance(parsed, dict):
399
+ raise InvalidConfigDataError("Configuration payload must decode to an object")
400
+ return parsed
401
+
402
+ def _parse_schema(self, data: Optional[Any], fmt: str) -> Optional[Dict[str, Any]]:
403
+ if data is None:
404
+ return None
405
+ parsed = self._parse_config(data, fmt)
406
+ return parsed
407
+
408
+ def _convert_value(self, value: Any, type_hint: str) -> Any:
409
+ if type_hint == "raw":
410
+ return value
411
+ if type_hint == "str":
412
+ return str(value)
413
+ if type_hint == "int":
414
+ return int(value)
415
+ if type_hint == "float":
416
+ return float(value)
417
+ if type_hint == "bool":
418
+ if isinstance(value, bool):
419
+ return value
420
+ if isinstance(value, str):
421
+ lowered = value.lower()
422
+ if lowered in {"true", "yes", "1", "on"}:
423
+ return True
424
+ if lowered in {"false", "no", "0", "off"}:
425
+ return False
426
+ raise ValueError(f"Cannot convert {value!r} to bool")
427
+ if type_hint in {"list", "dict"} and isinstance(value, str):
428
+ value = json.loads(value)
429
+ if type_hint == "list":
430
+ return list(value)
431
+ if type_hint == "dict":
432
+ return dict(value)
433
+ raise ValueError(f"Unsupported value type: {type_hint}")
434
+
435
+ def _allow_cors_credentials(self) -> bool:
436
+ return "*" not in self.cors_origins
437
+
438
+ def _get_app(self, name: str) -> ConfigApp:
439
+ app = self.manager.get(name)
440
+ if app is None:
441
+ raise self._not_found(name)
442
+ return app
443
+
444
+ def _not_found(self, name: str) -> HTTPException:
445
+ return HTTPException(
446
+ status_code=status.HTTP_404_NOT_FOUND,
447
+ detail=f"App {name!r} not found",
448
+ )
449
+
450
+ def _conflict(self, exc: RevisionConflictError) -> HTTPException:
451
+ return HTTPException(
452
+ status_code=status.HTTP_409_CONFLICT,
453
+ detail={
454
+ "error": "revision_conflict",
455
+ "expected": exc.expected,
456
+ "actual": exc.actual,
457
+ },
458
+ )
459
+
460
+ def _expected_revision(
461
+ self,
462
+ body_revision: Optional[int],
463
+ if_match: Optional[str],
464
+ ) -> Optional[int]:
465
+ header_revision = self._parse_if_match(if_match)
466
+ if (
467
+ body_revision is not None
468
+ and header_revision is not None
469
+ and body_revision != header_revision
470
+ ):
471
+ raise HTTPException(
472
+ status_code=status.HTTP_400_BAD_REQUEST,
473
+ detail="revision and If-Match refer to different revisions",
474
+ )
475
+ return body_revision if body_revision is not None else header_revision
476
+
477
+ def _parse_if_match(self, value: Optional[str]) -> Optional[int]:
478
+ if value is None:
479
+ return None
480
+ value = value.strip()
481
+ if value == "*":
482
+ return None
483
+ if value.startswith("W/"):
484
+ value = value[2:].strip()
485
+ if len(value) >= 2 and value[0] == value[-1] == '"':
486
+ value = value[1:-1]
487
+ try:
488
+ revision = int(value)
489
+ except ValueError as exc:
490
+ raise HTTPException(
491
+ status_code=status.HTTP_400_BAD_REQUEST,
492
+ detail="If-Match must be an integer revision",
493
+ ) from exc
494
+ if revision < 1:
495
+ raise HTTPException(
496
+ status_code=status.HTTP_400_BAD_REQUEST,
497
+ detail="If-Match revision must be positive",
498
+ )
499
+ return revision
500
+
501
+ def _set_revision_headers(self, response: Response, app: ConfigApp) -> None:
502
+ revision = str(app.revision)
503
+ response.headers["ETag"] = f'"{revision}"'
504
+ response.headers["X-Nacho-Revision"] = revision
505
+
506
+ def _check_writable(self) -> None:
507
+ if self.read_only:
508
+ raise HTTPException(
509
+ status_code=status.HTTP_403_FORBIDDEN,
510
+ detail="Server is in read-only mode",
511
+ )
512
+
513
+ def run(self, host: str = "0.0.0.0", port: int = 8000, reload: bool = False) -> None:
514
+ config = uvicorn.Config(app=self.app, host=host, port=port, reload=reload)
515
+ uvicorn.Server(config).run()
nacho/server/auth.py ADDED
@@ -0,0 +1,93 @@
1
+ """Authentication helpers for the Nacho API server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hmac
6
+ import logging
7
+ from typing import Optional, Sequence
8
+
9
+ from fastapi import Request, WebSocket
10
+ from starlette.middleware.base import BaseHTTPMiddleware
11
+ from starlette.responses import JSONResponse
12
+
13
+ LOGGER = logging.getLogger(__name__)
14
+
15
+ _AUTH_PREFIX = "Bearer "
16
+ _SESSION_COOKIE = "NACHO_api_key"
17
+ _DEFAULT_PUBLIC_PATHS = ("/health", "/favicon.ico", "/ui")
18
+
19
+
20
+ class AuthGuard:
21
+ """Verifies API keys from headers, cookies, and WebSocket handshakes."""
22
+
23
+ def __init__(self, api_key: Optional[str] = None) -> None:
24
+ self.api_key = api_key
25
+
26
+ @property
27
+ def enabled(self) -> bool:
28
+ return bool(self.api_key)
29
+
30
+ def set_api_key(self, api_key: str) -> None:
31
+ if not api_key:
32
+ raise ValueError("API key cannot be empty")
33
+ self.api_key = api_key
34
+
35
+ def verify_token(self, token: Optional[str]) -> bool:
36
+ """Return True when *token* matches the configured API key."""
37
+ if not self.api_key:
38
+ return True
39
+ if not token:
40
+ return False
41
+ token = token.strip()
42
+ if token.startswith(_AUTH_PREFIX):
43
+ token = token[len(_AUTH_PREFIX) :]
44
+ return bool(token) and hmac.compare_digest(token, self.api_key)
45
+
46
+ def verify_request(self, request: Request) -> bool:
47
+ """Verify HTTP auth from the session cookie or Authorization header."""
48
+ if not self.enabled:
49
+ return True
50
+ cookie_key = request.cookies.get(_SESSION_COOKIE)
51
+ if self.verify_token(cookie_key):
52
+ return True
53
+ return self.verify_token(request.headers.get("Authorization"))
54
+
55
+ def verify_websocket(self, websocket: WebSocket) -> bool:
56
+ """Verify WebSocket auth from cookie or Authorization header."""
57
+ if not self.enabled:
58
+ return True
59
+ cookie_key = websocket.cookies.get(_SESSION_COOKIE)
60
+ if self.verify_token(cookie_key):
61
+ return True
62
+ return self.verify_token(websocket.headers.get("Authorization"))
63
+
64
+
65
+ class AuthMiddleware(BaseHTTPMiddleware):
66
+ """Rejects unauthenticated HTTP requests when API-key auth is enabled."""
67
+
68
+ def __init__(
69
+ self,
70
+ app,
71
+ auth: AuthGuard,
72
+ logger: Optional[logging.Logger] = None,
73
+ public_paths: Sequence[str] = _DEFAULT_PUBLIC_PATHS,
74
+ ) -> None:
75
+ super().__init__(app)
76
+ self.auth = auth
77
+ self.logger = logger or LOGGER
78
+ self.public_paths = tuple(public_paths)
79
+
80
+ async def dispatch(self, request: Request, call_next):
81
+ if request.method == "OPTIONS" or self._is_public(request.url.path):
82
+ return await call_next(request)
83
+ if self.auth.verify_request(request):
84
+ return await call_next(request)
85
+
86
+ self.logger.debug("Rejected unauthenticated request to %s", request.url.path)
87
+ return JSONResponse(
88
+ status_code=403,
89
+ content={"error": "Unauthorized: invalid API key"},
90
+ )
91
+
92
+ def _is_public(self, path: str) -> bool:
93
+ return any(path == public or path.startswith(f"{public}/") for public in self.public_paths)