dynamic-settings-widget 2.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.
- dynamic_settings_widget/__init__.py +56 -0
- dynamic_settings_widget/adapters/__init__.py +42 -0
- dynamic_settings_widget/adapters/base.py +179 -0
- dynamic_settings_widget/adapters/memory.py +201 -0
- dynamic_settings_widget/adapters/runner.py +63 -0
- dynamic_settings_widget/core/__init__.py +1 -0
- dynamic_settings_widget/core/catalog.py +201 -0
- dynamic_settings_widget/core/common.py +214 -0
- dynamic_settings_widget/core/conditions.py +146 -0
- dynamic_settings_widget/core/datatypes.py +414 -0
- dynamic_settings_widget/core/diagnostics.py +69 -0
- dynamic_settings_widget/core/loader.py +101 -0
- dynamic_settings_widget/core/model.py +245 -0
- dynamic_settings_widget/core/overrides.py +353 -0
- dynamic_settings_widget/core/parser.py +552 -0
- dynamic_settings_widget/core/presentation.py +68 -0
- dynamic_settings_widget/core/registry.py +258 -0
- dynamic_settings_widget/core/state.py +314 -0
- dynamic_settings_widget/data/example_catalog.json +23 -0
- dynamic_settings_widget/data/example_layout.json +23 -0
- dynamic_settings_widget/data/settings_catalog.schema.json +388 -0
- dynamic_settings_widget/data/settings_definition.schema.json +1041 -0
- dynamic_settings_widget/data/settings_layout.schema.json +701 -0
- dynamic_settings_widget/data/settings_override.schema.json +406 -0
- dynamic_settings_widget/py.typed +0 -0
- dynamic_settings_widget/session.py +1537 -0
- dynamic_settings_widget/standalone/__init__.py +67 -0
- dynamic_settings_widget/standalone/action_button.py +200 -0
- dynamic_settings_widget/standalone/auth_widget.py +377 -0
- dynamic_settings_widget/standalone/check_box_editor.py +233 -0
- dynamic_settings_widget/standalone/choice_buttons_editor.py +394 -0
- dynamic_settings_widget/standalone/color_editor.py +316 -0
- dynamic_settings_widget/standalone/dropdown_editor.py +356 -0
- dynamic_settings_widget/standalone/editable_label.py +428 -0
- dynamic_settings_widget/standalone/float_spin_box.py +621 -0
- dynamic_settings_widget/standalone/font_editor.py +348 -0
- dynamic_settings_widget/standalone/hotkey_editor.py +681 -0
- dynamic_settings_widget/standalone/info_label.py +190 -0
- dynamic_settings_widget/standalone/int_spin_box.py +627 -0
- dynamic_settings_widget/standalone/multi_choice_editor.py +428 -0
- dynamic_settings_widget/standalone/password_editor.py +348 -0
- dynamic_settings_widget/standalone/path_editor.py +615 -0
- dynamic_settings_widget/standalone/protected_group_box.py +287 -0
- dynamic_settings_widget/standalone/server_connection_editor.py +642 -0
- dynamic_settings_widget/standalone/slider_spin_box.py +840 -0
- dynamic_settings_widget/standalone/sound_selection_widget.py +710 -0
- dynamic_settings_widget/standalone/status_label.py +148 -0
- dynamic_settings_widget/standalone/switch_editor.py +293 -0
- dynamic_settings_widget/standalone/text_editor.py +265 -0
- dynamic_settings_widget/testlab/__init__.py +1 -0
- dynamic_settings_widget/testlab/__main__.py +5 -0
- dynamic_settings_widget/testlab/app.py +699 -0
- dynamic_settings_widget/testlab/assets/extra_sounds/Signal.wav +0 -0
- dynamic_settings_widget/testlab/assets/sounds/Benachrichtigung.wav +0 -0
- dynamic_settings_widget/testlab/assets/sounds/feedback/Signal.wav +0 -0
- dynamic_settings_widget/testlab/definitions/broken_base.json +25 -0
- dynamic_settings_widget/testlab/definitions/demo.json +634 -0
- dynamic_settings_widget/testlab/definitions/gallery.json +255 -0
- dynamic_settings_widget/testlab/definitions/override_example.json +41 -0
- dynamic_settings_widget/testlab/definitions/override_invalid.json +11 -0
- dynamic_settings_widget/testlab/definitions/override_syntax_error.json +5 -0
- dynamic_settings_widget/testlab/definitions/override_weaken.json +10 -0
- dynamic_settings_widget/testlab/definitions/voice_v2/01_left_top.json +1190 -0
- dynamic_settings_widget/testlab/definitions/voice_v2/catalog.json +1930 -0
- dynamic_settings_widget/testlab/definitions/voice_v2/models.json +141 -0
- dynamic_settings_widget/testlab/definitions/voice_v2/wakewords.json +161 -0
- dynamic_settings_widget/testlab/dummy.py +353 -0
- dynamic_settings_widget/testlab/extensions.py +149 -0
- dynamic_settings_widget/testlab/gallery.py +223 -0
- dynamic_settings_widget/testlab/http_adapter.py +430 -0
- dynamic_settings_widget/testlab/http_server.py +493 -0
- dynamic_settings_widget/testlab/voice_v2.py +251 -0
- dynamic_settings_widget/ui/__init__.py +23 -0
- dynamic_settings_widget/ui/base.py +63 -0
- dynamic_settings_widget/ui/builders.py +226 -0
- dynamic_settings_widget/ui/containers.py +441 -0
- dynamic_settings_widget/ui/dialog.py +231 -0
- dynamic_settings_widget/ui/editing.py +51 -0
- dynamic_settings_widget/ui/row.py +810 -0
- dynamic_settings_widget/ui/view.py +248 -0
- dynamic_settings_widget/widgets/__init__.py +74 -0
- dynamic_settings_widget/widgets/base.py +145 -0
- dynamic_settings_widget/widgets/bridge.py +222 -0
- dynamic_settings_widget/widgets/theme.py +107 -0
- dynamic_settings_widget-2.0.0.dist-info/METADATA +237 -0
- dynamic_settings_widget-2.0.0.dist-info/RECORD +90 -0
- dynamic_settings_widget-2.0.0.dist-info/WHEEL +5 -0
- dynamic_settings_widget-2.0.0.dist-info/entry_points.txt +5 -0
- dynamic_settings_widget-2.0.0.dist-info/licenses/LICENSE +21 -0
- dynamic_settings_widget-2.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""Datei- und Mapping-Vertrag für fachliche Kataloge und Layouts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from copy import deepcopy
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
from .common import UNSET
|
|
9
|
+
from .datatypes import CONSTRAINT_FIELDS
|
|
10
|
+
from .diagnostics import Diagnostics
|
|
11
|
+
from .loader import LoadResult, Source, _read, load_definitions
|
|
12
|
+
from .overrides import _PROTECTED_OPTIONS
|
|
13
|
+
from .parser import FORMAT, ID_PATTERN, MAX_DEPTH, check_header, parse_document
|
|
14
|
+
from .registry import TypeRegistry
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from ..adapters.base import AdapterDescription
|
|
18
|
+
|
|
19
|
+
CATALOG_FORMAT = "dynamic-settings-catalog"
|
|
20
|
+
LAYOUT_FORMAT = "dynamic-settings-layout"
|
|
21
|
+
|
|
22
|
+
_FACT_FIELDS = {
|
|
23
|
+
"setting": CONSTRAINT_FIELDS | {"datatype", "bind", "default", "choices_from", "apply", "effect", "actions"},
|
|
24
|
+
"action": {"action", "confirm"},
|
|
25
|
+
"info": {"text", "source"},
|
|
26
|
+
}
|
|
27
|
+
_BINDING_OPTIONS = _PROTECTED_OPTIONS | {"check"}
|
|
28
|
+
_LAYOUT_FIELDS = {"id", "name", "label", "help", "order", "options", "visible", "enabled", "presentation"}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def catalog_from_description(adapter: str, description: AdapterDescription) -> dict:
|
|
32
|
+
"""Statische Katalogmomentaufnahme aus normalisierten Adaptermetadaten."""
|
|
33
|
+
entries = {}
|
|
34
|
+
for key, meta in description.keys.items():
|
|
35
|
+
entry = {
|
|
36
|
+
"type": "setting", "datatype": meta.datatype, "label": meta.label, "description": meta.description,
|
|
37
|
+
"bind": {"adapter": adapter, "key": key}, "read_only": not meta.writable, "effect": meta.effect,
|
|
38
|
+
**{name: deepcopy(value) for name, value in meta.constraints.items() if name in CONSTRAINT_FIELDS},
|
|
39
|
+
}
|
|
40
|
+
if meta.permission:
|
|
41
|
+
entry["permission"] = {"adapter": adapter, "scope": meta.permission}
|
|
42
|
+
if meta.choices_list:
|
|
43
|
+
entry["choices_from"] = {"adapter": adapter, "list": meta.choices_list}
|
|
44
|
+
if meta.default is not UNSET and meta.datatype != "secret":
|
|
45
|
+
entry["default"] = deepcopy(meta.default)
|
|
46
|
+
if meta.datatype == "connection":
|
|
47
|
+
entry.update(apply="manual", read_only=True)
|
|
48
|
+
fact_id = key if ID_PATTERN.fullmatch(key) and key != "root" and not key.startswith(("auto.", "key.")) else (
|
|
49
|
+
"key." + key.encode("utf-8").hex()
|
|
50
|
+
)
|
|
51
|
+
entries[fact_id] = entry
|
|
52
|
+
return {"format": CATALOG_FORMAT, "version": 1, "adapters": {adapter: adapter}, "entries": entries}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _fields(raw, allowed, diag, where):
|
|
56
|
+
for key in raw.keys() - allowed:
|
|
57
|
+
diag.error("catalog-field", f"Feld {key!r} ist hier nicht zulässig", where)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _as_document(catalog, root, layout=None):
|
|
61
|
+
document = {"format": FORMAT, "version": 1, "root": root}
|
|
62
|
+
for name in ("adapters", "default_adapter"):
|
|
63
|
+
if name in catalog:
|
|
64
|
+
document[name] = catalog[name]
|
|
65
|
+
for name in ("title", "description", "presentation"):
|
|
66
|
+
if layout is not None and name in layout:
|
|
67
|
+
document[name] = layout[name]
|
|
68
|
+
return document
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _check_catalog(raw, registry, source):
|
|
72
|
+
diag = Diagnostics(source)
|
|
73
|
+
check_header(raw, CATALOG_FORMAT, diag)
|
|
74
|
+
diag.raise_if_errors()
|
|
75
|
+
_fields(raw, {"format", "version", "$schema", "adapters", "default_adapter", "entries"}, diag, "/")
|
|
76
|
+
entries = raw.get("entries")
|
|
77
|
+
if not isinstance(entries, dict):
|
|
78
|
+
diag.error("catalog", "„entries“ muss ein Objekt mit fachlichen IDs sein")
|
|
79
|
+
diag.raise_if_errors()
|
|
80
|
+
children = []
|
|
81
|
+
for index, (key, entry) in enumerate(entries.items()):
|
|
82
|
+
if not isinstance(key, str) or not ID_PATTERN.fullmatch(key) or key == "root":
|
|
83
|
+
diag.error("catalog-id", f"Ungültige fachliche ID {key!r}")
|
|
84
|
+
continue
|
|
85
|
+
kind = entry.get("type") if isinstance(entry, dict) else None
|
|
86
|
+
if not isinstance(kind, str) or kind not in _FACT_FIELDS:
|
|
87
|
+
diag.error("catalog-type", "Erwartet setting, action oder info", key)
|
|
88
|
+
continue
|
|
89
|
+
allowed = _FACT_FIELDS[kind] | {"type", "label", "description", "permission", "read_only", "options"}
|
|
90
|
+
_fields(entry, allowed, diag, key)
|
|
91
|
+
if "read_only" in entry and type(entry["read_only"]) is not bool:
|
|
92
|
+
diag.error("catalog-field", "„read_only“ muss boolesch sein", key)
|
|
93
|
+
if isinstance(entry.get("options"), dict):
|
|
94
|
+
_fields(entry["options"], _BINDING_OPTIONS, diag, key)
|
|
95
|
+
children.append({**entry, "id": key, "name": f"entry_{index}"})
|
|
96
|
+
diag.raise_if_errors()
|
|
97
|
+
tree, parsed = parse_document(_as_document(raw, {"type": "vbox", "children": children}), registry, source)
|
|
98
|
+
for binding, owners in tree.by_binding.items():
|
|
99
|
+
if sum(owner.is_setting for owner in owners) > 1:
|
|
100
|
+
diag.error("catalog-binding", f"Mehrere fachliche Einstellungen für {binding}")
|
|
101
|
+
diag.raise_if_errors()
|
|
102
|
+
return entries, tree, parsed.items
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _compose(layout, entries, registry, diag):
|
|
106
|
+
references = {}
|
|
107
|
+
materialized = []
|
|
108
|
+
|
|
109
|
+
def resolve(node, where, depth):
|
|
110
|
+
if not isinstance(node, dict) or depth > MAX_DEPTH:
|
|
111
|
+
diag.error("layout-node", "Ungültiger oder zu tief verschachtelter Layoutknoten", where)
|
|
112
|
+
return {}
|
|
113
|
+
if "ref" in node:
|
|
114
|
+
ref = node["ref"]
|
|
115
|
+
if not isinstance(ref, str) or ref not in entries:
|
|
116
|
+
diag.error("catalog-reference", f"Unbekannte fachliche ID {ref!r}", where)
|
|
117
|
+
return {}
|
|
118
|
+
if ref in references:
|
|
119
|
+
diag.error("catalog-reference", f"Mehrfachreferenz auf {ref!r}", where)
|
|
120
|
+
layout_id = node.get("id")
|
|
121
|
+
if not isinstance(layout_id, str):
|
|
122
|
+
diag.error("layout-id", "Referenz benötigt eine eigene Layout-ID", where)
|
|
123
|
+
references[ref] = layout_id
|
|
124
|
+
entry = entries[ref]
|
|
125
|
+
_fields(node, _LAYOUT_FIELDS | {"ref", "widget"}, diag, where)
|
|
126
|
+
if "widget" in node and entry["type"] != "setting":
|
|
127
|
+
diag.error("layout-widget", "Editorwahl ist nur für Einstellungen zulässig", where)
|
|
128
|
+
visual = node.get("options", {})
|
|
129
|
+
if isinstance(visual, dict) and (protected := visual.keys() & _BINDING_OPTIONS):
|
|
130
|
+
diag.error("protected-field", f"Fachliche Optionen im Layout: {', '.join(sorted(protected))}", where)
|
|
131
|
+
merged = deepcopy(entry)
|
|
132
|
+
merged.update({key: val for key, val in node.items() if key not in ("ref", "options")})
|
|
133
|
+
if "options" in node:
|
|
134
|
+
merged["options"] = {**entry.get("options", {}), **visual} if isinstance(visual, dict) else visual
|
|
135
|
+
materialized.append(merged)
|
|
136
|
+
return merged
|
|
137
|
+
kind = node.get("type")
|
|
138
|
+
element_type = registry.elements.get(kind) if isinstance(kind, str) else None
|
|
139
|
+
if element_type is None or element_type.family not in ("container", "custom"):
|
|
140
|
+
diag.error("layout-node", f"{kind!r} benötigt einen Katalogverweis oder einen registrierten Container", where)
|
|
141
|
+
return {}
|
|
142
|
+
_fields(node, (_LAYOUT_FIELDS | {"type", "children", "description", "auth", "read_only", "permission"}
|
|
143
|
+
| set(element_type.fields)) - {"catch_all"}, diag, where)
|
|
144
|
+
merged = dict(node)
|
|
145
|
+
if "children" in node:
|
|
146
|
+
if isinstance(node["children"], list):
|
|
147
|
+
merged["children"] = [resolve(child, f"{where}/{i}", depth + 1)
|
|
148
|
+
for i, child in enumerate(node["children"])]
|
|
149
|
+
else:
|
|
150
|
+
diag.error("layout-node", "„children“ muss eine Liste sein", where)
|
|
151
|
+
return merged
|
|
152
|
+
|
|
153
|
+
root = resolve(layout.get("root"), "/root", 0)
|
|
154
|
+
diag.raise_if_errors()
|
|
155
|
+
|
|
156
|
+
def layout_id(ref):
|
|
157
|
+
if ref not in references:
|
|
158
|
+
diag.error("catalog-reference", f"Die fachliche Referenz {ref!r} benötigt eine Platzierung im Layout")
|
|
159
|
+
return references.get(ref, ref)
|
|
160
|
+
|
|
161
|
+
for node in materialized:
|
|
162
|
+
source = node.get("source", {})
|
|
163
|
+
if "action_result" in source:
|
|
164
|
+
source["action_result"] = layout_id(source["action_result"])
|
|
165
|
+
for action in [node.get("action"), *node.get("actions", {}).values()]:
|
|
166
|
+
if isinstance(action, dict) and "params_from" in action:
|
|
167
|
+
action["params_from"] = {key: layout_id(value) for key, value in action["params_from"].items()}
|
|
168
|
+
diag.raise_if_errors()
|
|
169
|
+
return root
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def load_catalog_layout(
|
|
173
|
+
catalog: Source, layout: Source, override=None, *, registry: TypeRegistry, use_env: bool = True,
|
|
174
|
+
) -> LoadResult:
|
|
175
|
+
"""Lädt zwei unabhängige Quellen in ein kombiniertes DSW-v1-Dokument samt Diagnosen."""
|
|
176
|
+
raw_catalog, catalog_name = _read(catalog)
|
|
177
|
+
entries, facts, catalog_diagnostics = _check_catalog(raw_catalog, registry, catalog_name)
|
|
178
|
+
raw_layout, layout_name = _read(layout)
|
|
179
|
+
diag = Diagnostics(layout_name)
|
|
180
|
+
check_header(raw_layout, LAYOUT_FORMAT, diag)
|
|
181
|
+
diag.raise_if_errors()
|
|
182
|
+
_fields(raw_layout, {"$schema", "format", "version", "title", "description", "presentation", "root"}, diag, "/")
|
|
183
|
+
root = _compose(raw_layout, entries, registry, diag)
|
|
184
|
+
known_actions = {(ref.adapter, ref.name) for node in facts.walk() for ref in node.action_refs()}
|
|
185
|
+
|
|
186
|
+
def validate_override(tree, diagnostics):
|
|
187
|
+
for node in tree.walk():
|
|
188
|
+
if node.origin != "override":
|
|
189
|
+
continue
|
|
190
|
+
if node.bind in facts.by_binding or any(
|
|
191
|
+
(ref.adapter, ref.name) in known_actions for ref in node.action_refs()
|
|
192
|
+
):
|
|
193
|
+
diagnostics.error("catalog-binding", "Katalogbindung oder -aktion kann nicht erneut angelegt werden", node.path)
|
|
194
|
+
if node.catch_all:
|
|
195
|
+
diagnostics.error("catalog-binding", "Auffanggruppen sind in Kataloglayouts nicht zulässig", node.path)
|
|
196
|
+
|
|
197
|
+
result = load_definitions(_as_document(raw_catalog, root, raw_layout), override, registry=registry,
|
|
198
|
+
use_env=use_env, _validate_override=validate_override)
|
|
199
|
+
result.base_source = layout_name
|
|
200
|
+
result.diagnostics[:0] = catalog_diagnostics
|
|
201
|
+
return result
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"""Grundbausteine: UNSET-Marke, Geheimwerte und Redaktion."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hmac
|
|
6
|
+
import json
|
|
7
|
+
import re
|
|
8
|
+
import threading
|
|
9
|
+
from collections.abc import Mapping
|
|
10
|
+
from enum import Enum
|
|
11
|
+
from typing import Any
|
|
12
|
+
from urllib.parse import quote, quote_plus
|
|
13
|
+
|
|
14
|
+
REDACTED = "•••"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class _Unset:
|
|
18
|
+
"""Eindeutige Marke für „kein Wert bekannt“ (``None`` ist ein gültiger Wert)."""
|
|
19
|
+
|
|
20
|
+
_instance: "_Unset | None" = None
|
|
21
|
+
|
|
22
|
+
def __new__(cls) -> "_Unset":
|
|
23
|
+
if cls._instance is None:
|
|
24
|
+
cls._instance = super().__new__(cls)
|
|
25
|
+
return cls._instance
|
|
26
|
+
|
|
27
|
+
def __bool__(self) -> bool:
|
|
28
|
+
return False
|
|
29
|
+
|
|
30
|
+
def __repr__(self) -> str:
|
|
31
|
+
return "<UNSET>"
|
|
32
|
+
|
|
33
|
+
def __copy__(self) -> "_Unset":
|
|
34
|
+
return self
|
|
35
|
+
|
|
36
|
+
def __deepcopy__(self, memo: dict) -> "_Unset":
|
|
37
|
+
return self
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
UNSET = _Unset()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class SecretValue:
|
|
44
|
+
"""Kapselt einen Geheimwert, sodass er nicht versehentlich ausgegeben wird.
|
|
45
|
+
|
|
46
|
+
Nur :meth:`reveal` liefert den Klartext; ``repr``/``str``/``format`` nicht.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
__slots__ = ("__text",)
|
|
50
|
+
|
|
51
|
+
def __init__(self, text: str) -> None:
|
|
52
|
+
if not isinstance(text, str):
|
|
53
|
+
raise TypeError("SecretValue erwartet Text")
|
|
54
|
+
self.__text = text
|
|
55
|
+
|
|
56
|
+
def reveal(self) -> str:
|
|
57
|
+
return self.__text
|
|
58
|
+
|
|
59
|
+
def __bool__(self) -> bool:
|
|
60
|
+
return bool(self.__text)
|
|
61
|
+
|
|
62
|
+
def __len__(self) -> int:
|
|
63
|
+
return len(self.__text)
|
|
64
|
+
|
|
65
|
+
def __eq__(self, other: object) -> bool:
|
|
66
|
+
if not isinstance(other, SecretValue):
|
|
67
|
+
return NotImplemented
|
|
68
|
+
return hmac.compare_digest(self.__text.encode(), other.__text.encode())
|
|
69
|
+
|
|
70
|
+
def __hash__(self) -> int:
|
|
71
|
+
return hash(("SecretValue", self.__text))
|
|
72
|
+
|
|
73
|
+
def __repr__(self) -> str:
|
|
74
|
+
return f"<SecretValue {REDACTED}>"
|
|
75
|
+
|
|
76
|
+
__str__ = __repr__
|
|
77
|
+
|
|
78
|
+
def __reduce__(self): # kein Pickle → keine versehentliche Speicherung
|
|
79
|
+
raise TypeError("SecretValue ist nicht serialisierbar")
|
|
80
|
+
|
|
81
|
+
def __copy__(self) -> "SecretValue":
|
|
82
|
+
return self
|
|
83
|
+
|
|
84
|
+
def __deepcopy__(self, memo: dict) -> "SecretValue":
|
|
85
|
+
return self
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class _SecretStored:
|
|
89
|
+
"""Marke: Beim Adapter ist ein Geheimwert hinterlegt, sein Inhalt ist unbekannt."""
|
|
90
|
+
|
|
91
|
+
def __repr__(self) -> str:
|
|
92
|
+
return "<gesetzt>"
|
|
93
|
+
|
|
94
|
+
def __copy__(self) -> "_SecretStored":
|
|
95
|
+
return self
|
|
96
|
+
|
|
97
|
+
def __deepcopy__(self, memo: dict) -> "_SecretStored":
|
|
98
|
+
return self
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
SECRET_SET = _SecretStored()
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
#: Ersatz für eine Meldung, die einen kurzen Geheimwert enthalten könnte.
|
|
105
|
+
WITHHELD = "Meldung ausgeblendet – sie könnte Zugangsdaten enthalten"
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class Redactor:
|
|
109
|
+
"""Entfernt bekannte Geheimwerte aus Texten und Strukturen.
|
|
110
|
+
|
|
111
|
+
Schutz auf drei Wegen:
|
|
112
|
+
|
|
113
|
+
* sensible Feldnamen werden unabhängig vom Inhalt geschwärzt;
|
|
114
|
+
* jeder der Sitzung bekannt gewordene Geheimtext ab ``_MIN_LENGTH`` Zeichen wird in
|
|
115
|
+
beliebigen Texten ersetzt (auch URL-/JSON-kodiert);
|
|
116
|
+
* kürzere Geheimtexte (1–2 Zeichen) lassen sich nicht sinnvoll einzeln ersetzen, ohne
|
|
117
|
+
den Text unlesbar zu machen. Enthält ein Text einen davon, wird stattdessen die
|
|
118
|
+
**ganze Meldung** durch einen generischen Text ersetzt: bei Freitext von außen
|
|
119
|
+
(:meth:`scrub_message`, z. B. Adapterantworten) schon bei jedem Vorkommen, sonst
|
|
120
|
+
(:meth:`scrub_text`) bei einem Vorkommen als eigenständiges Wort.
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
_SENSITIVE_NAME = re.compile(
|
|
124
|
+
r"passw(or[dt])?|passphrase|secret|geheim|token|credential|zugangsdaten"
|
|
125
|
+
r"|api[_-]?key|admin[_-]?key|access[_-]?key|auth[_-]?key|authorization",
|
|
126
|
+
re.IGNORECASE,
|
|
127
|
+
)
|
|
128
|
+
_MIN_LENGTH = 3
|
|
129
|
+
|
|
130
|
+
def __init__(self) -> None:
|
|
131
|
+
self._needles: set[str] = set()
|
|
132
|
+
self._short: set[str] = set()
|
|
133
|
+
self._lock = threading.Lock()
|
|
134
|
+
|
|
135
|
+
def register(self, secret: SecretValue | str) -> None:
|
|
136
|
+
text = secret.reveal() if isinstance(secret, SecretValue) else secret
|
|
137
|
+
if not text:
|
|
138
|
+
return
|
|
139
|
+
variants = {
|
|
140
|
+
text,
|
|
141
|
+
json.dumps(text)[1:-1],
|
|
142
|
+
json.dumps(text, ensure_ascii=False)[1:-1],
|
|
143
|
+
repr(text)[1:-1],
|
|
144
|
+
quote(text, safe=""),
|
|
145
|
+
quote_plus(text),
|
|
146
|
+
}
|
|
147
|
+
with self._lock:
|
|
148
|
+
for variant in variants:
|
|
149
|
+
if len(variant) >= self._MIN_LENGTH:
|
|
150
|
+
self._needles.add(variant)
|
|
151
|
+
elif variant:
|
|
152
|
+
self._short.add(variant.casefold())
|
|
153
|
+
|
|
154
|
+
def _contains_short(self, text: str, *, anywhere: bool) -> bool:
|
|
155
|
+
with self._lock:
|
|
156
|
+
shorts = list(self._short)
|
|
157
|
+
if not shorts or not text:
|
|
158
|
+
return False
|
|
159
|
+
folded = text.casefold()
|
|
160
|
+
for short in shorts:
|
|
161
|
+
if anywhere:
|
|
162
|
+
if short in folded:
|
|
163
|
+
return True
|
|
164
|
+
elif re.search(rf"(?<!\w){re.escape(short)}(?!\w)", folded):
|
|
165
|
+
return True
|
|
166
|
+
return False
|
|
167
|
+
|
|
168
|
+
def scrub_text(self, text: str) -> str:
|
|
169
|
+
"""Ersetzt bekannte Geheimtexte; ein kurzer Geheimwert als eigenes Wort verbirgt die ganze Meldung."""
|
|
170
|
+
with self._lock:
|
|
171
|
+
needles = sorted(self._needles, key=len, reverse=True)
|
|
172
|
+
for needle in needles:
|
|
173
|
+
if needle in text:
|
|
174
|
+
text = text.replace(needle, REDACTED)
|
|
175
|
+
if self._contains_short(text, anywhere=False):
|
|
176
|
+
return WITHHELD
|
|
177
|
+
return text
|
|
178
|
+
|
|
179
|
+
def scrub_message(self, text: str, fallback: str = WITHHELD) -> str:
|
|
180
|
+
"""Für Freitext von außen (Adapterantworten, Fehlertexte): enthält er einen kurzen
|
|
181
|
+
Geheimwert an beliebiger Stelle, wird er vollständig durch ``fallback`` ersetzt."""
|
|
182
|
+
if self._contains_short(text, anywhere=True):
|
|
183
|
+
return fallback
|
|
184
|
+
return self.scrub_text(text)
|
|
185
|
+
|
|
186
|
+
def redact(self, obj: Any, *, strict: bool = False) -> Any:
|
|
187
|
+
"""Liefert eine JSON-taugliche, geschwärzte Kopie.
|
|
188
|
+
|
|
189
|
+
``strict`` für Daten von außen (z. B. Aktionsergebnisse eines Adapters): Texte werden
|
|
190
|
+
wie mit :meth:`scrub_message` behandelt.
|
|
191
|
+
"""
|
|
192
|
+
scrub = self.scrub_message if strict else self.scrub_text
|
|
193
|
+
if isinstance(obj, SecretValue):
|
|
194
|
+
return REDACTED
|
|
195
|
+
if obj is SECRET_SET:
|
|
196
|
+
return "<gesetzt>"
|
|
197
|
+
if obj is UNSET:
|
|
198
|
+
return None
|
|
199
|
+
if isinstance(obj, Enum):
|
|
200
|
+
return self.redact(obj.value, strict=strict)
|
|
201
|
+
if isinstance(obj, Mapping):
|
|
202
|
+
out: dict[str, Any] = {}
|
|
203
|
+
for key, value in obj.items():
|
|
204
|
+
name = scrub(str(key))
|
|
205
|
+
sensitive = self._SENSITIVE_NAME.search(name) and isinstance(value, (str, SecretValue, bytes, list))
|
|
206
|
+
out[name] = REDACTED if sensitive else self.redact(value, strict=strict)
|
|
207
|
+
return out
|
|
208
|
+
if isinstance(obj, (list, tuple, set, frozenset)):
|
|
209
|
+
return [self.redact(item, strict=strict) for item in obj]
|
|
210
|
+
if isinstance(obj, str):
|
|
211
|
+
return scrub(obj)
|
|
212
|
+
if obj is None or isinstance(obj, (bool, int, float)):
|
|
213
|
+
return obj
|
|
214
|
+
return scrub(repr(obj))
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Deklarative Bedingungen – reine Daten, keine Ausdrücke, kein ``eval``.
|
|
2
|
+
|
|
3
|
+
Formen::
|
|
4
|
+
|
|
5
|
+
true | false
|
|
6
|
+
{"all": [..]} {"any": [..]} {"not": {..}}
|
|
7
|
+
{"setting": "<element-id>", "<operator>": <vergleich>, "of": "draft|requested|effective"}
|
|
8
|
+
{"permission": {"adapter": "a", "scope": "s"}}
|
|
9
|
+
{"adapter": "a", "status": "online|offline|unknown"}
|
|
10
|
+
|
|
11
|
+
Vergleiche mit nicht verfügbaren Werten sind immer falsch.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from collections.abc import Callable, Iterator
|
|
17
|
+
from typing import Any, Protocol
|
|
18
|
+
|
|
19
|
+
from .common import SECRET_SET, UNSET, SecretValue
|
|
20
|
+
from .datatypes import same
|
|
21
|
+
|
|
22
|
+
Condition = bool | dict[str, Any]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ConditionEnvironment(Protocol):
|
|
26
|
+
def condition_value(self, element_id: str, of: str) -> Any: ...
|
|
27
|
+
|
|
28
|
+
def permission_granted(self, adapter: str, scope: str) -> bool: ...
|
|
29
|
+
|
|
30
|
+
def adapter_status_name(self, adapter: str) -> str: ...
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _ordered(compare: Callable[[Any, Any], bool]) -> Callable[[Any, Any], bool]:
|
|
34
|
+
def check(value: Any, expected: Any) -> bool:
|
|
35
|
+
if isinstance(value, bool) or isinstance(expected, bool):
|
|
36
|
+
return False
|
|
37
|
+
try:
|
|
38
|
+
return bool(compare(value, expected))
|
|
39
|
+
except TypeError:
|
|
40
|
+
return False
|
|
41
|
+
|
|
42
|
+
return check
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
OPERATORS: dict[str, Callable[[Any, Any], bool]] = {
|
|
46
|
+
"equals": same,
|
|
47
|
+
"not_equals": lambda v, e: not same(v, e),
|
|
48
|
+
"in": lambda v, e: any(same(v, x) for x in e),
|
|
49
|
+
"not_in": lambda v, e: not any(same(v, x) for x in e),
|
|
50
|
+
"gt": _ordered(lambda v, e: v > e),
|
|
51
|
+
"gte": _ordered(lambda v, e: v >= e),
|
|
52
|
+
"lt": _ordered(lambda v, e: v < e),
|
|
53
|
+
"lte": _ordered(lambda v, e: v <= e),
|
|
54
|
+
"contains": lambda v, e: isinstance(v, list) and any(same(x, e) for x in v),
|
|
55
|
+
"truthy": lambda v, e: bool(v) is e,
|
|
56
|
+
"is_set": lambda v, e: (v is not None) is e,
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
STATUS_NAMES = ("unknown", "online", "offline")
|
|
60
|
+
VALUE_SOURCES = ("draft", "requested", "effective")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def check_condition(raw: Any) -> list[str]:
|
|
64
|
+
"""Prüft die Form einer Bedingung; liefert Fehlermeldungen."""
|
|
65
|
+
if isinstance(raw, bool):
|
|
66
|
+
return []
|
|
67
|
+
if not isinstance(raw, dict) or not raw:
|
|
68
|
+
return [f"Bedingung muss true, false oder ein Objekt sein, ist aber {raw!r}"]
|
|
69
|
+
keys = set(raw)
|
|
70
|
+
for group in ("all", "any"):
|
|
71
|
+
if group in raw:
|
|
72
|
+
if keys != {group} or not isinstance(raw[group], list) or not raw[group]:
|
|
73
|
+
return [f"„{group}“ erwartet als einziges Feld eine nicht leere Liste"]
|
|
74
|
+
return [error for item in raw[group] for error in check_condition(item)]
|
|
75
|
+
if "not" in raw:
|
|
76
|
+
return ["„not“ muss allein stehen"] if keys != {"not"} else check_condition(raw["not"])
|
|
77
|
+
if "setting" in raw:
|
|
78
|
+
if not isinstance(raw["setting"], str) or raw["setting"].startswith("/"):
|
|
79
|
+
return ["„setting“ erwartet eine Element-ID (keinen Layoutpfad)"]
|
|
80
|
+
ops = keys - {"setting", "of"}
|
|
81
|
+
if len(ops) != 1 or not ops <= OPERATORS.keys():
|
|
82
|
+
return [f"Genau ein Operator erwartet ({', '.join(OPERATORS)}), gefunden: {sorted(ops) or 'keiner'}"]
|
|
83
|
+
if raw.get("of", "draft") not in VALUE_SOURCES:
|
|
84
|
+
return [f"„of“ muss eines von {', '.join(VALUE_SOURCES)} sein"]
|
|
85
|
+
op = next(iter(ops))
|
|
86
|
+
if op in ("in", "not_in") and not isinstance(raw[op], list):
|
|
87
|
+
return [f"Operator „{op}“ erwartet eine Liste"]
|
|
88
|
+
if op in ("truthy", "is_set") and not isinstance(raw[op], bool):
|
|
89
|
+
return [f"Operator „{op}“ erwartet true oder false"]
|
|
90
|
+
return []
|
|
91
|
+
if "permission" in raw:
|
|
92
|
+
ref = raw["permission"]
|
|
93
|
+
if (
|
|
94
|
+
keys != {"permission"}
|
|
95
|
+
or not isinstance(ref, dict)
|
|
96
|
+
or set(ref) != {"adapter", "scope"}
|
|
97
|
+
or not all(isinstance(v, str) for v in ref.values())
|
|
98
|
+
):
|
|
99
|
+
return ["„permission“ erwartet {adapter, scope}"]
|
|
100
|
+
return []
|
|
101
|
+
if "adapter" in raw:
|
|
102
|
+
if keys != {"adapter", "status"} or not isinstance(raw["adapter"], str) or raw["status"] not in STATUS_NAMES:
|
|
103
|
+
return [f"Adapterbedingung erwartet adapter und status ({', '.join(STATUS_NAMES)})"]
|
|
104
|
+
return []
|
|
105
|
+
return [f"Unbekannte Bedingung mit Feldern {sorted(keys)}"]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def walk(raw: Any) -> Iterator[dict[str, Any]]:
|
|
109
|
+
"""Alle elementaren Bedingungen (Blätter)."""
|
|
110
|
+
if not isinstance(raw, dict):
|
|
111
|
+
return
|
|
112
|
+
for group in ("all", "any"):
|
|
113
|
+
if group in raw:
|
|
114
|
+
for item in raw[group]:
|
|
115
|
+
yield from walk(item)
|
|
116
|
+
return
|
|
117
|
+
if "not" in raw:
|
|
118
|
+
yield from walk(raw["not"])
|
|
119
|
+
return
|
|
120
|
+
yield raw
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def mentions_permission(raw: Any) -> bool:
|
|
124
|
+
return any("permission" in leaf for leaf in walk(raw))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def evaluate(raw: Condition, env: ConditionEnvironment) -> bool:
|
|
128
|
+
if isinstance(raw, bool):
|
|
129
|
+
return raw
|
|
130
|
+
if "all" in raw:
|
|
131
|
+
return all(evaluate(item, env) for item in raw["all"])
|
|
132
|
+
if "any" in raw:
|
|
133
|
+
return any(evaluate(item, env) for item in raw["any"])
|
|
134
|
+
if "not" in raw:
|
|
135
|
+
return not evaluate(raw["not"], env)
|
|
136
|
+
if "permission" in raw:
|
|
137
|
+
return env.permission_granted(raw["permission"]["adapter"], raw["permission"]["scope"])
|
|
138
|
+
if "adapter" in raw:
|
|
139
|
+
return env.adapter_status_name(raw["adapter"]) == raw["status"]
|
|
140
|
+
value = env.condition_value(raw["setting"], raw.get("of", "draft"))
|
|
141
|
+
if value is UNSET:
|
|
142
|
+
return False
|
|
143
|
+
op = next(k for k in raw if k in OPERATORS)
|
|
144
|
+
if (isinstance(value, SecretValue) or value is SECRET_SET) and op not in ("truthy", "is_set"):
|
|
145
|
+
return False
|
|
146
|
+
return OPERATORS[op](value, raw[op])
|