Source code for bragi_quantum.gui.registry

# ══════════════════════════════════════════════════════════════════════════
#     ___   ___ ___   _      _   ___
#    / _ \ / __|_  ) | |    /_\ | _ )
#   | (_) | (__ / /  | |__ / _ \| _ \
#    \__\_\\___/___| |____/_/ \_\___/
#
#   QC2 @ CHALMERS CALIBRATION TOOLKIT
#   (c) 2026 Chalmers University of Technology and Project Contributors
# ──────────────────────────────────────────────────────────────────────────
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       https://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
# ──────────────────────────────────────────────────────────────────────────
#   CONTRIBUTORS list:
#
#   Matteo Robbiati, robbiati@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


"""
Allowlist for dynamic imports.

The replot server has to import analysis / parameters / QOI classes whose
fully qualified names come from a JSON file on disk (the session timeline).
A malformed or tampered timeline could otherwise be used to import arbitrary
code. We restrict imports to a fixed set of trusted top-level packages.
"""

from importlib import import_module
from typing import Any

ALLOWED_ROOTS: tuple[str, ...] = (
    "bragi_quantum.experiments.",
    "bragi_quantum.api.",
    "bragi_quantum.datalayer.",
    "bragi_quantum.gui.",
)


[docs] class DisallowedImportError(ImportError): """Raised when a dotted name is not under an allowed root."""
def _check_allowed(dotted: str) -> None: if not isinstance(dotted, str) or not dotted: raise DisallowedImportError(f"empty / non-string module name: {dotted!r}") for prefix in ALLOWED_ROOTS: # Allow exact root match (e.g. "bragi_quantum.experiments") and any submodule. if dotted == prefix.rstrip(".") or dotted.startswith(prefix): return raise DisallowedImportError( f"module {dotted!r} is not under an allowed root ({', '.join(ALLOWED_ROOTS)})" )
[docs] def safe_import_class(module_name: str, qualname: str) -> Any: """ Import `qualname` from `module_name`, refusing to import anything outside the allowed roots. Supports dotted qualnames like 'Outer.Inner'. """ _check_allowed(module_name) mod = import_module(module_name) obj: Any = mod for part in qualname.split("."): obj = getattr(obj, part) return obj