authorizer.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. """An Authorizer for use in the Jupyter server.
  2. The default authorizer (AllowAllAuthorizer)
  3. allows all authenticated requests
  4. .. versionadded:: 2.0
  5. """
  6. # Copyright (c) Jupyter Development Team.
  7. # Distributed under the terms of the Modified BSD License.
  8. from __future__ import annotations
  9. from typing import TYPE_CHECKING
  10. from traitlets import Instance
  11. from traitlets.config import LoggingConfigurable
  12. from .identity import IdentityProvider, User
  13. if TYPE_CHECKING:
  14. from collections.abc import Awaitable
  15. from jupyter_server.base.handlers import JupyterHandler
  16. class Authorizer(LoggingConfigurable):
  17. """Base class for authorizing access to resources
  18. in the Jupyter Server.
  19. All authorizers used in Jupyter Server
  20. should inherit from this base class and, at the very minimum,
  21. implement an ``is_authorized`` method with the
  22. same signature as in this base class.
  23. The ``is_authorized`` method is called by the ``@authorized`` decorator
  24. in JupyterHandler. If it returns True, the incoming request
  25. to the server is accepted; if it returns False, the server
  26. returns a 403 (Forbidden) error code.
  27. The authorization check will only be applied to requests
  28. that have already been authenticated.
  29. .. versionadded:: 2.0
  30. """
  31. identity_provider = Instance(IdentityProvider)
  32. def is_authorized(
  33. self, handler: JupyterHandler, user: User, action: str, resource: str
  34. ) -> Awaitable[bool] | bool:
  35. """A method to determine if ``user`` is authorized to perform ``action``
  36. (read, write, or execute) on the ``resource`` type.
  37. Parameters
  38. ----------
  39. user : jupyter_server.auth.User
  40. An object representing the authenticated user,
  41. as returned by :meth:`jupyter_server.auth.IdentityProvider.get_user`.
  42. action : str
  43. the category of action for the current request: read, write, or execute.
  44. resource : str
  45. the type of resource (i.e. contents, kernels, files, etc.) the user is requesting.
  46. Returns
  47. -------
  48. bool
  49. True if user authorized to make request; False, otherwise
  50. """
  51. raise NotImplementedError
  52. class AllowAllAuthorizer(Authorizer):
  53. """A no-op implementation of the Authorizer
  54. This authorizer allows all authenticated requests.
  55. .. versionadded:: 2.0
  56. """
  57. def is_authorized(
  58. self, handler: JupyterHandler, user: User, action: str, resource: str
  59. ) -> bool:
  60. """This method always returns True.
  61. All authenticated users are allowed to do anything in the Jupyter Server.
  62. """
  63. return True