magpie.adapter.magpieowssecurity ================================ .. py:module:: magpie.adapter.magpieowssecurity Attributes ---------- .. autoapisummary:: magpie.adapter.magpieowssecurity.ProviderSigninAPI magpie.adapter.magpieowssecurity.CONTENT_TYPE_JSON magpie.adapter.magpieowssecurity.LOGGER Classes ------- .. autoapisummary:: magpie.adapter.magpieowssecurity.LooseVersion magpie.adapter.magpieowssecurity.Service magpie.adapter.magpieowssecurity.Permission magpie.adapter.magpieowssecurity.MagpieOWSSecurity Functions --------- .. autoapisummary:: magpie.adapter.magpieowssecurity.evaluate_call magpie.adapter.magpieowssecurity.verify_param magpie.adapter.magpieowssecurity.get_constant magpie.adapter.magpieowssecurity.get_connected_session magpie.adapter.magpieowssecurity.invalidate_service magpie.adapter.magpieowssecurity.service_factory magpie.adapter.magpieowssecurity.get_authenticate_headers magpie.adapter.magpieowssecurity.get_logger magpie.adapter.magpieowssecurity.get_magpie_url magpie.adapter.magpieowssecurity.get_settings Module Contents --------------- .. py:function:: evaluate_call(call: Callable[[], Any], fallback: Optional[Callable[[], None]] = None, http_error: Type[pyramid.httpexceptions.HTTPError] = HTTPInternalServerError, http_kwargs: Optional[magpie.typedefs.ParamsType] = None, msg_on_fail: magpie.typedefs.Str = '', content: Optional[magpie.typedefs.JSON] = None, content_type: magpie.typedefs.Str = CONTENT_TYPE_JSON, metadata: Optional[magpie.typedefs.JSON] = None) -> Any Evaluates the specified :paramref:`call` with a wrapped HTTP exception handling. On failure, tries to call. :paramref:`fallback` if specified, and finally raises the specified :paramref:`http_error`. Any potential error generated by :paramref:`fallback` or :paramref:`http_error` themselves are treated as :class:`HTTPInternalServerError`. Exceptions are generated using the standard output method formatted based on specified :paramref:`content_type`. Example: normal call:: try: res = func(args) except Exception as exc: fb_func() raise HTTPExcept(exc.message) wrapped call:: res = evaluate_call(lambda: func(args), fallback=lambda: fb_func(), http_error=HTTPExcept, **kwargs) :param call: function to call, *MUST* be specified as `lambda: ` :param fallback: function to call (if any) when `call` failed, *MUST* be `lambda: ` :param http_error: alternative exception to raise on `call` failure :param http_kwargs: additional keyword arguments to pass to `http_error` if called in case of HTTP exception :param msg_on_fail: message details to return in HTTP exception if `call` failed :param content: json formatted additional content to provide in case of exception :param content_type: format in which to return the exception (one of `magpie.common.SUPPORTED_ACCEPT_TYPES`) :param metadata: request metadata to add to the response body. (see: :func:`magpie.api.requests.get_request_info`) :raises http_error: on `call` failure :raises `HTTPInternalServerError`: on `fallback` failure :return: whichever return value `call` might have if no exception occurred .. py:function:: verify_param(param: Any, param_compare: Optional[Union[Any, List[Any]]] = None, param_name: Optional[magpie.typedefs.Str] = None, param_content: Optional[magpie.typedefs.JSON] = None, with_param: bool = True, http_error: Type[pyramid.httpexceptions.HTTPError] = HTTPBadRequest, http_kwargs: Optional[magpie.typedefs.ParamsType] = None, msg_on_fail: magpie.typedefs.Str = '', content: Optional[magpie.typedefs.JSON] = None, content_type: magpie.typedefs.Str = CONTENT_TYPE_JSON, metadata: Optional[magpie.typedefs.JSON] = None, not_none: bool = False, not_empty: bool = False, not_in: bool = False, not_equal: bool = False, is_true: bool = False, is_false: bool = False, is_none: bool = False, is_empty: bool = False, is_in: bool = False, is_equal: bool = False, is_type: bool = False, matches: bool = False) -> None Evaluate various parameter combinations given the requested verification flags. Given a failing verification, directly raises the specified :paramref:`http_error`. Invalid usage exceptions generated by this verification process are treated as :class:`HTTPInternalServerError`. Exceptions are generated using the standard output method. :param param: parameter value to evaluate :param param_compare: Other value(s) to test :paramref:`param` against. Can be an iterable (single value resolved as iterable unless ``None``). To test for ``None`` type, use :paramref:`is_none`/:paramref:`not_none` flags instead. :param param_name: name of the tested parameter returned in response if specified for debugging purposes :param param_content: Additional JSON content to apply to generated error content on raise when :paramref:`with_param` is ``True``. Must be JSON serializable. Provided content can override generated error parameter if matching fields. :param with_param: On raise, adds values of :paramref:`param`, :paramref:`param_name` and :paramref:`param_compare`, as well as additional failing conditions metadata to the JSON response body for each of the corresponding value. :param http_error: derived exception to raise on test failure (default: :class:`HTTPBadRequest`) :param http_kwargs: additional keyword arguments to pass to :paramref:`http_error` called in case of HTTP exception :param msg_on_fail: message details to return in HTTP exception if flag condition failed :param content: json formatted additional content to provide in case of exception :param content_type: format in which to return the exception (one of :py:data:`magpie.common.SUPPORTED_ACCEPT_TYPES`) :param metadata: request metadata to add to the response body. (see: :func:`magpie.api.requests.get_request_info`) :param not_none: test that :paramref:`param` is not ``None`` type :param not_empty: test that :paramref:`param` is not an empty iterable (string, list, set, etc.) :param not_in: test that :paramref:`param` does not exist in :paramref:`param_compare` values :param not_equal: test that :paramref:`param` is not equal to :paramref:`param_compare` value :param is_true: test that :paramref:`param` is ``True`` :param is_false: test that :paramref:`param` is ``False`` :param is_none: test that :paramref:`param` is ``None`` type :param is_empty: test `param` for an empty iterable (string, list, set, etc.) :param is_in: test that :paramref:`param` exists in :paramref:`param_compare` values :param is_equal: test that :paramref:`param` equals :paramref:`param_compare` value :param is_type: test that :paramref:`param` is of same type as specified by :paramref:`param_compare` type :param matches: test that :paramref:`param` matches the regex specified by :paramref:`param_compare` value :raises HTTPError: if tests fail, specified exception is raised (default: :class:`HTTPBadRequest`) :raises HTTPInternalServerError: for evaluation error :return: nothing if all tests passed .. py:data:: ProviderSigninAPI .. py:class:: LooseVersion(version: str) Bases: :py:obj:`packaging.version.Version`, :py:obj:`VersionInterface` This class abstracts handling of a project's versions. A :class:`Version` instance is comparison aware and can be compared and sorted using the standard Python interfaces. >>> v1 = Version("1.0a5") >>> v2 = Version("1.0") >>> v1 >>> v2 >>> v1 < v2 True >>> v1 == v2 False >>> v1 > v2 False >>> v1 >= v2 False >>> v1 <= v2 True Initialize a Version object. :param version: The string representation of a version which will be parsed and normalized before use. :raises InvalidVersion: If the ``version`` does not conform to PEP 440 in any way then this exception will be raised. .. py:property:: version :type: Tuple[Union[int, str], Ellipsis] .. py:property:: patch .. py:method:: _cmp(other: Union[LooseVersion, str]) -> int .. py:function:: get_constant(constant_name: magpie.typedefs.Str, settings_container: Optional[magpie.typedefs.AnySettingsContainer] = None, settings_name: Optional[magpie.typedefs.Str] = None, default_value: Optional[magpie.typedefs.SettingValue] = None, raise_not_set: bool = True, raise_missing: bool = True, print_missing: bool = False, empty_missing: bool = False) -> magpie.typedefs.SettingValue Search in order for matched value of :paramref:`constant_name`: 1. search in :py:data:`MAGPIE_CONSTANTS` 2. search in settings if specified 3. search alternative setting names (see below) 4. search in :mod:`magpie.constants` definitions 5. search in environment variables Parameter :paramref:`constant_name` is expected to have the format ``MAGPIE_[VARIABLE_NAME]`` although any value can be passed to retrieve generic settings from all above-mentioned search locations. If :paramref:`settings_name` is provided as alternative name, it is used as is to search for results if :paramref:`constant_name` was not found. Otherwise, ``magpie.[variable_name]`` is used for additional search when the format ``MAGPIE_[VARIABLE_NAME]`` was used for :paramref:`constant_name` (i.e.: ``MAGPIE_ADMIN_USER`` will also search for ``magpie.admin_user`` and so on for corresponding constants). :param constant_name: key to search for a value :param settings_container: WSGI application settings container (if not provided, uses found one in current thread) :param settings_name: alternative name for `settings` if specified :param default_value: default value to be returned if not found anywhere, and exception raises are disabled. :param raise_not_set: raise an exception if the found key is ``None``, search until last case if others are ``None`` :param raise_missing: raise exception if key is not found anywhere :param print_missing: print message if key is not found anywhere, return ``None`` :param empty_missing: consider an empty value for an existing key as if it was missing (i.e.: as if not set). :returns: found value or `default_value` :raises ValueError: if resulting value is invalid based on options (by default raise missing/empty/``None`` value) :raises LookupError: if no appropriate value could be found from all search locations (according to options) .. py:function:: get_connected_session(request: pyramid.request.Request) -> sqlalchemy.orm.session.Session Retrieve the session attached to the request or recreated it to ensure it is open and within scoped transaction. .. py:class:: Service Bases: :py:obj:`Resource` Resource of `service` type. .. py:attribute:: __tablename__ :value: 'services' .. py:attribute:: resource_id .. py:attribute:: resource_type_name :value: 'service' .. py:attribute:: __mapper_args__ .. py:property:: permissions .. py:property:: url .. py:property:: type Identifier matching ``magpie.services.ServiceInterface.service_type``. .. py:property:: sync_type Identifier matching ``magpie.cli.SyncServiceInterface.sync_type``. .. py:property:: configuration Configuration modifiers for parsing access to resources and permissions. .. seealso:: - :meth:`magpie.services.ServiceInterface.get_config` .. py:method:: by_service_name(service_name, db_session) :staticmethod: .. py:class:: Permission Bases: :py:obj:`magpie.utils.ExtendedEnum` Applicable :term:`Permission` values (names) under certain :term:`Service` and :term:`Resource`. .. py:attribute:: READ :value: 'read' .. py:attribute:: WRITE :value: 'write' .. py:attribute:: ACCESS :value: 'access' .. py:attribute:: BROWSE :value: 'browse' .. py:attribute:: GET_CAPABILITIES :value: 'getcapabilities' .. py:attribute:: GET_MAP :value: 'getmap' .. py:attribute:: GET_FEATURE_INFO :value: 'getfeatureinfo' .. py:attribute:: GET_LEGEND_GRAPHIC :value: 'getlegendgraphic' .. py:attribute:: GET_METADATA :value: 'getmetadata' .. py:attribute:: GET_PROPERTY_VALUE :value: 'getpropertyvalue' .. py:attribute:: GET_FEATURE :value: 'getfeature' .. py:attribute:: GET_FEATURE_WITH_LOCK :value: 'getfeaturewithlock' .. py:attribute:: GET_GML_OBJECT :value: 'getgmlobject' .. py:attribute:: DESCRIBE_FEATURE_TYPE :value: 'describefeaturetype' .. py:attribute:: DESCRIBE_LAYER :value: 'describelayer' .. py:attribute:: DESCRIBE_PROCESS :value: 'describeprocess' .. py:attribute:: EXECUTE :value: 'execute' .. py:attribute:: LOCK_FEATURE :value: 'lockfeature' .. py:attribute:: TRANSACTION :value: 'transaction' .. py:attribute:: CREATE_STORED_QUERY :value: 'createstoredquery' .. py:attribute:: DROP_STORED_QUERY :value: 'dropstoredquery' .. py:attribute:: LIST_STORED_QUERIES :value: 'liststoredqueries' .. py:attribute:: DESCRIBE_STORED_QUERIES :value: 'describestoredqueries' .. py:function:: invalidate_service(service_name: magpie.typedefs.Str) -> None Invalidates any caching reference to the specified service name. .. py:function:: service_factory(service: magpie.models.Service, request: pyramid.request.Request) -> ServiceInterface Retrieve the specific service class from the provided database service entry. .. py:data:: CONTENT_TYPE_JSON :value: 'application/json' .. py:function:: get_authenticate_headers(request: pyramid.request.Request, error_type: magpie.typedefs.Str = 'invalid_token') -> Optional[magpie.typedefs.HeadersType] Obtains all required headers by 401 responses based on executed :paramref:`request`. :param request: request that was sent to attempt authentication or access which must respond with Unauthorized. :param error_type: Additional detail of the cause of error. Must be one of (invalid_request, invalid_token, insufficient_scope). .. py:function:: get_logger(name: magpie.typedefs.Str, level: Optional[int] = None, force_stdout: bool = None, message_format: Optional[magpie.typedefs.Str] = None, datetime_format: Optional[magpie.typedefs.Str] = None) -> logging.Logger Immediately sets the logger level to avoid duplicate log outputs from the `root logger` and `this logger` when `level` is ``logging.NOTSET``. .. py:function:: get_magpie_url(container: Optional[magpie.typedefs.AnySettingsContainer] = None) -> magpie.typedefs.Str Obtains the configured Magpie URL entrypoint based on the various combinations of supported configuration settings. .. seealso:: Documentation section :ref:`config_app_settings` for available setting combinations. :param container: container that provides access to application settings. :return: resolved Magpie URL .. py:function:: get_settings(container: Optional[magpie.typedefs.AnySettingsContainer], app: bool = False) -> magpie.typedefs.SettingsType Retrieve application settings from a supported container. :param container: supported container with a handle to application settings. :param app: allow retrieving from current thread registry if no container was defined. :return: found application settings dictionary. :raise TypeError: when no application settings could be found or unsupported container. .. py:data:: LOGGER .. py:class:: MagpieOWSSecurity(container: magpie.typedefs.AnySettingsContainer) Bases: :py:obj:`twitcher.interface.OWSSecurityInterface` .. py:attribute:: _cached_request :type: Dict[uuid.UUID, pyramid.request.Request] .. py:method:: _get_service_cached(service_name: magpie.typedefs.Str, request_uuid: uuid.UUID) -> Tuple[magpie.services.ServiceInterface, Dict[str, magpie.typedefs.AnyValue]] Cache this method with :py:mod:`beaker` based on the provided caching key parameters. If the cache is not hit (expired timeout or new key entry), calls :func:`service_factory` to retrieve the actual :class:`ServiceInterface` implementation. Otherwise, returns the cached service to avoid SQL queries. .. note:: Function arguments are required to generate caching keys by which cached elements will be retrieved. Those arguments must be serializable to generate the cache key (i.e.: cannot pass a :class:`Request` object that contains session and other unserializable/circular references). .. seealso:: - :meth:`magpie.adapter.magpieowssecurity.MagpieOWSSecurity.get_service` - :meth:`magpie.adapter.magpieservice.MagpieServiceStore.fetch_by_name` .. py:method:: get_service(request: pyramid.request.Request) -> magpie.services.ServiceInterface Obtains the service referenced by the request. Caching is automatically handled according to configured application settings and whether the specific service name being requested was already processed recently and not expired. .. py:method:: verify_request(request: pyramid.request.Request) -> bool Verify that the service request is allowed. .. versionadded:: 3.18 Available only in ``Twitcher >= 0.6.x``. .. py:method:: check_request(request: pyramid.request.Request) -> None Verifies if the request user has access to the targeted resource according to parent service and permissions. If the request path corresponds to configured `Twitcher` proxy, evaluate the :term:`ACL`. Otherwise, ignore request access validation. In the case `Twitcher` proxy path is matched, the :term:`Logged User` **MUST** be allowed access following :term:`Effective Permissions ` resolution via :term:`ACL`. Otherwise, :exception:`OWSAccessForbidden` is raised. Failing to parse the request or any underlying component that raises an exception will be left up to the parent caller to handle the exception. In most typical use case, this means `Twitcher` will raise a generic :exception:`OWSException` with ``NoApplicableCode``, unless the exception was more specifically handled. :raises OWSAccessForbidden: If the user does not have access to the targeted resource under the service. :raises HTTPBadRequest: If a request parsing error was detected when trying to resolve the permission based on the service/resource. :raises Exception: Any derived exception that was not explicitly handled is re-raised directly after logging the event. :returns: Nothing if user has access. .. py:method:: update_request_cookies(request: pyramid.request.Request) -> None Ensure login of the user and update the request cookies if Twitcher is in a special configuration. Only update if ``MAGPIE_COOKIE_NAME`` is missing and is retrievable from ``access_token`` field within the ``Authorization`` header. Counter-validate the login procedure by calling Magpie's ``/session`` which should indicate if there is a logged user.