dash-auth-async 1.3.7__tar.gz → 1.3.8__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 (22) hide show
  1. {dash_auth_async-1.3.7/dash_auth_async.egg-info → dash_auth_async-1.3.8}/PKG-INFO +4 -1
  2. {dash_auth_async-1.3.7 → dash_auth_async-1.3.8}/README.md +3 -0
  3. {dash_auth_async-1.3.7 → dash_auth_async-1.3.8}/dash_auth_async/auth.py +12 -0
  4. {dash_auth_async-1.3.7 → dash_auth_async-1.3.8}/dash_auth_async/group_protection.py +157 -18
  5. {dash_auth_async-1.3.7 → dash_auth_async-1.3.8}/dash_auth_async/version.py +1 -1
  6. {dash_auth_async-1.3.7 → dash_auth_async-1.3.8/dash_auth_async.egg-info}/PKG-INFO +4 -1
  7. {dash_auth_async-1.3.7 → dash_auth_async-1.3.8}/pyproject.toml +2 -2
  8. {dash_auth_async-1.3.7 → dash_auth_async-1.3.8}/LICENSE +0 -0
  9. {dash_auth_async-1.3.7 → dash_auth_async-1.3.8}/MANIFEST.in +0 -0
  10. {dash_auth_async-1.3.7 → dash_auth_async-1.3.8}/dash_auth_async/__init__.py +0 -0
  11. {dash_auth_async-1.3.7 → dash_auth_async-1.3.8}/dash_auth_async/_optional.py +0 -0
  12. {dash_auth_async-1.3.7 → dash_auth_async-1.3.8}/dash_auth_async/backends.py +0 -0
  13. {dash_auth_async-1.3.7 → dash_auth_async-1.3.8}/dash_auth_async/basic_auth.py +0 -0
  14. {dash_auth_async-1.3.7 → dash_auth_async-1.3.8}/dash_auth_async/oidc_auth.py +0 -0
  15. {dash_auth_async-1.3.7 → dash_auth_async-1.3.8}/dash_auth_async/public_routes.py +0 -0
  16. {dash_auth_async-1.3.7 → dash_auth_async-1.3.8}/dash_auth_async/quart_client.py +0 -0
  17. {dash_auth_async-1.3.7 → dash_auth_async-1.3.8}/dash_auth_async/websocket_auth.py +0 -0
  18. {dash_auth_async-1.3.7 → dash_auth_async-1.3.8}/dash_auth_async.egg-info/SOURCES.txt +0 -0
  19. {dash_auth_async-1.3.7 → dash_auth_async-1.3.8}/dash_auth_async.egg-info/dependency_links.txt +0 -0
  20. {dash_auth_async-1.3.7 → dash_auth_async-1.3.8}/dash_auth_async.egg-info/requires.txt +0 -0
  21. {dash_auth_async-1.3.7 → dash_auth_async-1.3.8}/dash_auth_async.egg-info/top_level.txt +0 -0
  22. {dash_auth_async-1.3.7 → dash_auth_async-1.3.8}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dash-auth-async
3
- Version: 1.3.7
3
+ Version: 1.3.8
4
4
  Summary: Dash Authorization Package.
5
5
  Author-email: Jonas Schrage <119843859+joschrag@users.noreply.github.com>
6
6
  License: MIT
@@ -71,6 +71,7 @@ How this fork compares to upstream [`dash-auth`](https://github.com/plotly/dash-
71
71
  | Protected / public callbacks | ✅ | ✅ |
72
72
  | Async callbacks | ❌ | ✅ <sup>2</sup> |
73
73
  | Authenticated WebSocket callbacks | ❌ | ✅ <sup>3</sup> |
74
+ | Group-protected background callbacks | ❌ | ✅ <sup>4</sup> |
74
75
 
75
76
  ✅ supported · ❌ not supported
76
77
 
@@ -80,6 +81,8 @@ How this fork compares to upstream [`dash-auth`](https://github.com/plotly/dash-
80
81
 
81
82
  <sup>3</sup> Provided by the Quart and FastAPI backends only. WebSocket auth is a no-op on Flask, which has no WebSocket callback transport.
82
83
 
84
+ <sup>4</sup> `protected_callback(..., background=True)` checks the user's groups when the request arrives — on the start request and every poll — so a denied user gets the fallback output without a job ever being started. The job itself runs in a separate process with no session, which is why the check can't live inside it (upstream checks there, so a background job always sees "no user" and is denied). Needs a background manager, e.g. `dash[diskcache]`. These callbacks are refused over the WebSocket; Dash only sends background callbacks over HTTP.
85
+
83
86
 
84
87
  For local testing, install [uv](https://docs.astral.sh/uv/getting-started/installation/), then install the dev dependencies and run individual tests:
85
88
 
@@ -26,6 +26,7 @@ How this fork compares to upstream [`dash-auth`](https://github.com/plotly/dash-
26
26
  | Protected / public callbacks | ✅ | ✅ |
27
27
  | Async callbacks | ❌ | ✅ <sup>2</sup> |
28
28
  | Authenticated WebSocket callbacks | ❌ | ✅ <sup>3</sup> |
29
+ | Group-protected background callbacks | ❌ | ✅ <sup>4</sup> |
29
30
 
30
31
  ✅ supported · ❌ not supported
31
32
 
@@ -35,6 +36,8 @@ How this fork compares to upstream [`dash-auth`](https://github.com/plotly/dash-
35
36
 
36
37
  <sup>3</sup> Provided by the Quart and FastAPI backends only. WebSocket auth is a no-op on Flask, which has no WebSocket callback transport.
37
38
 
39
+ <sup>4</sup> `protected_callback(..., background=True)` checks the user's groups when the request arrives — on the start request and every poll — so a denied user gets the fallback output without a job ever being started. The job itself runs in a separate process with no session, which is why the check can't live inside it (upstream checks there, so a background job always sees "no user" and is denied). Needs a background manager, e.g. `dash[diskcache]`. These callbacks are refused over the WebSocket; Dash only sends background callbacks over HTTP.
40
+
38
41
 
39
42
  For local testing, install [uv](https://docs.astral.sh/uv/getting-started/installation/), then install the dev dependencies and run individual tests:
40
43
 
@@ -13,6 +13,7 @@ from .backends import (
13
13
  register_backend,
14
14
  set_active_backend,
15
15
  )
16
+ from .group_protection import background_gate_response, has_background_gate
16
17
  from .public_routes import (
17
18
  add_public_routes,
18
19
  get_public_callbacks,
@@ -128,6 +129,10 @@ class Auth(ABC):
128
129
  # If the route is not a callback route, check whether the path
129
130
  # matches a public route, or whether the request is authorised
130
131
  if public_routes.test(path) or self.is_authorized():
132
+ if path == self._callback_path():
133
+ # Group-protected background callbacks are gated here, not in
134
+ # their job process (which has no session to read).
135
+ return background_gate_response(self.app, body)
131
136
  return None
132
137
 
133
138
  # Otherwise, ask the user to log in
@@ -156,6 +161,13 @@ class Auth(ABC):
156
161
  if self._is_public_routing_callback(payload):
157
162
  return True
158
163
 
164
+ # A group-protected background callback's job is registered ungated
165
+ # (its gate runs in _authorize, over HTTP). The renderer never sends
166
+ # background callbacks over the socket, so refuse them here rather
167
+ # than let a crafted message run the job without the group check.
168
+ if has_background_gate(self.app, payload.get("output")):
169
+ return False
170
+
159
171
  return user is not None
160
172
 
161
173
  def _is_public_routing_callback(self, body: dict) -> bool:
@@ -8,9 +8,22 @@ from collections.abc import Callable
8
8
  from typing import Any, Literal
9
9
 
10
10
  import dash
11
+ from dash import get_app
12
+
13
+ # The helpers Dash uses internally to key its callback map and serialise
14
+ # responses; no public API equivalent.
15
+ from dash._grouping import flatten_grouping # noqa: PLC2701
16
+ from dash._no_update import NoUpdate # noqa: PLC2701 — Dash's no_update check
17
+ from dash._utils import ( # noqa: PLC2701
18
+ clean_property_name,
19
+ create_callback_id,
20
+ stringify_id,
21
+ to_json,
22
+ )
23
+ from dash.dependencies import Output, handle_grouped_callback_args
11
24
  from dash.exceptions import PreventUpdate
12
25
 
13
- from .backends import get_active_backend
26
+ from .backends import detect_backend, get_active_backend
14
27
  from .websocket_auth import _WS_AUTH_USER
15
28
 
16
29
  OutputVal = Callable[[], Any] | Any
@@ -273,24 +286,32 @@ def protected_callback( # noqa: PLR0913 — public decorator with many optional
273
286
  """
274
287
 
275
288
  def decorator(func):
276
- wrapped_func = dash.callback(*callback_args, **callback_kwargs)(
277
- protected(
278
- unauthenticated_output=(
279
- unauthenticated_output
280
- if unauthenticated_output is not None
281
- else functools.partial(_prevent_unauthenticated, func.__name__)
282
- ),
283
- missing_permissions_output=(
284
- missing_permissions_output
285
- if missing_permissions_output is not None
286
- else functools.partial(_prevent_unauthorised, func.__name__)
287
- ),
288
- groups=groups,
289
- groups_key=groups_key,
290
- groups_str_split=groups_str_split,
291
- check_type=check_type,
292
- )(func)
289
+ guard = protected(
290
+ unauthenticated_output=(
291
+ unauthenticated_output
292
+ if unauthenticated_output is not None
293
+ else functools.partial(_prevent_unauthenticated, func.__name__)
294
+ ),
295
+ missing_permissions_output=(
296
+ missing_permissions_output
297
+ if missing_permissions_output is not None
298
+ else functools.partial(_prevent_unauthorised, func.__name__)
299
+ ),
300
+ groups=groups,
301
+ groups_key=groups_key,
302
+ groups_str_split=groups_str_split,
303
+ check_type=check_type,
293
304
  )
305
+ if callback_kwargs.get("background"):
306
+ # A background job runs in another process with no session, so the
307
+ # gate can't run inside it (it would always deny). Gate at HTTP
308
+ # dispatch instead -- Auth._authorize, on the start request and
309
+ # every poll -- and register the job unwrapped. Registered first so
310
+ # a failure leaves no ungated callback behind.
311
+ _register_background_gate(callback_args, callback_kwargs, guard(_proceed))
312
+ wrapped_func = dash.callback(*callback_args, **callback_kwargs)(func)
313
+ else:
314
+ wrapped_func = dash.callback(*callback_args, **callback_kwargs)(guard(func))
294
315
 
295
316
  def wrap(*args, **kwargs):
296
317
  return wrapped_func(*args, **kwargs)
@@ -298,3 +319,121 @@ def protected_callback( # noqa: PLR0913 — public decorator with many optional
298
319
  return wrap
299
320
 
300
321
  return decorator
322
+
323
+
324
+ BACKGROUND_GATES = "PROTECTED_BACKGROUND_CALLBACKS"
325
+
326
+
327
+ def _proceed() -> object:
328
+ """Target for the dispatch-time gate: reached only when authorised.
329
+
330
+ Returns:
331
+ The ``_PROCEED`` sentinel.
332
+ """
333
+ return _PROCEED
334
+
335
+
336
+ def _register_background_gate(callback_args, callback_kwargs, gate: Callable) -> None:
337
+ """Record ``gate`` for a background callback, keyed like ``public_callback``.
338
+
339
+ Raises:
340
+ RuntimeError: when no Dash app exists yet. Fails loudly because the job
341
+ itself is registered ungated -- silently skipping the gate (as
342
+ ``public_callback`` may skip its whitelist) would leave it open.
343
+ """
344
+ output, inputs, _state, _indices, _prevent = handle_grouped_callback_args(
345
+ callback_args, callback_kwargs
346
+ )
347
+ # Same id Dash computes in register_callback, so dispatch lookups match.
348
+ flat_output = output if isinstance(output, Output) else flatten_grouping(output)
349
+ callback_id = create_callback_id(flat_output, inputs, no_output=not flat_output)
350
+ try:
351
+ app = get_app()
352
+ except Exception as err:
353
+ raise RuntimeError(
354
+ "protected_callback(background=True) must be registered after the "
355
+ "Dash app is created: the group check runs at request dispatch."
356
+ ) from err
357
+ backend = detect_backend(app.server)
358
+ gates = backend.read_config(app.server, BACKGROUND_GATES, {})
359
+ backend.store_config(
360
+ app.server, BACKGROUND_GATES, {**gates, callback_id: (gate, output)}
361
+ )
362
+
363
+
364
+ def has_background_gate(app, output: str | None) -> bool:
365
+ """Whether ``output`` is a group-protected background callback.
366
+
367
+ Returns:
368
+ True when a dispatch-time gate is registered for that callback id.
369
+ """
370
+ backend = detect_backend(app.server)
371
+ return output in backend.read_config(app.server, BACKGROUND_GATES, {})
372
+
373
+
374
+ def background_gate_response(app, body: dict | None) -> Any:
375
+ """Run a background callback's group gate for an authorised request.
376
+
377
+ Called from ``Auth._authorize`` under the request context, where
378
+ ``_current_user()`` can read the session -- unlike the job process.
379
+
380
+ Returns:
381
+ None to let the request proceed (start or poll the job), ``("", 204)``
382
+ when the fallback raised ``PreventUpdate`` or updates nothing, or a Dash
383
+ callback response carrying the fallback output -- so a denied user
384
+ never spawns a job.
385
+ """
386
+ if not body: # _authorize already rejects bodiless callback requests
387
+ return None
388
+ backend = detect_backend(app.server)
389
+ entry = backend.read_config(app.server, BACKGROUND_GATES, {}).get(
390
+ body.get("output")
391
+ )
392
+ if entry is None:
393
+ return None
394
+ gate, output = entry
395
+ try:
396
+ fallback = gate()
397
+ except PreventUpdate:
398
+ return "", 204
399
+ if fallback is _PROCEED:
400
+ return None
401
+ response = _callback_response(output, body.get("outputs"), fallback)
402
+ if not response: # Dash answers an all-no_update result with 204 too
403
+ return "", 204
404
+ return (
405
+ to_json({"multi": True, "response": response}),
406
+ 200,
407
+ {"Content-Type": "application/json"},
408
+ )
409
+
410
+
411
+ def _callback_response(output: Any, outputs: Any, value: Any) -> dict:
412
+ """Map ``value`` onto the request's output specs, as Dash's own dispatch does.
413
+
414
+ Mirrors ``dash._callback._prepare_response``: a wildcard (``ALL``/
415
+ ``ALLSMALLER``) output's spec is a list, matched item-by-item against a list
416
+ value; ``prop@hash`` (``allow_duplicate``) is reduced to ``prop``.
417
+
418
+ Returns:
419
+ ``{component_id: {prop: value}}``; empty when nothing is updated.
420
+ """
421
+ if isinstance(output, Output):
422
+ value, outputs = [value], [outputs]
423
+ elif NoUpdate.is_no_update(value):
424
+ return {}
425
+ else:
426
+ value = flatten_grouping(
427
+ list(value) if isinstance(value, tuple) else value, output
428
+ )
429
+ response: dict = {}
430
+ for val, spec in zip(value, outputs, strict=True):
431
+ if NoUpdate.is_no_update(val):
432
+ continue
433
+ # A wildcard output's spec is a list, matched item-by-item to a list value.
434
+ vals, specs = (val, spec) if isinstance(spec, list) else ([val], [spec])
435
+ for vali, speci in zip(vals, specs, strict=True):
436
+ if not NoUpdate.is_no_update(vali):
437
+ prop = clean_property_name(speci["property"])
438
+ response.setdefault(stringify_id(speci["id"]), {})[prop] = vali
439
+ return response
@@ -1,3 +1,3 @@
1
1
  """Single source of truth for the package version."""
2
2
 
3
- __version__ = "1.3.7"
3
+ __version__ = "1.3.8"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dash-auth-async
3
- Version: 1.3.7
3
+ Version: 1.3.8
4
4
  Summary: Dash Authorization Package.
5
5
  Author-email: Jonas Schrage <119843859+joschrag@users.noreply.github.com>
6
6
  License: MIT
@@ -71,6 +71,7 @@ How this fork compares to upstream [`dash-auth`](https://github.com/plotly/dash-
71
71
  | Protected / public callbacks | ✅ | ✅ |
72
72
  | Async callbacks | ❌ | ✅ <sup>2</sup> |
73
73
  | Authenticated WebSocket callbacks | ❌ | ✅ <sup>3</sup> |
74
+ | Group-protected background callbacks | ❌ | ✅ <sup>4</sup> |
74
75
 
75
76
  ✅ supported · ❌ not supported
76
77
 
@@ -80,6 +81,8 @@ How this fork compares to upstream [`dash-auth`](https://github.com/plotly/dash-
80
81
 
81
82
  <sup>3</sup> Provided by the Quart and FastAPI backends only. WebSocket auth is a no-op on Flask, which has no WebSocket callback transport.
82
83
 
84
+ <sup>4</sup> `protected_callback(..., background=True)` checks the user's groups when the request arrives — on the start request and every poll — so a denied user gets the fallback output without a job ever being started. The job itself runs in a separate process with no session, which is why the check can't live inside it (upstream checks there, so a background job always sees "no user" and is denied). Needs a background manager, e.g. `dash[diskcache]`. These callbacks are refused over the WebSocket; Dash only sends background callbacks over HTTP.
85
+
83
86
 
84
87
  For local testing, install [uv](https://docs.astral.sh/uv/getting-started/installation/), then install the dev dependencies and run individual tests:
85
88
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "dash-auth-async"
7
- version = "1.3.7"
7
+ version = "1.3.8"
8
8
  description = "Dash Authorization Package."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -58,7 +58,7 @@ include = ["dash_auth_async*"]
58
58
  dev = [
59
59
  "asgiref>=3.11.1",
60
60
  "creosote>=5.2.0",
61
- "dash[testing]>=4.2.0",
61
+ "dash[testing,diskcache]>=4.2.0",
62
62
  "setuptools>=79.0.1",
63
63
  "ty==0.0.51",
64
64
  "pre-commit>=3.5.0",
File without changes