nacho-python 0.1.0__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.0"
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
@@ -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:
nacho/server/auth.py CHANGED
@@ -4,7 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import hmac
6
6
  import logging
7
- from typing import Optional, Sequence
7
+ from typing import Any, Optional, Sequence
8
8
  from urllib.parse import unquote
9
9
 
10
10
  from fastapi import Request, WebSocket
@@ -20,106 +20,83 @@ _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
23
+ def validate_api_key(name: str, value: Any) -> Optional[str]:
24
+ """Return *value* if it is a usable API key, raising TypeError otherwise.
25
+
26
+ Keys are compared as UTF-8 bytes, so a non-str key would only fail when
27
+ someone first presents a *valid* credential — an opaque 500 long after
28
+ the misconfiguration. Worse, a falsy non-str (``[]``, ``0``) would leave
29
+ the server silently unauthenticated. Both are caught here instead.
30
+ """
31
+ if value is None:
32
+ return None
33
+ if not isinstance(value, str):
34
+ raise TypeError(f"{name} must be a str or None, got {type(value).__name__}")
35
+ return value
26
36
 
27
37
 
28
38
  class AuthGuard:
29
- """Verifies API keys from headers, cookies, and WebSocket handshakes.
39
+ """Verifies the API key from headers, cookies, and WebSocket handshakes.
30
40
 
31
- Two keys can be configured: *api_key* grants full access, and the
32
- optional *read_only_api_key* grants read access only — the middleware
33
- rejects unsafe methods presented with it. Handing dashboards and
34
- 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``.
35
45
  """
36
46
 
37
- def __init__(
38
- self,
39
- api_key: Optional[str] = None,
40
- read_only_api_key: Optional[str] = None,
41
- ) -> None:
42
- self.api_key = api_key
43
- self.read_only_api_key = read_only_api_key
47
+ def __init__(self, api_key: Optional[str] = None) -> None:
48
+ self.api_key = validate_api_key("api_key", api_key)
44
49
 
45
50
  @property
46
51
  def enabled(self) -> bool:
47
- return bool(self.api_key or self.read_only_api_key)
52
+ return bool(self.api_key)
48
53
 
49
54
  @staticmethod
50
55
  def _matches(token: str, key: str) -> bool:
51
56
  # Compare as bytes: compare_digest raises TypeError on non-ASCII str input.
52
57
  return hmac.compare_digest(token.encode("utf-8"), key.encode("utf-8"))
53
58
 
54
- def role_for_token(self, token: Optional[str]) -> Optional[str]:
55
- """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 ")."""
56
61
  if not self.enabled:
57
- return ROLE_ADMIN
62
+ return True
58
63
  if not token:
59
- return None
64
+ return False
60
65
  token = token.strip()
61
66
  if token.startswith(_AUTH_PREFIX):
62
67
  token = token[len(_AUTH_PREFIX) :]
63
68
  if not token:
64
- return None
65
- if self.api_key and self._matches(token, self.api_key):
66
- return ROLE_ADMIN
67
- if self.read_only_api_key and self._matches(token, self.read_only_api_key):
68
- return ROLE_READ
69
- return None
69
+ return False
70
+ return self._matches(token, self.api_key)
70
71
 
71
- def role_for_cookie(self, raw: Optional[str]) -> Optional[str]:
72
- """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.
73
74
 
74
75
  The raw form is also accepted so a cookie written before encoding
75
76
  was introduced keeps working until it is rewritten.
76
77
  """
77
78
  if not raw:
78
- return None
79
- role = self.role_for_token(raw)
80
- if role is not None:
81
- return role
79
+ return False
80
+ if self.verify_token(raw):
81
+ return True
82
82
  decoded = unquote(raw)
83
- if decoded != raw:
84
- return self.role_for_token(decoded)
85
- return None
86
-
87
- def role_for_request(self, request: Request) -> Optional[str]:
88
- """Best role granted by the session cookie or Authorization header."""
89
- roles = {
90
- self.role_for_cookie(request.cookies.get(_SESSION_COOKIE)),
91
- self.role_for_token(request.headers.get("Authorization")),
92
- }
93
- if ROLE_ADMIN in roles:
94
- return ROLE_ADMIN
95
- if ROLE_READ in roles:
96
- return ROLE_READ
97
- return None
98
-
99
- # -- boolean convenience wrappers ----------------------------------
100
-
101
- def verify_token(self, token: Optional[str]) -> bool:
102
- """True when *token* grants full access."""
103
- return self.role_for_token(token) == ROLE_ADMIN
104
-
105
- def verify_cookie(self, raw: Optional[str]) -> bool:
106
- """True when the cookie grants any access."""
107
- return self.role_for_cookie(raw) is not None
83
+ return decoded != raw and self.verify_token(decoded)
108
84
 
109
85
  def verify_request(self, request: Request) -> bool:
110
- """True when the request carries any valid credential (read or admin)."""
111
- 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
+ )
112
92
 
113
93
  def verify_websocket(self, websocket: WebSocket) -> bool:
114
- """Verify WebSocket auth from cookie or Authorization header.
115
-
116
- Subscriptions are read-only by nature, so either key is accepted.
117
- """
94
+ """Verify WebSocket auth from cookie or Authorization header."""
118
95
  if not self.enabled:
119
96
  return True
120
- if self.role_for_cookie(websocket.cookies.get(_SESSION_COOKIE)) is not None:
97
+ if self.verify_cookie(websocket.cookies.get(_SESSION_COOKIE)):
121
98
  return True
122
- return self.role_for_token(websocket.headers.get("Authorization")) is not None
99
+ return self.verify_token(websocket.headers.get("Authorization"))
123
100
 
124
101
 
125
102
  class AuthMiddleware(BaseHTTPMiddleware):
@@ -137,23 +114,14 @@ class AuthMiddleware(BaseHTTPMiddleware):
137
114
  self.logger = logger or LOGGER
138
115
  self.public_paths = tuple(public_paths)
139
116
 
140
- _SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
141
-
142
117
  async def dispatch(self, request: Request, call_next):
143
118
  if request.method == "OPTIONS" or self._is_public(request.url.path):
144
119
  return await call_next(request)
145
- role = self.auth.role_for_request(request)
146
- if role == ROLE_ADMIN or (role == ROLE_READ and request.method in self._SAFE_METHODS):
120
+ if self.auth.verify_request(request):
147
121
  return await call_next(request)
148
122
 
149
123
  # Same {"detail": ...} envelope FastAPI uses for HTTPException, so
150
124
  # clients only ever parse one error shape.
151
- if role == ROLE_READ:
152
- self.logger.debug("Rejected read-only-key write to %s", request.url.path)
153
- return JSONResponse(
154
- status_code=403,
155
- content={"detail": "Forbidden: this API key grants read-only access"},
156
- )
157
125
  self.logger.debug("Rejected unauthenticated request to %s", request.url.path)
158
126
  return JSONResponse(
159
127
  status_code=401,